diff --git a/GIGA.xcodeproj/project.pbxproj b/GIGA.xcodeproj/project.pbxproj index f321da7..0d16e9a 100644 --- a/GIGA.xcodeproj/project.pbxproj +++ b/GIGA.xcodeproj/project.pbxproj @@ -7,6 +7,25 @@ objects = { /* Begin PBXBuildFile section */ + 6B67B068A469498C38CEF799 /* Pods_GIGA.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B14B65914FBF61910191D7A8 /* Pods_GIGA.framework */; }; + 83346AC0212BB50A0054D597 /* PassWordResetVC.m in Sources */ = {isa = PBXBuildFile; fileRef = 83346ABE212BB50A0054D597 /* PassWordResetVC.m */; }; + 83346AC1212BB50A0054D597 /* PassWordResetVC.xib in Resources */ = {isa = PBXBuildFile; fileRef = 83346ABF212BB50A0054D597 /* PassWordResetVC.xib */; }; + 83346AC5212BBC8C0054D597 /* GiGaRegistViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 83346AC3212BBC8C0054D597 /* GiGaRegistViewController.m */; }; + 83346AC6212BBC8C0054D597 /* GiGaRegistViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 83346AC4212BBC8C0054D597 /* GiGaRegistViewController.xib */; }; + 83346ACE212BD7830054D597 /* GiGaWebViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 83346ACC212BD7830054D597 /* GiGaWebViewController.m */; }; + 83346ACF212BD7830054D597 /* GiGaWebViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 83346ACD212BD7830054D597 /* GiGaWebViewController.xib */; }; + 83346AD1212BF5B70054D597 /* useragreement.html in Resources */ = {isa = PBXBuildFile; fileRef = 83346AD0212BF5B70054D597 /* useragreement.html */; }; + 83346AD4212BFF6E0054D597 /* UserGuardViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 83346AD3212BFF6E0054D597 /* UserGuardViewController.m */; }; + 83346AD7212C18F50054D597 /* GiGaAppGaurdVC.m in Sources */ = {isa = PBXBuildFile; fileRef = 83346AD6212C18F50054D597 /* GiGaAppGaurdVC.m */; }; + 833DA7762122A62000A5C614 /* GiGaMaskTaskViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 833DA7752122A62000A5C614 /* GiGaMaskTaskViewController.m */; }; + 8349585C212511040064DB6C /* AppDelegate+ThirdParty.m in Sources */ = {isa = PBXBuildFile; fileRef = 8349585B212511040064DB6C /* AppDelegate+ThirdParty.m */; }; + 8357ADC52123BEBD000816F2 /* GiGaUser.m in Sources */ = {isa = PBXBuildFile; fileRef = 8357ADC42123BEBD000816F2 /* GiGaUser.m */; }; + 8357ADC92123BFCA000816F2 /* GiGaUserManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 8357ADC82123BFCA000816F2 /* GiGaUserManager.m */; }; + 8357ADCD2123C091000816F2 /* GiGaNetManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 8357ADCC2123C091000816F2 /* GiGaNetManager.m */; }; + 8357ADD02123C5F7000816F2 /* GiGaAPIRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 8357ADCF2123C5F7000816F2 /* GiGaAPIRequest.m */; }; + 8357ADD32123C7C6000816F2 /* GiGaAPIResult.m in Sources */ = {isa = PBXBuildFile; fileRef = 8357ADD22123C7C6000816F2 /* GiGaAPIResult.m */; }; + 8357ADD52123F5EC000816F2 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 8357ADD42123F5EC000816F2 /* libsqlite3.tbd */; }; + 8357ADD82124027D000816F2 /* GiGaUserDefault.m in Sources */ = {isa = PBXBuildFile; fileRef = 8357ADD72124027D000816F2 /* GiGaUserDefault.m */; }; 8361B3CB212155C200238FEB /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 8361B3CA212155C200238FEB /* AppDelegate.m */; }; 8361B3CE212155C200238FEB /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 8361B3CD212155C200238FEB /* ViewController.m */; }; 8361B3D1212155C200238FEB /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8361B3CF212155C200238FEB /* Main.storyboard */; }; @@ -15,6 +34,32 @@ 8361B3D9212155C300238FEB /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 8361B3D8212155C300238FEB /* main.m */; }; 8361B3E3212155C300238FEB /* GIGATests.m in Sources */ = {isa = PBXBuildFile; fileRef = 8361B3E2212155C300238FEB /* GIGATests.m */; }; 8361B3EE212155C300238FEB /* GIGAUITests.m in Sources */ = {isa = PBXBuildFile; fileRef = 8361B3ED212155C300238FEB /* GIGAUITests.m */; }; + 8361B40421215E0C00238FEB /* LXCountTimer.m in Sources */ = {isa = PBXBuildFile; fileRef = 8361B40221215E0C00238FEB /* LXCountTimer.m */; }; + 8361B40721215E6F00238FEB /* GiGaHelper.m in Sources */ = {isa = PBXBuildFile; fileRef = 8361B40621215E6F00238FEB /* GiGaHelper.m */; }; + 8361B40B21217B2100238FEB /* AppDelegate+GiGaConfig.m in Sources */ = {isa = PBXBuildFile; fileRef = 8361B40A21217B2100238FEB /* AppDelegate+GiGaConfig.m */; }; + 8361B40D21217C8200238FEB /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8361B40C21217C8200238FEB /* CFNetwork.framework */; }; + 8361B40F21217C9200238FEB /* CoreFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8361B40E21217C9100238FEB /* CoreFoundation.framework */; }; + 8361B41121217CA100238FEB /* CoreTelephony.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8361B41021217CA100238FEB /* CoreTelephony.framework */; }; + 8361B41321217D7E00238FEB /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8361B41221217D7E00238FEB /* SystemConfiguration.framework */; }; + 8361B41521217D9200238FEB /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8361B41421217D9200238FEB /* CoreGraphics.framework */; }; + 8361B41721217DA000238FEB /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8361B41621217DA000238FEB /* Foundation.framework */; }; + 8361B41921217DAD00238FEB /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8361B41821217DAD00238FEB /* UIKit.framework */; }; + 8361B41B21217DBA00238FEB /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8361B41A21217DBA00238FEB /* Security.framework */; }; + 8361B41D21217DCD00238FEB /* libz.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 8361B41C21217DCD00238FEB /* libz.tbd */; }; + 8361B41F21217DDF00238FEB /* AdSupport.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8361B41E21217DDF00238FEB /* AdSupport.framework */; }; + 8361B42121217DF000238FEB /* UserNotifications.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8361B42021217DF000238FEB /* UserNotifications.framework */; }; + 8361B42321217DFF00238FEB /* libresolv.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 8361B42221217DFF00238FEB /* libresolv.tbd */; }; + 8361B42E2121812000238FEB /* GiGaServerConfig.m in Sources */ = {isa = PBXBuildFile; fileRef = 8361B42D2121812000238FEB /* GiGaServerConfig.m */; }; + 8361B4322121832800238FEB /* GiGaBaseViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 8361B4312121832800238FEB /* GiGaBaseViewController.m */; }; + 8361B4352121836700238FEB /* GiGaBaseNavViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 8361B4342121836700238FEB /* GiGaBaseNavViewController.m */; }; + 8361B4382121847600238FEB /* UINavigationBar+Custom.m in Sources */ = {isa = PBXBuildFile; fileRef = 8361B4372121847600238FEB /* UINavigationBar+Custom.m */; }; + 83A2270C212A97ED00B3E75C /* MaskViewBootomWaringView.m in Sources */ = {isa = PBXBuildFile; fileRef = 83A2270B212A97ED00B3E75C /* MaskViewBootomWaringView.m */; }; + 83A22712212A9EA900B3E75C /* UIView+Sizes.m in Sources */ = {isa = PBXBuildFile; fileRef = 83A22710212A9EA900B3E75C /* UIView+Sizes.m */; }; + 83A22718212ABDFF00B3E75C /* GiGaBlockButton.m in Sources */ = {isa = PBXBuildFile; fileRef = 83A22717212ABDFF00B3E75C /* GiGaBlockButton.m */; }; + 83A2271F212AC8C100B3E75C /* GiGaUserLoginVC.m in Sources */ = {isa = PBXBuildFile; fileRef = 83A2271D212AC8C100B3E75C /* GiGaUserLoginVC.m */; }; + 83A22720212AC8C100B3E75C /* GiGaUserLoginVC.xib in Resources */ = {isa = PBXBuildFile; fileRef = 83A2271E212AC8C100B3E75C /* GiGaUserLoginVC.xib */; }; + 83E40B2B21218B6F008149C4 /* GiGaExercisesViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 83E40B2A21218B6F008149C4 /* GiGaExercisesViewController.m */; }; + 83E40B2F21218BA0008149C4 /* GiGaUserViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 83E40B2E21218BA0008149C4 /* GiGaUserViewController.m */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -35,6 +80,38 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 055947143A68ADCC68C3F3E1 /* Pods-GIGA.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GIGA.debug.xcconfig"; path = "Pods/Target Support Files/Pods-GIGA/Pods-GIGA.debug.xcconfig"; sourceTree = ""; }; + 83346ABD212BB50A0054D597 /* PassWordResetVC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PassWordResetVC.h; sourceTree = ""; }; + 83346ABE212BB50A0054D597 /* PassWordResetVC.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = PassWordResetVC.m; sourceTree = ""; }; + 83346ABF212BB50A0054D597 /* PassWordResetVC.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = PassWordResetVC.xib; sourceTree = ""; }; + 83346AC2212BBC8C0054D597 /* GiGaRegistViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaRegistViewController.h; sourceTree = ""; }; + 83346AC3212BBC8C0054D597 /* GiGaRegistViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaRegistViewController.m; sourceTree = ""; }; + 83346AC4212BBC8C0054D597 /* GiGaRegistViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = GiGaRegistViewController.xib; sourceTree = ""; }; + 83346ACB212BD7830054D597 /* GiGaWebViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaWebViewController.h; sourceTree = ""; }; + 83346ACC212BD7830054D597 /* GiGaWebViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaWebViewController.m; sourceTree = ""; }; + 83346ACD212BD7830054D597 /* GiGaWebViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = GiGaWebViewController.xib; sourceTree = ""; }; + 83346AD0212BF5B70054D597 /* useragreement.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = useragreement.html; sourceTree = ""; }; + 83346AD2212BFF6E0054D597 /* UserGuardViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = UserGuardViewController.h; sourceTree = ""; }; + 83346AD3212BFF6E0054D597 /* UserGuardViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = UserGuardViewController.m; sourceTree = ""; }; + 83346AD5212C18F50054D597 /* GiGaAppGaurdVC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaAppGaurdVC.h; sourceTree = ""; }; + 83346AD6212C18F50054D597 /* GiGaAppGaurdVC.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaAppGaurdVC.m; sourceTree = ""; }; + 833DA7742122A62000A5C614 /* GiGaMaskTaskViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaMaskTaskViewController.h; sourceTree = ""; }; + 833DA7752122A62000A5C614 /* GiGaMaskTaskViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaMaskTaskViewController.m; sourceTree = ""; }; + 8349585A212511040064DB6C /* AppDelegate+ThirdParty.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "AppDelegate+ThirdParty.h"; sourceTree = ""; }; + 8349585B212511040064DB6C /* AppDelegate+ThirdParty.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "AppDelegate+ThirdParty.m"; sourceTree = ""; }; + 8357ADC32123BEBD000816F2 /* GiGaUser.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaUser.h; sourceTree = ""; }; + 8357ADC42123BEBD000816F2 /* GiGaUser.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaUser.m; sourceTree = ""; }; + 8357ADC72123BFCA000816F2 /* GiGaUserManager.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaUserManager.h; sourceTree = ""; }; + 8357ADC82123BFCA000816F2 /* GiGaUserManager.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaUserManager.m; sourceTree = ""; }; + 8357ADCB2123C091000816F2 /* GiGaNetManager.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaNetManager.h; sourceTree = ""; }; + 8357ADCC2123C091000816F2 /* GiGaNetManager.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaNetManager.m; sourceTree = ""; }; + 8357ADCE2123C5F7000816F2 /* GiGaAPIRequest.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaAPIRequest.h; sourceTree = ""; }; + 8357ADCF2123C5F7000816F2 /* GiGaAPIRequest.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaAPIRequest.m; sourceTree = ""; }; + 8357ADD12123C7C6000816F2 /* GiGaAPIResult.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaAPIResult.h; sourceTree = ""; }; + 8357ADD22123C7C6000816F2 /* GiGaAPIResult.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaAPIResult.m; sourceTree = ""; }; + 8357ADD42123F5EC000816F2 /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = usr/lib/libsqlite3.tbd; sourceTree = SDKROOT; }; + 8357ADD62124027D000816F2 /* GiGaUserDefault.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaUserDefault.h; sourceTree = ""; }; + 8357ADD72124027D000816F2 /* GiGaUserDefault.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaUserDefault.m; sourceTree = ""; }; 8361B3C6212155C200238FEB /* GIGA.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GIGA.app; sourceTree = BUILT_PRODUCTS_DIR; }; 8361B3C9212155C200238FEB /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 8361B3CA212155C200238FEB /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; @@ -51,6 +128,49 @@ 8361B3E9212155C300238FEB /* GIGAUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GIGAUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 8361B3ED212155C300238FEB /* GIGAUITests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GIGAUITests.m; sourceTree = ""; }; 8361B3EF212155C300238FEB /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 8361B3FB21215BE900238FEB /* GIGA.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GIGA.pch; sourceTree = ""; }; + 8361B40021215CD800238FEB /* GIGA.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GIGA.h; sourceTree = ""; }; + 8361B40221215E0C00238FEB /* LXCountTimer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = LXCountTimer.m; sourceTree = ""; }; + 8361B40321215E0C00238FEB /* LXCountTimer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LXCountTimer.h; sourceTree = ""; }; + 8361B40521215E6F00238FEB /* GiGaHelper.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaHelper.h; sourceTree = ""; }; + 8361B40621215E6F00238FEB /* GiGaHelper.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaHelper.m; sourceTree = ""; }; + 8361B40921217B2100238FEB /* AppDelegate+GiGaConfig.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "AppDelegate+GiGaConfig.h"; sourceTree = ""; }; + 8361B40A21217B2100238FEB /* AppDelegate+GiGaConfig.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "AppDelegate+GiGaConfig.m"; sourceTree = ""; }; + 8361B40C21217C8200238FEB /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = System/Library/Frameworks/CFNetwork.framework; sourceTree = SDKROOT; }; + 8361B40E21217C9100238FEB /* CoreFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreFoundation.framework; path = System/Library/Frameworks/CoreFoundation.framework; sourceTree = SDKROOT; }; + 8361B41021217CA100238FEB /* CoreTelephony.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreTelephony.framework; path = System/Library/Frameworks/CoreTelephony.framework; sourceTree = SDKROOT; }; + 8361B41221217D7E00238FEB /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; }; + 8361B41421217D9200238FEB /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; + 8361B41621217DA000238FEB /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; + 8361B41821217DAD00238FEB /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; + 8361B41A21217DBA00238FEB /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; }; + 8361B41C21217DCD00238FEB /* libz.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libz.tbd; path = usr/lib/libz.tbd; sourceTree = SDKROOT; }; + 8361B41E21217DDF00238FEB /* AdSupport.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AdSupport.framework; path = System/Library/Frameworks/AdSupport.framework; sourceTree = SDKROOT; }; + 8361B42021217DF000238FEB /* UserNotifications.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UserNotifications.framework; path = System/Library/Frameworks/UserNotifications.framework; sourceTree = SDKROOT; }; + 8361B42221217DFF00238FEB /* libresolv.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libresolv.tbd; path = usr/lib/libresolv.tbd; sourceTree = SDKROOT; }; + 8361B42C2121812000238FEB /* GiGaServerConfig.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaServerConfig.h; sourceTree = ""; }; + 8361B42D2121812000238FEB /* GiGaServerConfig.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaServerConfig.m; sourceTree = ""; }; + 8361B4302121832800238FEB /* GiGaBaseViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaBaseViewController.h; sourceTree = ""; }; + 8361B4312121832800238FEB /* GiGaBaseViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaBaseViewController.m; sourceTree = ""; }; + 8361B4332121836700238FEB /* GiGaBaseNavViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaBaseNavViewController.h; sourceTree = ""; }; + 8361B4342121836700238FEB /* GiGaBaseNavViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaBaseNavViewController.m; sourceTree = ""; }; + 8361B4362121847600238FEB /* UINavigationBar+Custom.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "UINavigationBar+Custom.h"; sourceTree = ""; }; + 8361B4372121847600238FEB /* UINavigationBar+Custom.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "UINavigationBar+Custom.m"; sourceTree = ""; }; + 83A2270A212A97ED00B3E75C /* MaskViewBootomWaringView.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MaskViewBootomWaringView.h; sourceTree = ""; }; + 83A2270B212A97ED00B3E75C /* MaskViewBootomWaringView.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MaskViewBootomWaringView.m; sourceTree = ""; }; + 83A22710212A9EA900B3E75C /* UIView+Sizes.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIView+Sizes.m"; sourceTree = ""; }; + 83A22711212A9EA900B3E75C /* UIView+Sizes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIView+Sizes.h"; sourceTree = ""; }; + 83A22716212ABDFF00B3E75C /* GiGaBlockButton.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaBlockButton.h; sourceTree = ""; }; + 83A22717212ABDFF00B3E75C /* GiGaBlockButton.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaBlockButton.m; sourceTree = ""; }; + 83A2271C212AC8C100B3E75C /* GiGaUserLoginVC.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaUserLoginVC.h; sourceTree = ""; }; + 83A2271D212AC8C100B3E75C /* GiGaUserLoginVC.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaUserLoginVC.m; sourceTree = ""; }; + 83A2271E212AC8C100B3E75C /* GiGaUserLoginVC.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = GiGaUserLoginVC.xib; sourceTree = ""; }; + 83E40B2921218B6F008149C4 /* GiGaExercisesViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaExercisesViewController.h; sourceTree = ""; }; + 83E40B2A21218B6F008149C4 /* GiGaExercisesViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaExercisesViewController.m; sourceTree = ""; }; + 83E40B2D21218BA0008149C4 /* GiGaUserViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GiGaUserViewController.h; sourceTree = ""; }; + 83E40B2E21218BA0008149C4 /* GiGaUserViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = GiGaUserViewController.m; sourceTree = ""; }; + B14B65914FBF61910191D7A8 /* Pods_GIGA.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GIGA.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + F5264C04C5FC282D0E6AB7E5 /* Pods-GIGA.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GIGA.release.xcconfig"; path = "Pods/Target Support Files/Pods-GIGA/Pods-GIGA.release.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -58,6 +178,20 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + 8357ADD52123F5EC000816F2 /* libsqlite3.tbd in Frameworks */, + 8361B42321217DFF00238FEB /* libresolv.tbd in Frameworks */, + 8361B42121217DF000238FEB /* UserNotifications.framework in Frameworks */, + 8361B41F21217DDF00238FEB /* AdSupport.framework in Frameworks */, + 8361B41D21217DCD00238FEB /* libz.tbd in Frameworks */, + 8361B41B21217DBA00238FEB /* Security.framework in Frameworks */, + 8361B41921217DAD00238FEB /* UIKit.framework in Frameworks */, + 8361B41721217DA000238FEB /* Foundation.framework in Frameworks */, + 8361B41521217D9200238FEB /* CoreGraphics.framework in Frameworks */, + 8361B41321217D7E00238FEB /* SystemConfiguration.framework in Frameworks */, + 8361B41121217CA100238FEB /* CoreTelephony.framework in Frameworks */, + 8361B40F21217C9200238FEB /* CoreFoundation.framework in Frameworks */, + 8361B40D21217C8200238FEB /* CFNetwork.framework in Frameworks */, + 6B67B068A469498C38CEF799 /* Pods_GIGA.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -78,6 +212,76 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 65EAB96A62781B2C8A9EE493 /* Pods */ = { + isa = PBXGroup; + children = ( + 055947143A68ADCC68C3F3E1 /* Pods-GIGA.debug.xcconfig */, + F5264C04C5FC282D0E6AB7E5 /* Pods-GIGA.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; + 83346AC8212BD4160054D597 /* Source */ = { + isa = PBXGroup; + children = ( + 83346AD0212BF5B70054D597 /* useragreement.html */, + ); + path = Source; + sourceTree = ""; + }; + 8354B3812121BAE1004F448F /* Controller */ = { + isa = PBXGroup; + children = ( + 833DA7742122A62000A5C614 /* GiGaMaskTaskViewController.h */, + 833DA7752122A62000A5C614 /* GiGaMaskTaskViewController.m */, + 83346AD2212BFF6E0054D597 /* UserGuardViewController.h */, + 83346AD3212BFF6E0054D597 /* UserGuardViewController.m */, + 83346AD5212C18F50054D597 /* GiGaAppGaurdVC.h */, + 83346AD6212C18F50054D597 /* GiGaAppGaurdVC.m */, + ); + path = Controller; + sourceTree = ""; + }; + 8354B3822121BAFA004F448F /* Model */ = { + isa = PBXGroup; + children = ( + ); + path = Model; + sourceTree = ""; + }; + 8354B3832121BB00004F448F /* View */ = { + isa = PBXGroup; + children = ( + 83A2270A212A97ED00B3E75C /* MaskViewBootomWaringView.h */, + 83A2270B212A97ED00B3E75C /* MaskViewBootomWaringView.m */, + ); + path = View; + sourceTree = ""; + }; + 8357ADC62123BF6D000816F2 /* GiGaUserDB */ = { + isa = PBXGroup; + children = ( + 8357ADC72123BFCA000816F2 /* GiGaUserManager.h */, + 8357ADC82123BFCA000816F2 /* GiGaUserManager.m */, + 8357ADD62124027D000816F2 /* GiGaUserDefault.h */, + 8357ADD72124027D000816F2 /* GiGaUserDefault.m */, + ); + path = GiGaUserDB; + sourceTree = ""; + }; + 8357ADCA2123BFD8000816F2 /* GiGaNetTool */ = { + isa = PBXGroup; + children = ( + 8357ADCB2123C091000816F2 /* GiGaNetManager.h */, + 8357ADCC2123C091000816F2 /* GiGaNetManager.m */, + 8357ADCE2123C5F7000816F2 /* GiGaAPIRequest.h */, + 8357ADCF2123C5F7000816F2 /* GiGaAPIRequest.m */, + 8357ADD12123C7C6000816F2 /* GiGaAPIResult.h */, + 8357ADD22123C7C6000816F2 /* GiGaAPIResult.m */, + ); + path = GiGaNetTool; + sourceTree = ""; + }; 8361B3BD212155C200238FEB = { isa = PBXGroup; children = ( @@ -85,6 +289,8 @@ 8361B3E1212155C300238FEB /* GIGATests */, 8361B3EC212155C300238FEB /* GIGAUITests */, 8361B3C7212155C200238FEB /* Products */, + 65EAB96A62781B2C8A9EE493 /* Pods */, + F3264CFCC2F2D369DC49BD1A /* Frameworks */, ); sourceTree = ""; }; @@ -101,8 +307,16 @@ 8361B3C8212155C200238FEB /* GIGA */ = { isa = PBXGroup; children = ( + 8361B3FF21215C9D00238FEB /* Modules */, + 8361B3FE21215C8A00238FEB /* Category */, + 8361B3FD21215C7F00238FEB /* Config */, + 8361B3FC21215C7400238FEB /* Common */, 8361B3C9212155C200238FEB /* AppDelegate.h */, 8361B3CA212155C200238FEB /* AppDelegate.m */, + 8361B40921217B2100238FEB /* AppDelegate+GiGaConfig.h */, + 8361B40A21217B2100238FEB /* AppDelegate+GiGaConfig.m */, + 8349585A212511040064DB6C /* AppDelegate+ThirdParty.h */, + 8349585B212511040064DB6C /* AppDelegate+ThirdParty.m */, 8361B3CC212155C200238FEB /* ViewController.h */, 8361B3CD212155C200238FEB /* ViewController.m */, 8361B3CF212155C200238FEB /* Main.storyboard */, @@ -110,6 +324,7 @@ 8361B3D4212155C300238FEB /* LaunchScreen.storyboard */, 8361B3D7212155C300238FEB /* Info.plist */, 8361B3D8212155C300238FEB /* main.m */, + 8361B3FB21215BE900238FEB /* GIGA.pch */, ); path = GIGA; sourceTree = ""; @@ -132,6 +347,216 @@ path = GIGAUITests; sourceTree = ""; }; + 8361B3FC21215C7400238FEB /* Common */ = { + isa = PBXGroup; + children = ( + 83346AC8212BD4160054D597 /* Source */, + 8357ADCA2123BFD8000816F2 /* GiGaNetTool */, + 8357ADC62123BF6D000816F2 /* GiGaUserDB */, + 8361B42F2121830500238FEB /* BaseVC */, + 8361B40121215E0C00238FEB /* LXCountTimer */, + 8361B40521215E6F00238FEB /* GiGaHelper.h */, + 8361B40621215E6F00238FEB /* GiGaHelper.m */, + ); + path = Common; + sourceTree = ""; + }; + 8361B3FD21215C7F00238FEB /* Config */ = { + isa = PBXGroup; + children = ( + 8361B40021215CD800238FEB /* GIGA.h */, + 8361B42C2121812000238FEB /* GiGaServerConfig.h */, + 8361B42D2121812000238FEB /* GiGaServerConfig.m */, + ); + path = Config; + sourceTree = ""; + }; + 8361B3FE21215C8A00238FEB /* Category */ = { + isa = PBXGroup; + children = ( + 83A22711212A9EA900B3E75C /* UIView+Sizes.h */, + 83A22710212A9EA900B3E75C /* UIView+Sizes.m */, + 8361B4362121847600238FEB /* UINavigationBar+Custom.h */, + 8361B4372121847600238FEB /* UINavigationBar+Custom.m */, + 83A22716212ABDFF00B3E75C /* GiGaBlockButton.h */, + 83A22717212ABDFF00B3E75C /* GiGaBlockButton.m */, + ); + path = Category; + sourceTree = ""; + }; + 8361B3FF21215C9D00238FEB /* Modules */ = { + isa = PBXGroup; + children = ( + 83E40B3021219078008149C4 /* Mask */, + 83E40B2C21218B7E008149C4 /* LogIn */, + 8361B42521217FC000238FEB /* GiGaExercises */, + 8361B42421217F6000238FEB /* Me */, + ); + path = Modules; + sourceTree = ""; + }; + 8361B40121215E0C00238FEB /* LXCountTimer */ = { + isa = PBXGroup; + children = ( + 8361B40221215E0C00238FEB /* LXCountTimer.m */, + 8361B40321215E0C00238FEB /* LXCountTimer.h */, + ); + path = LXCountTimer; + sourceTree = ""; + }; + 8361B42421217F6000238FEB /* Me */ = { + isa = PBXGroup; + children = ( + 8361B42B212180A800238FEB /* Controller */, + 8361B42A212180A100238FEB /* View */, + 8361B4292121809A00238FEB /* Model */, + ); + path = Me; + sourceTree = ""; + }; + 8361B42521217FC000238FEB /* GiGaExercises */ = { + isa = PBXGroup; + children = ( + 8361B4282121807100238FEB /* Controller */, + 8361B4272121806500238FEB /* View */, + 8361B4262121805800238FEB /* Model */, + ); + path = GiGaExercises; + sourceTree = ""; + }; + 8361B4262121805800238FEB /* Model */ = { + isa = PBXGroup; + children = ( + ); + path = Model; + sourceTree = ""; + }; + 8361B4272121806500238FEB /* View */ = { + isa = PBXGroup; + children = ( + ); + path = View; + sourceTree = ""; + }; + 8361B4282121807100238FEB /* Controller */ = { + isa = PBXGroup; + children = ( + 83E40B2921218B6F008149C4 /* GiGaExercisesViewController.h */, + 83E40B2A21218B6F008149C4 /* GiGaExercisesViewController.m */, + ); + path = Controller; + sourceTree = ""; + }; + 8361B4292121809A00238FEB /* Model */ = { + isa = PBXGroup; + children = ( + 8357ADC32123BEBD000816F2 /* GiGaUser.h */, + 8357ADC42123BEBD000816F2 /* GiGaUser.m */, + ); + path = Model; + sourceTree = ""; + }; + 8361B42A212180A100238FEB /* View */ = { + isa = PBXGroup; + children = ( + ); + path = View; + sourceTree = ""; + }; + 8361B42B212180A800238FEB /* Controller */ = { + isa = PBXGroup; + children = ( + 83E40B2D21218BA0008149C4 /* GiGaUserViewController.h */, + 83E40B2E21218BA0008149C4 /* GiGaUserViewController.m */, + ); + path = Controller; + sourceTree = ""; + }; + 8361B42F2121830500238FEB /* BaseVC */ = { + isa = PBXGroup; + children = ( + 8361B4302121832800238FEB /* GiGaBaseViewController.h */, + 8361B4312121832800238FEB /* GiGaBaseViewController.m */, + 8361B4332121836700238FEB /* GiGaBaseNavViewController.h */, + 8361B4342121836700238FEB /* GiGaBaseNavViewController.m */, + ); + path = BaseVC; + sourceTree = ""; + }; + 83A22719212AC7FC00B3E75C /* View */ = { + isa = PBXGroup; + children = ( + ); + path = View; + sourceTree = ""; + }; + 83A2271A212AC80D00B3E75C /* Model */ = { + isa = PBXGroup; + children = ( + ); + path = Model; + sourceTree = ""; + }; + 83A2271B212AC81800B3E75C /* Controller */ = { + isa = PBXGroup; + children = ( + 83A2271C212AC8C100B3E75C /* GiGaUserLoginVC.h */, + 83A2271D212AC8C100B3E75C /* GiGaUserLoginVC.m */, + 83A2271E212AC8C100B3E75C /* GiGaUserLoginVC.xib */, + 83346ABD212BB50A0054D597 /* PassWordResetVC.h */, + 83346ABE212BB50A0054D597 /* PassWordResetVC.m */, + 83346ABF212BB50A0054D597 /* PassWordResetVC.xib */, + 83346AC2212BBC8C0054D597 /* GiGaRegistViewController.h */, + 83346AC3212BBC8C0054D597 /* GiGaRegistViewController.m */, + 83346AC4212BBC8C0054D597 /* GiGaRegistViewController.xib */, + 83346ACB212BD7830054D597 /* GiGaWebViewController.h */, + 83346ACC212BD7830054D597 /* GiGaWebViewController.m */, + 83346ACD212BD7830054D597 /* GiGaWebViewController.xib */, + ); + path = Controller; + sourceTree = ""; + }; + 83E40B2C21218B7E008149C4 /* LogIn */ = { + isa = PBXGroup; + children = ( + 83A2271B212AC81800B3E75C /* Controller */, + 83A2271A212AC80D00B3E75C /* Model */, + 83A22719212AC7FC00B3E75C /* View */, + ); + path = LogIn; + sourceTree = ""; + }; + 83E40B3021219078008149C4 /* Mask */ = { + isa = PBXGroup; + children = ( + 8354B3832121BB00004F448F /* View */, + 8354B3822121BAFA004F448F /* Model */, + 8354B3812121BAE1004F448F /* Controller */, + ); + path = Mask; + sourceTree = ""; + }; + F3264CFCC2F2D369DC49BD1A /* Frameworks */ = { + isa = PBXGroup; + children = ( + 8357ADD42123F5EC000816F2 /* libsqlite3.tbd */, + 8361B42221217DFF00238FEB /* libresolv.tbd */, + 8361B42021217DF000238FEB /* UserNotifications.framework */, + 8361B41E21217DDF00238FEB /* AdSupport.framework */, + 8361B41C21217DCD00238FEB /* libz.tbd */, + 8361B41A21217DBA00238FEB /* Security.framework */, + 8361B41821217DAD00238FEB /* UIKit.framework */, + 8361B41621217DA000238FEB /* Foundation.framework */, + 8361B41421217D9200238FEB /* CoreGraphics.framework */, + 8361B41221217D7E00238FEB /* SystemConfiguration.framework */, + 8361B41021217CA100238FEB /* CoreTelephony.framework */, + 8361B40E21217C9100238FEB /* CoreFoundation.framework */, + 8361B40C21217C8200238FEB /* CFNetwork.framework */, + B14B65914FBF61910191D7A8 /* Pods_GIGA.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -139,9 +564,11 @@ isa = PBXNativeTarget; buildConfigurationList = 8361B3F2212155C300238FEB /* Build configuration list for PBXNativeTarget "GIGA" */; buildPhases = ( + 4B5D1A4AA6F42082A6FF0825 /* [CP] Check Pods Manifest.lock */, 8361B3C2212155C200238FEB /* Sources */, 8361B3C3212155C200238FEB /* Frameworks */, 8361B3C4212155C200238FEB /* Resources */, + E4327C8129838280C8779238 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -235,9 +662,14 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 83346AC6212BBC8C0054D597 /* GiGaRegistViewController.xib in Resources */, 8361B3D6212155C300238FEB /* LaunchScreen.storyboard in Resources */, + 83A22720212AC8C100B3E75C /* GiGaUserLoginVC.xib in Resources */, + 83346AC1212BB50A0054D597 /* PassWordResetVC.xib in Resources */, + 83346AD1212BF5B70054D597 /* useragreement.html in Resources */, 8361B3D3212155C300238FEB /* Assets.xcassets in Resources */, 8361B3D1212155C200238FEB /* Main.storyboard in Resources */, + 83346ACF212BD7830054D597 /* GiGaWebViewController.xib in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -257,14 +689,107 @@ }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + 4B5D1A4AA6F42082A6FF0825 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-GIGA-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + E4327C8129838280C8779238 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${SRCROOT}/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-frameworks.sh", + "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework", + "${BUILT_PRODUCTS_DIR}/FMDB/FMDB.framework", + "${BUILT_PRODUCTS_DIR}/IQKeyboardManager/IQKeyboardManager.framework", + "${BUILT_PRODUCTS_DIR}/JSONModel/JSONModel.framework", + "${BUILT_PRODUCTS_DIR}/LKDBHelper/LKDBHelper.framework", + "${BUILT_PRODUCTS_DIR}/MBProgressHUD/MBProgressHUD.framework", + "${BUILT_PRODUCTS_DIR}/MJRefresh/MJRefresh.framework", + "${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework", + "${BUILT_PRODUCTS_DIR}/NJKWebViewProgress/NJKWebViewProgress.framework", + "${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework", + "${BUILT_PRODUCTS_DIR}/SocketRocket/SocketRocket.framework", + "${BUILT_PRODUCTS_DIR}/TTTAttributedLabel/TTTAttributedLabel.framework", + "${BUILT_PRODUCTS_DIR}/Toast/Toast.framework", + "${BUILT_PRODUCTS_DIR}/UITableView+FDTemplateLayoutCell/UITableView_FDTemplateLayoutCell.framework", + "${BUILT_PRODUCTS_DIR}/YTKKeyValueStore/YTKKeyValueStore.framework", + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/AFNetworking.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/FMDB.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/IQKeyboardManager.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/JSONModel.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/LKDBHelper.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/MBProgressHUD.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/MJRefresh.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Masonry.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/NJKWebViewProgress.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SDWebImage.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SocketRocket.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/TTTAttributedLabel.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Toast.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/UITableView_FDTemplateLayoutCell.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/YTKKeyValueStore.framework", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 8361B3C2212155C200238FEB /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 83346AC5212BBC8C0054D597 /* GiGaRegistViewController.m in Sources */, + 83346AD7212C18F50054D597 /* GiGaAppGaurdVC.m in Sources */, + 8361B40B21217B2100238FEB /* AppDelegate+GiGaConfig.m in Sources */, + 8349585C212511040064DB6C /* AppDelegate+ThirdParty.m in Sources */, 8361B3CE212155C200238FEB /* ViewController.m in Sources */, + 8361B4382121847600238FEB /* UINavigationBar+Custom.m in Sources */, + 83346AD4212BFF6E0054D597 /* UserGuardViewController.m in Sources */, + 8357ADC92123BFCA000816F2 /* GiGaUserManager.m in Sources */, + 83A2271F212AC8C100B3E75C /* GiGaUserLoginVC.m in Sources */, + 83346ACE212BD7830054D597 /* GiGaWebViewController.m in Sources */, + 8357ADD82124027D000816F2 /* GiGaUserDefault.m in Sources */, + 8361B40721215E6F00238FEB /* GiGaHelper.m in Sources */, + 8357ADCD2123C091000816F2 /* GiGaNetManager.m in Sources */, + 833DA7762122A62000A5C614 /* GiGaMaskTaskViewController.m in Sources */, + 8357ADD02123C5F7000816F2 /* GiGaAPIRequest.m in Sources */, 8361B3D9212155C300238FEB /* main.m in Sources */, 8361B3CB212155C200238FEB /* AppDelegate.m in Sources */, + 8361B4322121832800238FEB /* GiGaBaseViewController.m in Sources */, + 8357ADD32123C7C6000816F2 /* GiGaAPIResult.m in Sources */, + 8361B4352121836700238FEB /* GiGaBaseNavViewController.m in Sources */, + 83346AC0212BB50A0054D597 /* PassWordResetVC.m in Sources */, + 8361B40421215E0C00238FEB /* LXCountTimer.m in Sources */, + 8357ADC52123BEBD000816F2 /* GiGaUser.m in Sources */, + 83E40B2F21218BA0008149C4 /* GiGaUserViewController.m in Sources */, + 83E40B2B21218B6F008149C4 /* GiGaExercisesViewController.m in Sources */, + 8361B42E2121812000238FEB /* GiGaServerConfig.m in Sources */, + 83A22712212A9EA900B3E75C /* UIView+Sizes.m in Sources */, + 83A22718212ABDFF00B3E75C /* GiGaBlockButton.m in Sources */, + 83A2270C212A97ED00B3E75C /* MaskViewBootomWaringView.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -431,32 +956,54 @@ }; 8361B3F3212155C300238FEB /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 055947143A68ADCC68C3F3E1 /* Pods-GIGA.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CODE_SIGN_STYLE = Automatic; + CODE_SIGN_STYLE = Manual; + DEVELOPMENT_TEAM = ""; + GCC_PREFIX_HEADER = "$(SRCROOT)//GIGA/GIGA.pch"; + GCC_PREPROCESSOR_DEFINITIONS = ( + "$(inherited)", + "COCOAPODS=1", + "GIGA_ENVIRONMENT=0", + "GIGA_PUSH_ENVIRONMENT=0", + ); INFOPLIST_FILE = GIGA/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = lianxiang.GIGA; + PRODUCT_BUNDLE_IDENTIFIER = com.gigamask.ios; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; }; 8361B3F4212155C300238FEB /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = F5264C04C5FC282D0E6AB7E5 /* Pods-GIGA.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CODE_SIGN_STYLE = Automatic; + CODE_SIGN_STYLE = Manual; + DEVELOPMENT_TEAM = ""; + GCC_PREFIX_HEADER = "$(SRCROOT)//GIGA/GIGA.pch"; + GCC_PREPROCESSOR_DEFINITIONS = ( + "$(inherited)", + "COCOAPODS=1", + "GIGA_ENVIRONMENT=1", + "GIGA_PUSH_ENVIRONMENT=1", + ); INFOPLIST_FILE = GIGA/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - PRODUCT_BUNDLE_IDENTIFIER = lianxiang.GIGA; + PRODUCT_BUNDLE_IDENTIFIER = com.gigamask.ios; PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Release; diff --git a/GIGA.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/xcschememanagement.plist b/GIGA.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/xcschememanagement.plist index 0e35953..cd80bed 100644 --- a/GIGA.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/xcschememanagement.plist +++ b/GIGA.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/xcschememanagement.plist @@ -7,7 +7,7 @@ GIGA.xcscheme orderHint - 0 + 16 diff --git a/GIGA.xcworkspace/contents.xcworkspacedata b/GIGA.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..f6d1e27 --- /dev/null +++ b/GIGA.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/GIGA.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/GIGA.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/GIGA.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/GIGA.xcworkspace/xcuserdata/lianxiang.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/GIGA.xcworkspace/xcuserdata/lianxiang.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist new file mode 100644 index 0000000..ed9a9b4 --- /dev/null +++ b/GIGA.xcworkspace/xcuserdata/lianxiang.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -0,0 +1,5 @@ + + + diff --git a/GIGA/AppDelegate+Config.h b/GIGA/AppDelegate+Config.h new file mode 100644 index 0000000..5267cd5 --- /dev/null +++ b/GIGA/AppDelegate+Config.h @@ -0,0 +1,13 @@ +// +// AppDelegate+Config.h +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "AppDelegate.h" + +@interface AppDelegate () + +@end diff --git a/GIGA/AppDelegate+GiGaConfig.h b/GIGA/AppDelegate+GiGaConfig.h new file mode 100644 index 0000000..7d6a952 --- /dev/null +++ b/GIGA/AppDelegate+GiGaConfig.h @@ -0,0 +1,20 @@ +// +// AppDelegate+GiGaConfig.h +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "AppDelegate.h" + +@interface AppDelegate (GiGaConfig) + +- (void)setupTabBarController; +- (void)configEnvironment; + +//v1.0 +- (void)setupRootVC; + + +@end diff --git a/GIGA/AppDelegate+GiGaConfig.m b/GIGA/AppDelegate+GiGaConfig.m new file mode 100644 index 0000000..730bbfc --- /dev/null +++ b/GIGA/AppDelegate+GiGaConfig.m @@ -0,0 +1,90 @@ +// +// AppDelegate+GiGaConfig.m +// GIGA +// + +#import "AppDelegate+GiGaConfig.h" +#import "GiGaServerConfig.h" +#import "GiGaUserViewController.h" +#import "GiGaExercisesViewController.h" +#import "GiGaBaseNavViewController.h" +#import "GiGaMaskTaskViewController.h" +#import "GiGaUserDefault.h" +@implementation AppDelegate (GiGaConfig) + +-(void)setupTabBarController{ + + GiGaExercisesViewController *exerciseVC = [[GiGaExercisesViewController alloc] init]; + GiGaBaseNavViewController *exerciseNav =[[GiGaBaseNavViewController alloc] initWithRootViewController:exerciseVC]; + exerciseNav.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor blackColor]}; + exerciseNav.title = @"测试"; + exerciseNav.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"测试" + image:nil + selectedImage:nil]; + + GiGaMaskTaskViewController *maskVC = [[GiGaMaskTaskViewController alloc] init]; + GiGaBaseNavViewController *maskNav =[[GiGaBaseNavViewController alloc] initWithRootViewController:maskVC]; + maskNav.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor blackColor]}; + maskNav.title = @"测试2"; + maskNav.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"测试2" + image:nil + selectedImage:nil]; + + + GiGaUserViewController *userVC = [[GiGaUserViewController alloc] init]; + GiGaBaseNavViewController *userNav = [[GiGaBaseNavViewController alloc] initWithRootViewController:userVC]; + userNav.navigationBar.titleTextAttributes =@{NSForegroundColorAttributeName:[UIColor blackColor]}; + userNav.title = @"我的"; + userNav.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"我的" image:nil selectedImage:nil]; + + [[UITabBar appearance] setTintColor:GIGARGB(70, 70, 70, 1)]; + self.rootTabBarVC = [[UITabBarController alloc] init]; + self.rootTabBarVC.viewControllers = @[exerciseNav,maskNav,userNav]; + [self initTabItems]; + self.window.rootViewController = self.rootTabBarVC; + self.window.backgroundColor = [UIColor whiteColor]; + [self.window makeKeyAndVisible]; + +} + +-(void)initTabItems{ + UITabBar *tabBar = self.rootTabBarVC.tabBar; + UITabBarItem *item0 = [tabBar.items objectAtIndex:0]; + UITabBarItem *item1 = [tabBar.items objectAtIndex:1]; + UITabBarItem *item2 = [tabBar.items objectAtIndex:2]; + + item0.selectedImage = [[UIImage imageNamed:@""] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; + ; + item0.image = [[UIImage imageNamed:@""] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; + + item1.selectedImage = [[UIImage imageNamed:@""] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; + ; + item1.image = [[UIImage imageNamed:@""] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; + + item2.selectedImage = [[UIImage imageNamed:@""] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; + ; + item2.image = [[UIImage imageNamed:@""] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]; + + + +} + +-(void)configEnvironment{ + + [GiGaServerConfig setServerType:GIGA_ENVIRONMENT]; + +} + +// +- (void)setupRootVC{ + GiGaMaskTaskViewController *maskeVC = [[GiGaMaskTaskViewController alloc] init]; + GiGaBaseNavViewController *maskNav =[[GiGaBaseNavViewController alloc] initWithRootViewController:maskeVC]; + maskNav.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor blackColor]}; + maskeVC.title = @"面膜时间"; + self.window.rootViewController = maskNav; + self.window.backgroundColor = [UIColor whiteColor]; + [self.window makeKeyAndVisible]; +} + + +@end diff --git a/GIGA/AppDelegate+ThirdParty.h b/GIGA/AppDelegate+ThirdParty.h new file mode 100644 index 0000000..97c6d81 --- /dev/null +++ b/GIGA/AppDelegate+ThirdParty.h @@ -0,0 +1,23 @@ +// +// AppDelegate+ThirdParty.h +// GIGA +// +// Created by lianxiang on 2018/8/16. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "AppDelegate.h" +#import "WXApi.h" +#import "JPUSHService.h" +// iOS10注册APNs所需头文件 +#ifdef NSFoundationVersionNumber_iOS_9_x_Max + +#import + +#endif + +@interface AppDelegate (ThirdParty) + +-(void)configThridPartyWithOptions:(NSDictionary *)launchOptions; + +@end diff --git a/GIGA/AppDelegate+ThirdParty.m b/GIGA/AppDelegate+ThirdParty.m new file mode 100644 index 0000000..5c5eca3 --- /dev/null +++ b/GIGA/AppDelegate+ThirdParty.m @@ -0,0 +1,109 @@ +// +// AppDelegate+ThirdParty.m +// GIGA +// +// Created by lianxiang on 2018/8/16. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "AppDelegate+ThirdParty.h" +#define PUSH_APPKEY @"1f8122badd24c2adb8b3f231" + +@implementation AppDelegate (ThirdParty) + +-(void)configThridPartyWithOptions:(NSDictionary *)launchOptions{ + + //极光推送 + //APNS Regist + JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init]; + entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound; + if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) { + // 可以添加自定义categories + // NSSet *categories for iOS10 or later + // NSSet *categories for iOS8 and iOS9 + } + [JPUSHService registerForRemoteNotificationConfig:entity delegate:self]; + + // Required + // init Push + + [JPUSHService setupWithOption:launchOptions appKey:PUSH_APPKEY + channel:@"App store" + apsForProduction:GIGA_PUSH_ENVIRONMENT + advertisingIdentifier:nil]; + + //微信 + + +} + +// 微信 +- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options +{ + return [WXApi handleOpenURL:url delegate:self]; +} + +//WXApiDelegate +- (void)onReq:(BaseReq *)req{ + +} + +- (void)onResp:(BaseResp *)resp{ + NSLog(@"resp:%d",resp.errCode); + if ([resp isKindOfClass:[SendAuthResp class]]) { + SendAuthResp*rep = (SendAuthResp*)resp; + if (resp.errCode == 0) { + [[NSNotificationCenter defaultCenter] postNotificationName: @"WXAuthSuccess" object:@{@"code":rep.code}]; + + } + } +} +// ios 10 Support +- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler API_AVAILABLE(ios(10.0)){ + + // Required + NSDictionary * userInfo = response.notification.request.content.userInfo; + if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) { + [JPUSHService handleRemoteNotification:userInfo]; + } + completionHandler(); // 系统要求执行这个方法 + +} +- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler API_AVAILABLE(ios(10.0)){ + + // Required + NSDictionary * userInfo = notification.request.content.userInfo; + if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) { + [JPUSHService handleRemoteNotification:userInfo]; + } + completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以选择设置 + +} + +-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{ + + [JPUSHService registerDeviceToken:deviceToken]; +} + +- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { + //Optional + NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error); +} + +//ios8 以下本应用可忽略 +- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { + + // Required, iOS 7 Support + [JPUSHService handleRemoteNotification:userInfo]; + completionHandler(UIBackgroundFetchResultNewData); +} + +- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { + + // Required,For systems with less than or equal to iOS6 + [JPUSHService handleRemoteNotification:userInfo]; +} + + + +@end diff --git a/GIGA/AppDelegate.h b/GIGA/AppDelegate.h index 661273d..4ac7851 100644 --- a/GIGA/AppDelegate.h +++ b/GIGA/AppDelegate.h @@ -11,6 +11,7 @@ @interface AppDelegate : UIResponder @property (strong, nonatomic) UIWindow *window; +@property (nonatomic ,strong) UITabBarController *rootTabBarVC; @end diff --git a/GIGA/AppDelegate.m b/GIGA/AppDelegate.m index cae70e9..2de2367 100644 --- a/GIGA/AppDelegate.m +++ b/GIGA/AppDelegate.m @@ -7,6 +7,9 @@ // #import "AppDelegate.h" +#import "AppDelegate+GiGaConfig.h" +#import "AppDelegate+ThirdParty.h" +#import "GiGaUserDefault.h" @interface AppDelegate () @@ -17,10 +20,18 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. + [NSThread sleepForTimeInterval:1];//延迟启动 + + [self configThridPartyWithOptions:launchOptions]; + [self configEnvironment]; + + [self setupRootVC]; + + //[self setupTabBarController]; + return YES; } - - (void)applicationWillResignActive:(UIApplication *)application { // 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. diff --git a/GIGA/Assets.xcassets/maskTime/Contents.json b/GIGA/Assets.xcassets/maskTime/Contents.json new file mode 100644 index 0000000..da4a164 --- /dev/null +++ b/GIGA/Assets.xcassets/maskTime/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/GIGA/Assets.xcassets/maskTime/maske_dismiss_waring.imageset/Contents.json b/GIGA/Assets.xcassets/maskTime/maske_dismiss_waring.imageset/Contents.json new file mode 100644 index 0000000..0561119 --- /dev/null +++ b/GIGA/Assets.xcassets/maskTime/maske_dismiss_waring.imageset/Contents.json @@ -0,0 +1,13 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "maske_dismiss_waring.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/GIGA/Assets.xcassets/maskTime/maske_dismiss_waring.imageset/maske_dismiss_waring.png b/GIGA/Assets.xcassets/maskTime/maske_dismiss_waring.imageset/maske_dismiss_waring.png new file mode 100644 index 0000000..07cc16e Binary files /dev/null and b/GIGA/Assets.xcassets/maskTime/maske_dismiss_waring.imageset/maske_dismiss_waring.png differ diff --git a/GIGA/Category/GiGaBlockButton.h b/GIGA/Category/GiGaBlockButton.h new file mode 100644 index 0000000..aa83c16 --- /dev/null +++ b/GIGA/Category/GiGaBlockButton.h @@ -0,0 +1,17 @@ +// +// GiGaBlockButton.h +// GIGA +// +// Created by lianxiang on 2018/8/20. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import +typedef void (^ClickActionBlock)(UIButton *); + +@interface GiGaBlockButton : UIButton + +@property(nonatomic,copy) ClickActionBlock clickBlock; +-(void)initWithBlock:(ClickActionBlock)clickBlock for:(UIControlEvents)envent; + +@end diff --git a/GIGA/Category/GiGaBlockButton.m b/GIGA/Category/GiGaBlockButton.m new file mode 100644 index 0000000..a321fd4 --- /dev/null +++ b/GIGA/Category/GiGaBlockButton.m @@ -0,0 +1,20 @@ +// +// GiGaBlockButton.m +// GIGA +// +// Created by lianxiang on 2018/8/20. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaBlockButton.h" + +@implementation GiGaBlockButton + +-(void)initWithBlock:(ClickActionBlock)clickBlock for:(UIControlEvents)envent{ + [self addTarget:self action:@selector(btnAction:) forControlEvents:envent]; + self.clickBlock = clickBlock; +} +-(void)btnAction:(UIButton *)btn{ + self.clickBlock(btn); +} +@end diff --git a/GIGA/Category/UINavigationBar+Custom.h b/GIGA/Category/UINavigationBar+Custom.h new file mode 100644 index 0000000..d720c33 --- /dev/null +++ b/GIGA/Category/UINavigationBar+Custom.h @@ -0,0 +1,20 @@ +// +// UINavigationBar+Custom.h +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import + +@interface UINavigationBar (Custom) + +- (void)cnSetBackgroundColor:(UIColor *)backgroundColor; +- (void)cnReset; +//设置透明导航 +-(void)setClearNav; + +-(void)resetBackgroundImage; + +@end diff --git a/GIGA/Category/UINavigationBar+Custom.m b/GIGA/Category/UINavigationBar+Custom.m new file mode 100644 index 0000000..0afce13 --- /dev/null +++ b/GIGA/Category/UINavigationBar+Custom.m @@ -0,0 +1,65 @@ +// +// UINavigationBar+Custom.m +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// +#import +#import "UINavigationBar+Custom.h" +static char overlayKey; + +@implementation UINavigationBar (Custom) +- (UIView *)overlay +{ + return objc_getAssociatedObject(self, &overlayKey); +} + +- (void)setOverlay:(UIView *)overlay +{ + objc_setAssociatedObject(self, &overlayKey, overlay, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (void)cnSetBackgroundColor:(UIColor *)backgroundColor +{ + if (!self.overlay) { + [self setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; + self.overlay = [[UIView alloc] initWithFrame:CGRectMake(0, -20, [UIScreen mainScreen].bounds.size.width, CGRectGetHeight(self.bounds) + 20)]; + self.overlay.userInteractionEnabled = NO; + self.overlay.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + [self insertSubview:self.overlay atIndex:0]; + } + + self.overlay.backgroundColor = backgroundColor; +} + +- (void)cnReset +{ + + [self setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; + [self.overlay removeFromSuperview]; + self.overlay = nil; +} + +-(void)setClearNav +{ + + [self setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault]; + //设置那条横线直接隐藏 + self.shadowImage = [[UIImage alloc] init]; + if (self.overlay) { + [self.overlay removeFromSuperview]; + self.overlay = nil; + } + +} + +-(void)resetBackgroundImage{ + + [self setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault]; + [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO]; + + +} + +@end diff --git a/GIGA/Category/UIView+Sizes.h b/GIGA/Category/UIView+Sizes.h new file mode 100755 index 0000000..f120bb8 --- /dev/null +++ b/GIGA/Category/UIView+Sizes.h @@ -0,0 +1,87 @@ +// +// Copyright 2009-2010 Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#import +#import + +@interface UIView (Sizes) + +/** + * Shortcut for frame.origin.x. + * + * Sets frame.origin.x = left + */ +@property (nonatomic) CGFloat left; + +/** + * Shortcut for frame.origin.y + * + * Sets frame.origin.y = top + */ +@property (nonatomic) CGFloat top; + +/** + * Shortcut for frame.origin.x + frame.size.width + * + * Sets frame.origin.x = right - frame.size.width + */ +@property (nonatomic) CGFloat right; + +/** + * Shortcut for frame.origin.y + frame.size.height + * + * Sets frame.origin.y = bottom - frame.size.height + */ +@property (nonatomic) CGFloat bottom; + +/** + * Shortcut for frame.size.width + * + * Sets frame.size.width = width + */ +@property (nonatomic) CGFloat width; + +/** + * Shortcut for frame.size.height + * + * Sets frame.size.height = height + */ +@property (nonatomic) CGFloat height; + +/** + * Shortcut for center.x + * + * Sets center.x = centerX + */ +@property (nonatomic) CGFloat centerX; + +/** + * Shortcut for center.y + * + * Sets center.y = centerY + */ +@property (nonatomic) CGFloat centerY; + +/** + * Shortcut for frame.origin + */ +@property (nonatomic) CGPoint origin; + +/** + * Shortcut for frame.size + */ +@property (nonatomic) CGSize size; + +@end diff --git a/GIGA/Category/UIView+Sizes.m b/GIGA/Category/UIView+Sizes.m new file mode 100755 index 0000000..6f86316 --- /dev/null +++ b/GIGA/Category/UIView+Sizes.m @@ -0,0 +1,118 @@ +// +// Copyright 2009-2010 Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#import "UIView+Sizes.h" + +@implementation UIView (Sizes) + +- (CGFloat)left { + return self.frame.origin.x; +} + +- (void)setLeft:(CGFloat)x { + CGRect frame = self.frame; + frame.origin.x = floorf(x); + self.frame = frame; +} + +- (CGFloat)top { + return self.frame.origin.y; +} + +- (void)setTop:(CGFloat)y { + CGRect frame = self.frame; + frame.origin.y = floorf(y); + self.frame = frame; +} + +- (CGFloat)right { + return self.frame.origin.x + self.frame.size.width; +} + +- (void)setRight:(CGFloat)right { + CGRect frame = self.frame; + frame.origin.x = floorf(right - frame.size.width); + self.frame = frame; +} + +- (CGFloat)bottom { + return self.frame.origin.y + self.frame.size.height; +} + +- (void)setBottom:(CGFloat)bottom { + CGRect frame = self.frame; + frame.origin.y = floorf(bottom - frame.size.height); + self.frame = frame; +} + +- (CGFloat)centerX { + return self.center.x; +} + +- (void)setCenterX:(CGFloat)centerX { + self.center = CGPointMake(floorf(centerX), floorf(self.center.y)); +} + +- (CGFloat)centerY { + return self.center.y; +} + +- (void)setCenterY:(CGFloat)centerY { + self.center = CGPointMake(floorf(self.center.x), floorf(centerY)); +} + +- (CGFloat)width { + return self.frame.size.width; +} + +- (void)setWidth:(CGFloat)width { + CGRect frame = self.frame; + frame.size.width = floorf(width); + self.frame = frame; +} + +- (CGFloat)height { + return self.frame.size.height; +} + +- (void)setHeight:(CGFloat)height { + CGRect frame = self.frame; + frame.size.height = floorf(height); + self.frame = frame; +} + +- (CGPoint)origin { + return self.frame.origin; +} + +- (void)setOrigin:(CGPoint)origin { + CGRect frame = self.frame; + frame.origin = origin; + self.frame = frame; +} + +- (CGSize)size { + return self.frame.size; +} + +- (void)setSize:(CGSize)size { + CGRect frame = self.frame; + frame.size = CGSizeMake(floorf(size.width), floorf(size.height)); + self.frame = frame; +} + +@end + diff --git a/GIGA/Common/BaseVC/GiGaBaseNavViewController.h b/GIGA/Common/BaseVC/GiGaBaseNavViewController.h new file mode 100644 index 0000000..184f598 --- /dev/null +++ b/GIGA/Common/BaseVC/GiGaBaseNavViewController.h @@ -0,0 +1,13 @@ +// +// GiGaBaseNavViewController.h +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import + +@interface GiGaBaseNavViewController : UINavigationController + +@end diff --git a/GIGA/Common/BaseVC/GiGaBaseNavViewController.m b/GIGA/Common/BaseVC/GiGaBaseNavViewController.m new file mode 100644 index 0000000..a55bd63 --- /dev/null +++ b/GIGA/Common/BaseVC/GiGaBaseNavViewController.m @@ -0,0 +1,68 @@ +// +// GiGaBaseNavViewController.m +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaBaseNavViewController.h" + +@interface GiGaBaseNavViewController () + +@end + +@implementation GiGaBaseNavViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + // Do any additional setup after loading the view. + self.interactivePopGestureRecognizer.delegate = (id)self; + self.view.backgroundColor = UIColor.whiteColor; +} + +-(UIStatusBarStyle)preferredStatusBarStyle +{ + return UIStatusBarStyleDefault; +} + +-(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated +{ + if (self.viewControllers.count > 0) { + viewController.hidesBottomBarWhenPushed = YES; + } + + [super pushViewController:viewController animated:animated]; + if (self.viewControllers.count > 1 ) { + //自定义返回按钮 + UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom]; + [backBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal]; + backBtn.backgroundColor = [UIColor redColor]; + [backBtn addTarget:self action:@selector(backItemAction) forControlEvents:UIControlEventTouchUpInside]; + UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn]; + viewController.navigationItem.leftBarButtonItem = backItem; + + } +} + +-(void)backItemAction{ + + [super popViewControllerAnimated:YES]; +} + +- (void)didReceiveMemoryWarning { + [super didReceiveMemoryWarning]; + // Dispose of any resources that can be recreated. +} + +/* +#pragma mark - Navigation + +// In a storyboard-based application, you will often want to do a little preparation before navigation +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. +} +*/ + +@end diff --git a/GIGA/Common/BaseVC/GiGaBaseViewController.h b/GIGA/Common/BaseVC/GiGaBaseViewController.h new file mode 100644 index 0000000..b1736f0 --- /dev/null +++ b/GIGA/Common/BaseVC/GiGaBaseViewController.h @@ -0,0 +1,29 @@ +// +// GiGaBaseViewController.h +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import + +@interface GiGaBaseViewController : UIViewController +{ + UIView *emptyView; +} + +//- (void)setNavigationViewWithBGColor:(UIColor *)bgColor TitleColor:(UIColor *)titleColor; +//- (void)setNavigationViewHidden:(BOOL)hidden; +//- (void)addBackButtonWithImageName:(NSString *)imageName; +//- (void)setBackButtonHidden:(BOOL)hidden; +//- (void)setNavigationViewBottomLineHidden:(BOOL)hidden; +// +//- (void)addRightButtonWithBGImageName:(NSString *)rightImageName action:(SEL)rightAction; +// +//- (void)addRefreshHeaderFooterForTableView:(UITableView *)tableView +// refreshHeaderSelector:(SEL)refreshHeaderSelector +// refreshFooterSelector:(SEL)refreshFooterSelector; + + +@end diff --git a/GIGA/Common/BaseVC/GiGaBaseViewController.m b/GIGA/Common/BaseVC/GiGaBaseViewController.m new file mode 100644 index 0000000..0177315 --- /dev/null +++ b/GIGA/Common/BaseVC/GiGaBaseViewController.m @@ -0,0 +1,44 @@ +// +// GiGaBaseViewController.m +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaBaseViewController.h" + +@interface GiGaBaseViewController () +{ +// UIColor *navigationBarBGColor; //导航栏背景色 +// UIColor *navigationBarTitleColor; //导航栏标题字色 +// SEL _rightBtnAction; +// SEL _refreshHeaderSelector; +// SEL _refreshFooterSelector; +} + +@end + +@implementation GiGaBaseViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + // Do any additional setup after loading the view. +} + +- (void)didReceiveMemoryWarning { + [super didReceiveMemoryWarning]; + // Dispose of any resources that can be recreated. +} + +/* +#pragma mark - Navigation + +// In a storyboard-based application, you will often want to do a little preparation before navigation +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. +} +*/ + +@end diff --git a/GIGA/Common/GiGaHelper.h b/GIGA/Common/GiGaHelper.h new file mode 100644 index 0000000..0321b5f --- /dev/null +++ b/GIGA/Common/GiGaHelper.h @@ -0,0 +1,41 @@ +// +// GiGaHelper.h +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import + +@interface GiGaHelper : NSObject +/** + * 获取当前时间 格式 yyyy-MM-dd hh:mm:ss + */ + ++(NSString *) getNowTimeString; +/** + * 时间转时间戳 + */ + ++(long) timeStampWithDate:(NSDate *) timeDate; + +/** + * 时间戳转时间 + */ + ++ (NSString *) dateWithTimeStamp:(long) longValue; +/** + * 根据时间间隔获取未来时间戳 + hour 几小时 + min 几分钟 + second 几秒 + */ ++(long)getFutureTimetstamp:(NSUInteger)hour minute:(NSUInteger)min second:(NSUInteger)second; + +/** + * NSTimeInterval 转分钟秒 + */ ++(NSString *)stringWithNSTimerinterval:(NSTimeInterval)interval; + +@end diff --git a/GIGA/Common/GiGaHelper.m b/GIGA/Common/GiGaHelper.m new file mode 100644 index 0000000..d890eeb --- /dev/null +++ b/GIGA/Common/GiGaHelper.m @@ -0,0 +1,72 @@ +// +// GiGaHelper.m +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaHelper.h" + +@implementation GiGaHelper + ++(NSString *) getNowTimeString{ + + NSDate *now = [NSDate date]; + NSDateFormatter *formatDate = [[NSDateFormatter alloc] init]; + formatDate.dateFormat= @"yyyy-MM-dd hh:mm:ss"; + NSString *dayStr = [formatDate stringFromDate:now]; + + return dayStr; +} + ++(long) timeStampWithDate:(NSDate *) timeDate{ + long timeStamp = 0; + NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; + [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; + NSString *timeString = [formatter stringFromDate:timeDate]; + NSDate *date = [formatter dateFromString:timeString]; + timeStamp = (long)[date timeIntervalSince1970]; + + return timeStamp; +} + ++ (NSString *) dateWithTimeStamp:(long) longValue{ + + long value = longValue; + NSDateFormatter *formatDay = [[NSDateFormatter alloc] init]; + formatDay.dateFormat = @"yyyy-MM-dd hh:mm:ss"; + NSNumber *time = [NSNumber numberWithLong:value]; + //转换成NSTimeInterval + NSTimeInterval nsTimeInterval = [time longValue]; + NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:nsTimeInterval]; + NSString *dayStr = [formatDay stringFromDate:date]; + return dayStr; + +} + ++(long)getFutureTimetstamp:(NSUInteger)hour minute:(NSUInteger)min second:(NSUInteger)second{ + + NSDate *datenow = [NSDate date]; + NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; + [formatter setDateFormat:@"YYYY年MM月dd日HH:mm:ss"]; + NSTimeInterval timeInterval = hour * 3600 + min * 60 + second; + NSDate *futrueDate = [datenow dateByAddingTimeInterval:timeInterval]; + NSString *futrueTimeStr = [formatter stringFromDate:futrueDate]; + NSDate *furtureformatDate = [formatter dateFromString:futrueTimeStr]; + long futrueTimestamp= [furtureformatDate timeIntervalSince1970]; + + return futrueTimestamp; + +} + ++(NSString *)stringWithNSTimerinterval:(NSTimeInterval)interval{ + + NSInteger min = interval / 60; + NSInteger sec = (NSInteger) interval % 60; + return [NSString stringWithFormat:@"%02ld:%02ld",min,sec]; + +} + + +@end diff --git a/GIGA/Common/GiGaNetTool/GiGaAPIRequest.h b/GIGA/Common/GiGaNetTool/GiGaAPIRequest.h new file mode 100644 index 0000000..30451ad --- /dev/null +++ b/GIGA/Common/GiGaNetTool/GiGaAPIRequest.h @@ -0,0 +1,71 @@ +// +// GiGaAPIRequest.h +// GIGA +// +// Created by lianxiang on 2018/8/15. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import +#import "GiGaAPIResult.h" +@class GiGaAPIRequest; +#define DEFALUT_APIREQUEST_TIMEOUT 20 + +typedef enum GiGaRequestType { + kRequestTypeGet, + kRequestTypePost, + kRequestTypeUpload, + kRequestTypeMultiUpload +}GiGaRequestTyp; + +typedef enum ApiResultFormat { + kApiResultJson, + kApiResultXml, +}ApiResultFormat; + +@protocol GiGaApiRquestDelegate +@optional + +- (void)serverApiFinishedSuccessed:(GiGaAPIRequest *)api result:(GiGaAPIResult *)result; +- (void)serverApiRequestFailed:(GiGaAPIRequest *)api error:(NSError *)error; +- (void)serverApiFinishedFailed:(GiGaAPIRequest *)api result:(GiGaAPIResult *)result; + +@end + +@interface GiGaAPIRequest : NSObject + +#pragma mark - porperty +/** 请求类型 */ +@property (nonatomic, readonly) GiGaRequestTyp requestType; +/** 请求返回的格式 */ +@property (nonatomic, readonly) ApiResultFormat resultFormat; +/** 请求超时时间 */ +@property (nonatomic, readonly) NSTimeInterval timeout; +/** 服务器地址 */ +@property (nonatomic, readonly) NSString *serviceUrl; +/** 请求路径 */ +@property (nonatomic, readonly) NSString *fullUrl; +/** 代理 */ +@property (nonatomic, weak) id delegate; +/** 请求参数数组 */ +@property (nonatomic, strong) NSMutableArray *params; + +#pragma mark - Method +- (id)initWithDelegate:(id)delegate; +/** + * 拼接公共参数 + */ +- (void)appendBaseParams; + +#pragma mark - APIRequestDelegate +/** + * 返回数据调用方法 + */ +- (void)callBackFinishedWithDictionary:(NSDictionary *)dic; +/** + * 返回数据错误 + */ +- (void)callBackFailed:(NSError *)error; + + +@end diff --git a/GIGA/Common/GiGaNetTool/GiGaAPIRequest.m b/GIGA/Common/GiGaNetTool/GiGaAPIRequest.m new file mode 100644 index 0000000..b61ffb8 --- /dev/null +++ b/GIGA/Common/GiGaNetTool/GiGaAPIRequest.m @@ -0,0 +1,81 @@ +// +// GiGaAPIRequest.m +// GIGA +// +// Created by lianxiang on 2018/8/15. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaAPIRequest.h" +#import "GiGaServerConfig.h" +@implementation GiGaAPIRequest + +- (id)initWithDelegate:(id)delegate +{ + if (self = [super init]) { + self.params = [NSMutableArray array]; + self.delegate = delegate; + } + + return self; +} +//默认Get访问 +- (GiGaRequestTyp)requestType +{ + return kRequestTypeGet; +} + +//默认超时时间 +- (NSTimeInterval)timeout +{ + return DEFALUT_APIREQUEST_TIMEOUT; +} + +//服务器地址 +-(NSString *)serviceUrl{ + return [GiGaServerConfig getMainUrl]; +} + +/** 拼接的请求地址 */ + +// +- (NSString *)fullUrl +{ + // 服务器地址 和 接口名 + NSString *url = [NSString stringWithFormat:@"%@",self.serviceUrl]; + + return url; +} +// 数据请求完成的 回调 +- (void)callBackFinishedWithDictionary:(NSDictionary *)dic +{ + // 处理 responseObject + GiGaAPIResult *resu = [[GiGaAPIResult alloc] initWithDictionary:dic]; + // error ID = 0 + if (resu.success) { + if (self.delegate && [self.delegate respondsToSelector:@selector(serverApiFinishedSuccessed: result:)]) { + // + [self.delegate serverApiFinishedSuccessed:self result:resu]; + } + // error ID = 1 + } else { + if (self.delegate && [self.delegate respondsToSelector:@selector(serverApiFinishedFailed:result:)]) { + [self.delegate serverApiFinishedFailed:self result:resu]; + } + } +} + +// 数据请求失败的回调 +- (void)callBackFailed:(NSError *)error +{ + if (self.delegate && [self.delegate respondsToSelector:@selector(serverApiRequestFailed:error:)]) { + [self.delegate serverApiRequestFailed:self error:error]; + } +} + +// 拼接的基本参数 +- (void)appendBaseParams +{ + +} +@end diff --git a/GIGA/Common/GiGaNetTool/GiGaAPIResult.h b/GIGA/Common/GiGaNetTool/GiGaAPIResult.h new file mode 100644 index 0000000..3089b82 --- /dev/null +++ b/GIGA/Common/GiGaNetTool/GiGaAPIResult.h @@ -0,0 +1,24 @@ +// +// GiGaAPIResult.h +// GIGA +// +// Created by lianxiang on 2018/8/15. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import + +@interface GiGaAPIResult : NSObject + +/** 提示信息 */ +@property (nonatomic, copy) NSString *message; +/** 请求状态 */ +@property (nonatomic, assign) NSInteger status; +/** 请求是否成功 */ +@property (nonatomic, readonly) BOOL success; +/** 接收数据的字典 */ +@property (nonatomic, strong) NSDictionary *dic; + +- (id)initWithDictionary:(NSDictionary *)dic; + +@end diff --git a/GIGA/Common/GiGaNetTool/GiGaAPIResult.m b/GIGA/Common/GiGaNetTool/GiGaAPIResult.m new file mode 100644 index 0000000..61d7ce0 --- /dev/null +++ b/GIGA/Common/GiGaNetTool/GiGaAPIResult.m @@ -0,0 +1,49 @@ +// +// GiGaAPIResult.m +// GIGA +// +// Created by lianxiang on 2018/8/15. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaAPIResult.h" + +@implementation GiGaAPIResult + +-(BOOL)success{ + + return self.status == 0; + +} + +-(id)initWithDictionary:(NSDictionary *)dic +{ + if (self = [super init]) { + @try { + if (dic && ![dic isKindOfClass:[NSNull class]]) { + self.status = [[dic objectForKey:@"errorcode"] intValue];//待定 + self.message = [dic objectForKey:@""];//待定 + NSDictionary *data = [[dic objectForKey:@"result"] objectForKey:@"data"]; + self.dic = data; + + }else{ + self.message = @"网络错误"; + self.dic = nil; + self.status = 1; + } + + } + @catch(NSException *exception) { + self.dic = dic; + self.status = 0; + + } + @finally { + + } + } + + return self; +} + +@end diff --git a/GIGA/Common/GiGaNetTool/GiGaNetManager.h b/GIGA/Common/GiGaNetTool/GiGaNetManager.h new file mode 100644 index 0000000..1885ee9 --- /dev/null +++ b/GIGA/Common/GiGaNetTool/GiGaNetManager.h @@ -0,0 +1,15 @@ +// +// GiGaNetManager.h +// GIGA +// +// Created by lianxiang on 2018/8/15. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import +#import "GiGaAPIRequest.h" +@interface GiGaNetManager : NSObject ++(GiGaNetManager *)shareInstance; ++(void)request:(GiGaAPIRequest*)api; + +@end diff --git a/GIGA/Common/GiGaNetTool/GiGaNetManager.m b/GIGA/Common/GiGaNetTool/GiGaNetManager.m new file mode 100644 index 0000000..d4ae1b2 --- /dev/null +++ b/GIGA/Common/GiGaNetTool/GiGaNetManager.m @@ -0,0 +1,70 @@ +// +// GiGaNetManager.m +// GIGA +// +// Created by lianxiang on 2018/8/15. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaNetManager.h" +#import "AFNetworking.h" +#import "GiGaServerConfig.h" +@interface GiGaNetManager() + +@end + +@implementation GiGaNetManager + ++ (GiGaNetManager *)shareInstance{ + static GiGaNetManager *instance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + instance = [[self alloc] init]; + }); + return instance; +} + ++ (void)request:(GiGaAPIRequest *)api{ + + NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; + NSURL *baseUrl = [NSURL URLWithString:[GiGaServerConfig getMainUrl]]; + AFHTTPSessionManager*manager=[[AFHTTPSessionManager alloc] initWithBaseURL:baseUrl sessionConfiguration:configuration]; + + manager.responseSerializer=[AFHTTPResponseSerializer serializer]; + switch (api.requestType) { + case kRequestTypeGet: + + { + [manager GET:api.fullUrl parameters:api.params progress:^(NSProgress * _Nonnull downloadProgress) { + + } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + NSDictionary *outDic = (NSDictionary *)responseObject; + [api callBackFinishedWithDictionary:outDic]; + + } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + [api callBackFailed:error]; + }]; + + } + break; + + case kRequestTypePost: + { + [manager POST:api.fullUrl parameters:api.params progress:^(NSProgress * _Nonnull uploadProgress) { + + } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { + NSDictionary *outDic = (NSDictionary *)responseObject; + [api callBackFinishedWithDictionary:outDic]; + } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { + [api callBackFailed:error]; + }]; + } + break; + + + default: + break; + } +} + +@end diff --git a/GIGA/Common/GiGaUserDB/GiGaUserDefault.h b/GIGA/Common/GiGaUserDB/GiGaUserDefault.h new file mode 100644 index 0000000..8aa16da --- /dev/null +++ b/GIGA/Common/GiGaUserDB/GiGaUserDefault.h @@ -0,0 +1,42 @@ +// +// GiGaUserDefault.h +// GIGA +// +// Created by lianxiang on 2018/8/15. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import + + + + +@interface GiGaUserDefault : NSObject + ++(void)saveUserId:(NSString *)userId; ++(NSString *)getCurentUserId; ++(void)removeUserId; ++(BOOL)isUserLogin; +/** + 保存用户表版本号 + */ ++(void)saveDBVersion:(NSInteger)versionNum; + ++(NSInteger)getOldVersion; + +/** + 新手页(蒙版) + @param showedGaurd 是否展示过 default NO + */ ++(void)saveUsergaurdflag:(BOOL)showedGaurd; ++(BOOL)isShowedGaurd; + +/** + App 引导页 + @param showedGaurd 是否展示过 default NO + */ ++(void)saveAppGaurdflag:(BOOL)showedGaurd; ++(BOOL)isShowedAppGaurd; + + +@end diff --git a/GIGA/Common/GiGaUserDB/GiGaUserDefault.m b/GIGA/Common/GiGaUserDB/GiGaUserDefault.m new file mode 100644 index 0000000..550e555 --- /dev/null +++ b/GIGA/Common/GiGaUserDB/GiGaUserDefault.m @@ -0,0 +1,79 @@ +// +// GiGaUserDefault.m +// GIGA +// +// Created by lianxiang on 2018/8/15. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaUserDefault.h" + +NSString *const kUserManagerVerision = @"GiGAUserDBVeriosn"; +NSString *const GIGADEFAULTKEY_USERID = @"GiGaUserId"; +NSString *const kShowUserGuard = @"ShowUserGuard"; +NSString *const kShowAppGuard = @"ShowAppGuard"; + +@implementation GiGaUserDefault + ++(void)saveUserId:(NSString *)userId{ + + UD_SET_KEY_VALUE(GIGADEFAULTKEY_USERID, userId); + +} + ++(NSString*)getCurentUserId{ + + NSString *userid = UD_GET_VALUE(GIGADEFAULTKEY_USERID); + return userid; +} + ++(void)removeUserId{ + + UD_REMOVE_KEY(GIGADEFAULTKEY_USERID); +} + ++(BOOL)isUserLogin{ + + NSString *uid = UD_GET_VALUE(GIGADEFAULTKEY_USERID); + return uid ? YES : NO; + +} + ++(void)saveDBVersion:(NSInteger)versionNum{ + + NSNumber *verNum = [NSNumber numberWithInteger:versionNum]; + UD_SET_KEY_VALUE(verNum.stringValue, kUserManagerVerision); + +} + ++ (NSInteger)getOldVersion{ + + return (NSInteger)UD_GET_VALUE(kUserManagerVerision); + +} + ++(void)saveUsergaurdflag:(BOOL)showedGaurd +{ + [UD_STADARDUD setBool:showedGaurd forKey:kShowUserGuard]; + [UD_STADARDUD synchronize]; + +} + ++(BOOL)isShowedGaurd +{ + BOOL showedGaurd = [UD_STADARDUD boolForKey:kShowUserGuard]; + return showedGaurd; +} + ++(void)saveAppGaurdflag:(BOOL)showedGaurd; +{ + [UD_STADARDUD setBool:showedGaurd forKey:kShowAppGuard]; + [UD_STADARDUD synchronize]; +} + ++(BOOL)isShowedAppGaurd{ + BOOL showedGaurd = [UD_STADARDUD boolForKey:kShowAppGuard]; + return showedGaurd; +} + +@end diff --git a/GIGA/Common/GiGaUserDB/GiGaUserManager.h b/GIGA/Common/GiGaUserDB/GiGaUserManager.h new file mode 100644 index 0000000..1ca0c67 --- /dev/null +++ b/GIGA/Common/GiGaUserDB/GiGaUserManager.h @@ -0,0 +1,25 @@ +// +// GiGaUserManager.h +// GIGA +// +// Created by lianxiang on 2018/8/15. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import +#import "GiGaUser.h" +@interface GiGaUserManager : NSObject + +@property(nonatomic,strong) GiGaUser *user; + ++(instancetype)shareUser; +- (void)saveUser:(GiGaUser *)user; +- (GiGaUser*)getCurrentUser; +-(void)loginOut; + +/** + 版本升级检测 + */ +//-(void)detectionUserUpgrade; + +@end diff --git a/GIGA/Common/GiGaUserDB/GiGaUserManager.m b/GIGA/Common/GiGaUserDB/GiGaUserManager.m new file mode 100644 index 0000000..105b07f --- /dev/null +++ b/GIGA/Common/GiGaUserDB/GiGaUserManager.m @@ -0,0 +1,108 @@ +// +// GiGaUserManager.m +// GIGA +// +// Created by lianxiang on 2018/8/15. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaUserManager.h" +#import "YTKKeyValueStore.h" +#import "GiGaUserDefault.h" + +NSString *const GIGA_USER_TABLE = @"user_table"; +const static NSInteger GIGADB_USER_VER = 0;//当前数据库版本号 + +@interface GiGaUserManager() + +@property (nonatomic,strong) YTKKeyValueStore *store; +@property (nonatomic,strong) NSMutableArray *userArr; +@property (nonatomic,copy) NSString *userTabId; + +@end + +@implementation GiGaUserManager + ++ (instancetype)shareUser{ + static GiGaUserManager *userManager = nil; + static dispatch_once_t once; + dispatch_once(&once, ^{ + userManager = [[self alloc] init]; + + }); + + return userManager; +} + +-(instancetype)init{ + + self = [super init]; + if (self) { + // 打开名为GiGa.db的数据库,如果该文件不存在,则创新一个新的。 + self.store = [[YTKKeyValueStore alloc] initDBWithName:@"GiGa.db"]; + [self creatTableByName:GIGA_USER_TABLE]; + _userArr = [NSMutableArray new]; + [self detectionUserUpgrade]; + } + return self; +} + +//建表 +-(void)creatTableByName:(NSString *)tableName{ + [_store createTableWithName:tableName]; +} + +- (void)saveUser:(GiGaUser *)user{ + + self.user = user; + NSString *userTableId = [NSString stringWithFormat:@"%@",user.userId]; + self.userTabId = userTableId; + + //暂定只保留一个用户 + [_userArr removeAllObjects]; + [_userArr addObject:user]; + [_store putObject:_userArr withId:userTableId intoTable:GIGA_USER_TABLE]; + [GiGaUserDefault saveUserId:userTableId]; + +} + +//已登录 +-(GiGaUser *)getCurrentUser{ + + NSString *useriD = [GiGaUserDefault getCurentUserId]; + NSArray *usrA= [_store getObjectById:useriD fromTable:GIGA_USER_TABLE]; + if (usrA && usrA.count > 0) { + self.user = usrA[0]; + } + return self.user; +} + +// + +-(void)loginOut{ + self.user = nil; + [GiGaUserDefault removeUserId]; + +} + +- (void)detectionUserUpgrade{ + + NSInteger oldVerion = [GiGaUserDefault getOldVersion]; + if (GIGADB_USER_VER <= oldVerion) { + return; + } + [self upgradUserDBToNew]; + [GiGaUserDefault saveDBVersion:GIGADB_USER_VER]; +} + +-(void)upgradUserDBToNew{ + + if (_userArr.count <= 0) { + GILog(@"there is no user yet"); + return; + } + [_store putObject:_userArr withId:self.userTabId intoTable:GIGA_USER_TABLE]; + +} + +@end diff --git a/GIGA/Common/LXCountTimer/LXCountTimer.h b/GIGA/Common/LXCountTimer/LXCountTimer.h new file mode 100644 index 0000000..a64a96d --- /dev/null +++ b/GIGA/Common/LXCountTimer/LXCountTimer.h @@ -0,0 +1,30 @@ +// +// LXCountTimer.h +// Elastagen +// +// Created by lianxiang on 2018/8/12. +// Copyright © 2018年 jijia. All rights reserved. +// + +#import + +@interface LXCountTimer : NSObject +/** + * 用时间戳倒计时 + * starTimeStamp 开始的时间戳 + * finishTimeStamp 结束的时间戳 + */ +-(void)countDownWithStratTimeStamp:(long)starTimeStamp finishTimeStamp:(long)finishTimeStamp completeBlock:(void (^)(NSInteger day,NSInteger hour,NSInteger minute,NSInteger second))completeBlock; + + +/** + * 每秒走一次,回调block + */ +-(void)countDownWithPER_SECBlock:(void (^)(void))PER_SECBlock; + +/** + * 销毁倒计时 + */ +-(void)destoryTimer; + +@end diff --git a/GIGA/Common/LXCountTimer/LXCountTimer.m b/GIGA/Common/LXCountTimer/LXCountTimer.m new file mode 100644 index 0000000..8b71595 --- /dev/null +++ b/GIGA/Common/LXCountTimer/LXCountTimer.m @@ -0,0 +1,93 @@ +// +// LXCountTimer.m +// Elastagen +// +// Created by lianxiang on 2018/8/12. +// Copyright © 2018年 jijia. All rights reserved. +// + +#import "LXCountTimer.h" + +@interface LXCountTimer() +@property(nonatomic,retain) dispatch_source_t timer; +@property(nonatomic,retain) NSDateFormatter *dateFormatter; + +@end + +@implementation LXCountTimer + +-(void)countDownWithStratTimeStamp:(long)starTimeStamp finishTimeStamp:(long)finishTimeStamp completeBlock:(void (^)(NSInteger, NSInteger, NSInteger, NSInteger))completeBlock{ + + if (_timer == nil) { + + NSDate *finishDate =[self dateWithLong:finishTimeStamp]; + NSDate *startDate = [self dateWithLong:starTimeStamp]; + NSTimeInterval timerInterval =[finishDate timeIntervalSinceDate:startDate]; + __block int timeout = timerInterval; + if (timeout !=0) { + + dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); + dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);//每秒执行 + dispatch_source_set_event_handler(_timer, ^{ + if (timeout<=0) { + //记时结束, 关闭 + dispatch_source_cancel(self->_timer); + self->_timer = nil; + dispatch_async(dispatch_get_main_queue(), ^{ + completeBlock(0,0,0,0); + }); + }else{ + int days = (int)(timeout/(3600*24)); + int hours = (int)((timeout-days*24*3600)/3600); + int minute = (int)(timeout-days*24*3600-hours*3600)/60; + int second = timeout-days*24*3600-hours*3600-minute*60; + dispatch_async(dispatch_get_main_queue(), ^{ + completeBlock(days,hours,minute,second); + }); + timeout--; + } + }); + dispatch_resume(_timer); + } + + } +} + +-(void)countDownWithPER_SECBlock:(void (^)(void))PER_SECBlock{ + if (_timer==nil) { + dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue); + dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行 + dispatch_source_set_event_handler(_timer, ^{ + dispatch_async(dispatch_get_main_queue(), ^{ + PER_SECBlock(); + }); + }); + dispatch_resume(_timer); + } +} + +-(void)destoryTimer{ + if (_timer) { + dispatch_source_cancel(_timer); + _timer = nil; + } +} + +-(void)dealloc{ + NSLog(@"%s dealloc",object_getClassName(self)); + +} + +-(NSDate *)dateWithLong:(long)longValue{ + long value = longValue; + NSNumber *time = [NSNumber numberWithLong:value]; + //转换成NSTimeInterval + NSTimeInterval nsTimeInterval = [time longValue]; + NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:nsTimeInterval]; + return date; +} + + +@end diff --git a/GIGA/Common/Source/useragreement.html b/GIGA/Common/Source/useragreement.html new file mode 100644 index 0000000..cd6a38a --- /dev/null +++ b/GIGA/Common/Source/useragreement.html @@ -0,0 +1,44 @@ + + + + 用户协议 + + +
+ + +
+
+
+ + +
+
+ +
+

本协议是您与XXX公司(以下简称为“面膜时间”)之间就面膜时间所提供的服务及相关事宜所立订的契约,请您仔细阅读本注册协议,在您确认阅读并选择注册后,本协议即构成对双方有约束力的法律文件。


第一条 服务条款的确认和接纳


1.面膜时间的各项电子服务的所有权和运作权归“面膜时间”所有。客户同意所有注册协议条款并完成注册程序,才能成为面膜时间的正式客户。客户确认:本协议条款是处理双方权利义务的契约,始终有效,法律另有强制性规定或双方另有特别约定的,依其规定。

2.面膜时间的各项电子服务的所有权和运作权归“面膜时间”所有。客户同意所有注册协议条款并完成注册程序,才能成为面膜时间的正式客户。客户确认:本协议条款是处理双方权利义务的契约,始终有效,法律另有强制性规定或双方另有特别约定的,依其规定。

3.如果您在18周岁以下,您只能在父母或监护人的监护参与下才能使用面膜时间。

4.“面膜时间”保留在中华人民共和国大陆地区法施行之法律允许的范围内独自决定拒绝服务、关闭客户账户、清除或编辑内容或取消订单的权利。


第二条 法律管辖和适用


本协议的订立、执行和解释及争议的解决均应适用在中华人民共和国大陆地区适用之有效法律(但不包括其冲突法规则)。 如发生优品汇服务条款与适用之法律相抵触时,则这些条款将完全按法律规定重新解释,而其它有效条款继续有效。 如缔约方就本协议内容或其执行发生任何争议,双方应尽力友好协商解决;协商不成时,任何一方均可向有管辖权的中华人民共和国大陆地区法院提起诉讼。


第三条 面膜时间服务


1.面膜时间的各项电子服务的所有权和运作权归“面膜时间”所有。客户同意所有注册协议条款并完成注册程序,才能成为面膜时间的正式客户。客户确认:本协议条款是处理双方权利义务的契约,始终有效,法律另有强制性规定或双方另有特别约定的,依其规定。


第四条 客户信息


1.面膜时间的各项电子服务的所有权和运作权归“面膜时间”所有。客户同意所有注册协议条款并完成注册程序,才能成为面膜时间的正式客户。客户确认:本协议条款是处理双方权利义务的契约,始终有效,法律另有强制性规定或双方另有特别约定的,依其规定。

2.面膜时间的各项电子服务的所有权和运作权归“面膜时间”所有。客户同意所有注册协议条款并完成注册程序,才能成为面膜时间的正式客户。客户确认:本协议条款是处理双方权利义务的契约,始终有效,法律另有强制性规定或双方另有特别约定的,依其规定。

3.面膜时间的各项电子服务的所有权和运作权归“面膜时间”所有。客户同意所有注册协议条款并完成注册程序,才能成为面膜时间的正式客户。客户确认:本协议条款是处理双方权利义务的契约,始终有效,法律另有强制性规定或双方另有特别约定的,依其规定。

4.面膜时间的各项电子服务的所有权和运作权归“面膜时间”所有。客户同意所有注册协议条款并完成注册程序,才能成为面膜时间的正式客户。客户确认:本协议条款是处理双方权利义务的契约,始终有效,法律另有强制性规定或双方另有特别约定的,依其规定。

5.面膜时间的各项电子服务的所有权和运作权归“面膜时间”所有。客户同意所有注册协议条款并完成注册程序,才能成为面膜时间的正式客户。客户确认:本协议条款是处理双方权利义务的契约,始终有效,法律另有强制性规定或双方另有特别约定的,依其规定。


第五条 客户依法言行义务


本协议依据国家相关法律法规规章制定,客户同意严格遵守以下义务:

1.不得传输或发表:煽动抗拒、破坏宪法和法律、行政法规实施的言论,煽动颠覆国家政权,推翻社会主义制度的言论,煽动分裂国家、破坏国家统一的的言论,煽动民族仇恨、民族歧视、破坏民族团结的言论;

2.从中国大陆向境外传输资料信息时必须符合中国有关法规;

3.不得利用面膜时间从事洗钱、窃取商业秘密、窃取个人信息等违法犯罪活动;

4.不得干扰面膜时间的正常运转,不得侵入面膜时间及国家计算机信息系统;

5.不得传输或发表任何违法犯罪的、骚扰性的、中伤他人的、辱骂性的、恐吓性的、伤害性的、庸俗的,淫秽的、不文明的等信息资料;

6.不得传输或发表损害国家社会公共利益和涉及国家安全的信息资料或言论;

7.不得教唆他人从事本条所禁止的行为;

8.不得利用在面膜时间注册的账户进行牟利性经营活动;

9.不得发布任何侵犯他人著作权、商标权等知识产权或合法权利的内容;

面膜时间保有删除站内各类不符合法律政策或不真实的信息内容而无须通知客户的权利。

若客户未遵守以上规定的,面膜时间有权作出独立判断并采取暂停或关闭客户帐号等措施。客户须对自己在网上的言论和行为承担法律责任。


有任何疑问,可向平台客服咨询。阅读协议的过程中,如果您不同意相关协议或其中任何条款约定,您应立即停止注册程序。

+
+
+
+
+
+ + +
+
+
+ + +
+
+ +
+

用户协议

+
+
+
+
+
+
+ + diff --git a/GIGA/Config/GIGA.h b/GIGA/Config/GIGA.h new file mode 100644 index 0000000..47b0988 --- /dev/null +++ b/GIGA/Config/GIGA.h @@ -0,0 +1,69 @@ +// +// GIGA.h +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#ifndef GIGA_h +#define GIGA_h + +#define UD_STADARDUD [NSUserDefaults standardUserDefaults] + +#define UD_REMOVE_KEY(__KEY__) \ +[[NSUserDefaults standardUserDefaults] removeObjectForKey:__KEY__]; \ +UD_SYNC + +#define UD_GET_VALUE(__KEY__) [[NSUserDefaults standardUserDefaults] valueForKey:__KEY__]; + +#define UD_SET_KEY_VALUE(__KEY__, __VALUE__) \ +[[NSUserDefaults standardUserDefaults] setValue:(__VALUE__) forKey:(__KEY__)]; \ +UD_SYNC + +#define UD_SYNC [[NSUserDefaults standardUserDefaults] synchronize]; + +// MARK: NotificationCenter - Add + +#define NC_ADD_TARGET_NAME_OBJECT(__target__, __sel__, __name__, __object__) [[NSNotificationCenter defaultCenter] addObserver:(__target__) selector:(__sel__) name:(__name__) object:(__object__)]; +#define NC_POST_NAME_OBJECT(__name__,__object__) [[NSNotificationCenter defaultCenter] postNotificationName:(__name__) object:(__object__)]; + +#define NC_REMOVE_NAME(__target__,__name__,__object__) [[NSNotificationCenter defaultCenter] removeObserver:(__target__) name:(__name__) object:(__object__)]; + +// MAKR: Noti Names +#define USER_GUARD_DISSMISS @"userGaurdDissmiss" +#define APP_GUARD_DISSMISS @"APPGaurdDissmiss" + + + +#define GIGARGB(R,G,B,A) [UIColor colorWithRed:R/255.0f green:G/255.0f blue:B/255.0f alpha:A] + +#define GIGAUIColorFromRGB_A(rgbValue,alphaValue) [UIColor \ +colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \ +green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \ +blue:((float)(rgbValue & 0xFF))/255.0 alpha:alphaValue] + +#define GIGAUIColorFromRGBA(rgbValue) [UIColor \ +colorWithRed:((float)((rgbValue & 0xFF000000) >> 24))/255.0 \ +green:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \ +blue:((float)((rgbValue & 0xFF00) >> 8))/255.0 \ +alpha:((float)(rgbValue & 0xFF))/255.0] + + +#define SCREEN [UIScreen mainScreen] +#define WIDTH self.view.frame.size.width +#define HEIGHT self.view.frame.size.height +#define KMainW [UIScreen mainScreen].bounds.size.width +#define KMainH [UIScreen mainScreen].bounds.size.height + +#define ISIOS8 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 ? YES : NO) +#define ISIOS9 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0 ? YES : NO) +#define ISIOS10 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0 ? YES : NO) + +#define weakify(var) __weak typeof(var) weakSelf = var +#define strongify(var) __strong typeof(var) strongSelf = var + +#define textFontWeightSize(X,W) [UIFont systemFontOfSize:X *([UIScreen mainScreen].bounds.size.width / 320.0) weight:W] + + +#endif /* GIGA_h */ diff --git a/GIGA/Config/GiGaServerConfig.h b/GIGA/Config/GiGaServerConfig.h new file mode 100644 index 0000000..e4d62a4 --- /dev/null +++ b/GIGA/Config/GiGaServerConfig.h @@ -0,0 +1,16 @@ +// +// GiGaServerConfig.h +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import + +@interface GiGaServerConfig : NSObject + ++ (void)setServerType:(NSInteger) type; ++ (NSString *)getMainUrl; + +@end diff --git a/GIGA/Config/GiGaServerConfig.m b/GIGA/Config/GiGaServerConfig.m new file mode 100644 index 0000000..4626236 --- /dev/null +++ b/GIGA/Config/GiGaServerConfig.m @@ -0,0 +1,38 @@ +// +// GiGaServerConfig.m +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaServerConfig.h" + +@implementation GiGaServerConfig ++ (void)setServerType:(NSInteger)type +{ +#if defined(DEBUG) || defined(RELEASE_VERTION_TEST) + +#endif + switch (type) { + case 0://测试环境 + { + + [[NSUserDefaults standardUserDefaults] setValue:@"https://" forKey:@"MainUrl"]; + } break; + case 1: //生产环境 + { + [[NSUserDefaults standardUserDefaults] setValue:@"https://" forKey:@"MainUrl"]; + } break; + + default: + break; + } +} + ++ (NSString *)getMainUrl +{ + return [[NSUserDefaults standardUserDefaults] objectForKey:@"MainUrl"]; +} + +@end diff --git a/GIGA/GIGA.pch b/GIGA/GIGA.pch new file mode 100644 index 0000000..412506b --- /dev/null +++ b/GIGA/GIGA.pch @@ -0,0 +1,22 @@ +// +// GIGA.pch +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#ifndef GIGA_pch +#define GIGA_pch + +// Include any system framework and library headers here that should be included in all compilation units. +// You will also need to set the Prefix Header build setting of one or more of your targets to reference this file. +#import "GIGA.h" + +#ifdef DEBUG +#define GILog(fmt,...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) +#else +#define GILog(...) +#endif + +#endif /* GIGA_pch */ diff --git a/GIGA/Info.plist b/GIGA/Info.plist index 16be3b6..ab33e25 100644 --- a/GIGA/Info.plist +++ b/GIGA/Info.plist @@ -2,8 +2,15 @@ + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + MaskTime CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier diff --git a/GIGA/Modules/GiGaExercises/Controller/GiGaExercisesViewController.h b/GIGA/Modules/GiGaExercises/Controller/GiGaExercisesViewController.h new file mode 100644 index 0000000..a1c25a6 --- /dev/null +++ b/GIGA/Modules/GiGaExercises/Controller/GiGaExercisesViewController.h @@ -0,0 +1,13 @@ +// +// GiGaExercisesViewController.h +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import + +@interface GiGaExercisesViewController : UIViewController + +@end diff --git a/GIGA/Modules/GiGaExercises/Controller/GiGaExercisesViewController.m b/GIGA/Modules/GiGaExercises/Controller/GiGaExercisesViewController.m new file mode 100644 index 0000000..78ab03a --- /dev/null +++ b/GIGA/Modules/GiGaExercises/Controller/GiGaExercisesViewController.m @@ -0,0 +1,37 @@ +// +// GiGaExercisesViewController.m +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaExercisesViewController.h" + +@interface GiGaExercisesViewController () + +@end + +@implementation GiGaExercisesViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + // Do any additional setup after loading the view. +} + +- (void)didReceiveMemoryWarning { + [super didReceiveMemoryWarning]; + // Dispose of any resources that can be recreated. +} + +/* +#pragma mark - Navigation + +// In a storyboard-based application, you will often want to do a little preparation before navigation +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. +} +*/ + +@end diff --git a/GIGA/Modules/LogIn/Controller/GiGaRegistViewController.h b/GIGA/Modules/LogIn/Controller/GiGaRegistViewController.h new file mode 100644 index 0000000..47d9c51 --- /dev/null +++ b/GIGA/Modules/LogIn/Controller/GiGaRegistViewController.h @@ -0,0 +1,13 @@ +// +// GiGaRegistViewController.h +// GIGA +// +// Created by lianxiang on 2018/8/21. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import + +@interface GiGaRegistViewController : UIViewController + +@end diff --git a/GIGA/Modules/LogIn/Controller/GiGaRegistViewController.m b/GIGA/Modules/LogIn/Controller/GiGaRegistViewController.m new file mode 100644 index 0000000..20ed7e0 --- /dev/null +++ b/GIGA/Modules/LogIn/Controller/GiGaRegistViewController.m @@ -0,0 +1,102 @@ +// +// GiGaRegistViewController.m +// GIGA +// +// Created by lianxiang on 2018/8/21. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaRegistViewController.h" +#import "TTTAttributedLabel.h" +#import "GiGaWebViewController.h" +@interface GiGaRegistViewController () +@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField; +@property (weak, nonatomic) IBOutlet UITextField *codeTextField; +@property (weak, nonatomic) IBOutlet UIButton *sendCodeBtn; +@property (weak, nonatomic) IBOutlet UITextField *passTexFied; +@property (weak, nonatomic) IBOutlet UIButton *checkBtn; +@property (weak, nonatomic) IBOutlet UIButton *registBtn; + +@property (weak, nonatomic) IBOutlet TTTAttributedLabel *useragreementLabel; + +@end + +@implementation GiGaRegistViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + self.title = @"注册"; + // Do any additional setup after loading the view from its nib. + [self confirmUI]; + + +} + +-(void)confirmUI{ + + self.useragreementLabel.highlightedTextColor = [UIColor lightGrayColor]; + self.useragreementLabel.delegate = self; + self.useragreementLabel.enabledTextCheckingTypes= NSTextCheckingTypePhoneNumber|NSTextCheckingTypeAddress|NSTextCheckingTypeLink; + self.useragreementLabel.linkAttributes = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCTUnderlineStyleAttributeName]; + + //链接正常状态文本属性NSTextCheckingTypeLink; + NSString *text = @"已阅读并同意《用户服务协议》"; + [self.useragreementLabel setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) { + + NSRange fontRange = [[mutableAttributedString string] rangeOfString:@"用户服务协议" options:NSCaseInsensitiveSearch]; + UIFont* sysFont = [UIFont systemFontOfSize:15]; + CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)sysFont.fontName, sysFont.pointSize, NULL); + + if (font) { + + [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font range:fontRange]; + + [mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(__bridge id)[[UIColor greenColor] CGColor] range:fontRange]; + } + + return mutableAttributedString; + + }]; + NSRange fontRange = [text rangeOfString:@"用户服务协议" options:NSCaseInsensitiveSearch]; + + [self.useragreementLabel addLinkToTransitInformation:@{ + @"SourceName":@"useragreement" + } withRange:fontRange]; + +} + +#pragma mark - TTTAttributedLabelDelegate +-(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url +{ + +} + +-(void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithTransitInformation:(NSDictionary *)components +{ + NSLog(@"components%@",components); +// GiGaWebViewController *webView = [[GiGaWebViewController alloc] init]; +// webView.souceType = WebSourceTypeLoacalHtml; +// webView.fileName = components[@"SourceName"]; +// [self.navigationController pushViewController:webView animated:YES]; + GiGaWebViewController *webView = [[GiGaWebViewController alloc] init]; + webView.souceType = WebSourceTypeUrlLink; + webView.url = @"http://www.youtansu.com"; + [self.navigationController pushViewController:webView animated:YES]; +} + +- (void)didReceiveMemoryWarning { + [super didReceiveMemoryWarning]; + // Dispose of any resources that can be recreated. +} + +/* +#pragma mark - Navigation + +// In a storyboard-based application, you will often want to do a little preparation before navigation +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. +} +*/ + +@end diff --git a/GIGA/Modules/LogIn/Controller/GiGaRegistViewController.xib b/GIGA/Modules/LogIn/Controller/GiGaRegistViewController.xib new file mode 100644 index 0000000..bbacb44 --- /dev/null +++ b/GIGA/Modules/LogIn/Controller/GiGaRegistViewController.xib @@ -0,0 +1,157 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/GIGA/Modules/LogIn/Controller/GiGaUserLoginVC.h b/GIGA/Modules/LogIn/Controller/GiGaUserLoginVC.h new file mode 100644 index 0000000..239beb3 --- /dev/null +++ b/GIGA/Modules/LogIn/Controller/GiGaUserLoginVC.h @@ -0,0 +1,13 @@ +// +// GiGaUserLoginVC.h +// GIGA +// +// Created by lianxiang on 2018/8/20. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaBaseNavViewController.h" + +@interface GiGaUserLoginVC : UIViewController + +@end diff --git a/GIGA/Modules/LogIn/Controller/GiGaUserLoginVC.m b/GIGA/Modules/LogIn/Controller/GiGaUserLoginVC.m new file mode 100644 index 0000000..a69b579 --- /dev/null +++ b/GIGA/Modules/LogIn/Controller/GiGaUserLoginVC.m @@ -0,0 +1,110 @@ +// +// GiGaUserLoginVC.m +// GIGA +// +// Created by lianxiang on 2018/8/20. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaUserLoginVC.h" +#import "UINavigationBar+Custom.h" +#import "PassWordResetVC.h" +#import "GiGaRegistViewController.h" + +@interface GiGaUserLoginVC () +@property (weak, nonatomic) IBOutlet UIImageView *userImagView; +@property (weak, nonatomic) IBOutlet UITextField *acountTextField; +@property (weak, nonatomic) IBOutlet UITextField *passwordTextField; +@property (weak, nonatomic) IBOutlet UIButton *loginBtn; + +@property (weak, nonatomic) IBOutlet UIButton *weiXinLoginBtn; +@property (weak, nonatomic) IBOutlet UIButton *registBtn; + + +@end + +@implementation GiGaUserLoginVC + +- (void)viewDidLoad { + [super viewDidLoad]; + + // Do any additional setup after loading the view from its nib. + [self setUpX]; + [self textFieldUI]; + [self.registBtn addTarget:self action:@selector(registBtnAction) forControlEvents:UIControlEventTouchUpInside]; + + +} + +-(void)setUpX{ + + UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom]; + rightBtn.frame = CGRectMake(0, 0, 40, 40); + rightBtn.backgroundColor = [UIColor blueColor]; + [rightBtn setImage:[UIImage imageNamed:@"maske_dismiss_waring"] forState:UIControlStateNormal]; + [rightBtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchUpInside]; + self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn]; +} + +-(void)textFieldUI{ + + [self.acountTextField setValue:[UIColor colorWithRed:153/255.0f green:153/255.0f blue:153/255.0f alpha:1] forKey:@"_placeholderLabel.textColor"]; + UIView *acountView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)]; + acountView.backgroundColor = [UIColor redColor]; + UIImageView *acountViewIcon = [[UIImageView alloc] initWithFrame:CGRectMake(15, 5, 16, 18)]; + acountViewIcon.image = [UIImage imageNamed:@""]; + [acountView addSubview:acountViewIcon]; + self.acountTextField.leftView = acountView; + self.acountTextField.leftViewMode = UITextFieldViewModeAlways; + + [self.passwordTextField setValue:[UIColor colorWithRed:153/255.0f green:153/255.0f blue:153/255.0f alpha:1] forKey:@"_placeholderLabel.textColor"]; + UIView *passView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)]; + passView.backgroundColor = [UIColor redColor]; + UIImageView *passViewIcon = [[UIImageView alloc] initWithFrame:CGRectMake(15, 5, 16, 18)]; + passViewIcon.image = [UIImage imageNamed:@""]; + [passView addSubview:passViewIcon]; + self.passwordTextField.leftView = passView; + self.passwordTextField.leftViewMode = UITextFieldViewModeAlways; + + self.loginBtn.layer.masksToBounds = YES; + self.loginBtn.layer.cornerRadius = self.loginBtn.frame.size.height / 2; + + self.weiXinLoginBtn.layer.masksToBounds = YES; + self.weiXinLoginBtn.layer.cornerRadius = self.weiXinLoginBtn.frame.size.height / 2; + +} +-(void)rightBtnAction{ + + [self dismissViewControllerAnimated:YES completion:nil]; + +} + +-(void)viewWillAppear:(BOOL)animated{ + + [super viewWillAppear:animated]; + [self.navigationController.navigationBar setClearNav]; +} +- (void)didReceiveMemoryWarning { + + [super didReceiveMemoryWarning]; + // Dispose of any resources that can be recreated. +} + +- (IBAction)forgetPassBtn:(id)sender { + + PassWordResetVC *passVC= [[PassWordResetVC alloc] init]; + [self.navigationController pushViewController:passVC animated:YES]; + + +} + +-(void)registBtnAction{ + + GiGaRegistViewController *registVC = [[GiGaRegistViewController alloc] init]; + [self.navigationController pushViewController:registVC animated:YES]; + + +} + + +@end diff --git a/GIGA/Modules/LogIn/Controller/GiGaUserLoginVC.xib b/GIGA/Modules/LogIn/Controller/GiGaUserLoginVC.xib new file mode 100644 index 0000000..6aab7b9 --- /dev/null +++ b/GIGA/Modules/LogIn/Controller/GiGaUserLoginVC.xib @@ -0,0 +1,175 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/GIGA/Modules/LogIn/Controller/GiGaWebViewController.h b/GIGA/Modules/LogIn/Controller/GiGaWebViewController.h new file mode 100644 index 0000000..fbaacff --- /dev/null +++ b/GIGA/Modules/LogIn/Controller/GiGaWebViewController.h @@ -0,0 +1,24 @@ +// +// GiGaWebViewController.h +// GIGA +// +// Created by lianxiang on 2018/8/21. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import + +typedef NS_ENUM(NSInteger,WebSourceType) +{ + WebSourceTypeLoacalHtml, + WebSourceTypeUrlLink + +}; + +@interface GiGaWebViewController : UIViewController + +@property (nonatomic,strong) NSString *url; +@property (nonatomic,assign) WebSourceType souceType; +@property (nonatomic,strong) NSString *fileName; + +@end diff --git a/GIGA/Modules/LogIn/Controller/GiGaWebViewController.m b/GIGA/Modules/LogIn/Controller/GiGaWebViewController.m new file mode 100644 index 0000000..9dd0332 --- /dev/null +++ b/GIGA/Modules/LogIn/Controller/GiGaWebViewController.m @@ -0,0 +1,122 @@ +// +// GiGaWebViewController.m +// GIGA +// +// Created by lianxiang on 2018/8/21. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaWebViewController.h" +#import "NJKWebViewProgressView.h" +#import "NJKWebViewProgress.h" +#import "UIView+Toast.h" +@interface GiGaWebViewController () +{ + NJKWebViewProgressView *_progressView; + NJKWebViewProgress *_progressProxy; + +} +@property (weak, nonatomic) IBOutlet UIWebView *webview; + +@end + +@implementation GiGaWebViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + // Do any additional setup after loading the view from its nib. + _progressProxy = [[NJKWebViewProgress alloc] init]; + _webview.delegate = _progressProxy; + _progressProxy.webViewProxyDelegate = self; + _progressProxy.progressDelegate = self; + + CGRect navBounds = self.navigationController.navigationBar.bounds; + CGRect barFrame = CGRectMake(0, + navBounds.size.height - 2, + navBounds.size.width,2); + + _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame]; + _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin; + [_progressView setProgress:0 animated:YES]; + + [self loadWeb]; + + +} +-(void)viewWillAppear:(BOOL)animated{ + [self.navigationController.navigationBar addSubview:_progressView]; +} +-(void)viewWillDisappear:(BOOL)animated{ + [_progressView removeFromSuperview]; +} +-(void)loadWeb{ + + switch (self.souceType) { + case WebSourceTypeUrlLink: + { + if (!self.url) { + [self.view makeToast:@"链接为空" duration:1 position:CSToastPositionCenter]; + return; + } + NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.url]]; + [_webview loadRequest:req]; + } + break; + + case WebSourceTypeLoacalHtml: + { + if (!self.fileName) { + [self.view makeToast:@"无此文件" duration:1 position:CSToastPositionCenter]; + return; + } + NSString *filepath = [[NSBundle mainBundle] pathForResource: self.fileName ofType:@"html"]; + NSString *html = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:nil]; + [_webview loadHTMLString:html baseURL:[NSURL URLWithString:filepath]]; + } + break; + + default: + break; + } + +} + + +#pragma mark -NJKWebViewProgressDelegate +-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress{ + [_progressView setProgress:progress animated:YES]; + self.title = [_webview stringByEvaluatingJavaScriptFromString:@"document.title"]; + NSLog(@"%@",self.title); + +} + +- (void)webViewDidStartLoad:(UIWebView *)webView{ + NSLog(@"startLoad"); + [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; +} + +-(void)webViewDidFinishLoad:(UIWebView *)webView{ + + NSLog(@"finishLoad"); + [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO]; +} + +-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{ + NSLog(@"error:%@",error); + [_progressView setProgress:0 animated:NO]; +} + +- (void)didReceiveMemoryWarning { + [super didReceiveMemoryWarning]; + // Dispose of any resources that can be recreated. +} + +- (void)removeCookies { + NSHTTPCookieStorage *cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage]; + NSArray *pcookies = [cookies cookiesForURL:[NSURL URLWithString:self.url]]; + for (NSHTTPCookie *cookie in pcookies) { + [cookies deleteCookie:cookie]; + } +} + +@end diff --git a/GIGA/Modules/LogIn/Controller/GiGaWebViewController.xib b/GIGA/Modules/LogIn/Controller/GiGaWebViewController.xib new file mode 100644 index 0000000..ad8b678 --- /dev/null +++ b/GIGA/Modules/LogIn/Controller/GiGaWebViewController.xib @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/GIGA/Modules/LogIn/Controller/PassWordResetVC.h b/GIGA/Modules/LogIn/Controller/PassWordResetVC.h new file mode 100644 index 0000000..ad0579d --- /dev/null +++ b/GIGA/Modules/LogIn/Controller/PassWordResetVC.h @@ -0,0 +1,13 @@ +// +// PassWordResetVC.h +// GIGA +// +// Created by lianxiang on 2018/8/21. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import + +@interface PassWordResetVC : UIViewController + +@end diff --git a/GIGA/Modules/LogIn/Controller/PassWordResetVC.m b/GIGA/Modules/LogIn/Controller/PassWordResetVC.m new file mode 100644 index 0000000..28b5381 --- /dev/null +++ b/GIGA/Modules/LogIn/Controller/PassWordResetVC.m @@ -0,0 +1,79 @@ +// +// PassWordResetVC.m +// GIGA +// +// Created by lianxiang on 2018/8/21. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "PassWordResetVC.h" + +@interface PassWordResetVC () +@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField; +@property (weak, nonatomic) IBOutlet UITextField *codeTextField; +@property (weak, nonatomic) IBOutlet UIButton *codeSendBtn; + +@property (weak, nonatomic) IBOutlet UITextField *passNewTextField; +@property (weak, nonatomic) IBOutlet UIButton *confirmBtn; + +@end + +@implementation PassWordResetVC + +- (void)viewDidLoad { + [super viewDidLoad]; + self.title = @"重置密码"; + // Do any additional setup after loading the view from its nib. + [self confirmUI]; +} + +-(void)confirmUI{ + + [self.phoneNumberTextField setValue:[UIColor colorWithRed:153/255.0f green:153/255.0f blue:153/255.0f alpha:1] forKey:@"_placeholderLabel.textColor"]; + UIView *phoneView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)]; + phoneView.backgroundColor = [UIColor redColor]; + UIImageView *phoneIcon = [[UIImageView alloc] initWithFrame:CGRectMake(15, 5, 16, 18)]; + phoneIcon.image = [UIImage imageNamed:@""]; + [phoneView addSubview:phoneIcon]; + self.phoneNumberTextField.leftView = phoneView; + self.phoneNumberTextField.leftViewMode = UITextFieldViewModeAlways; + + [self.codeTextField setValue:[UIColor colorWithRed:153/255.0f green:153/255.0f blue:153/255.0f alpha:1] forKey:@"_placeholderLabel.textColor"]; + UIView *codeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)]; + codeView.backgroundColor = [UIColor redColor]; + UIImageView *codeIcon = [[UIImageView alloc] initWithFrame:CGRectMake(15, 5, 16, 18)]; + codeIcon.image = [UIImage imageNamed:@""]; + [codeView addSubview:codeIcon]; + self.codeTextField.leftView = codeView; + self.codeTextField.leftViewMode = UITextFieldViewModeAlways; + + [self.passNewTextField setValue:[UIColor colorWithRed:153/255.0f green:153/255.0f blue:153/255.0f alpha:1] forKey:@"_placeholderLabel.textColor"]; + UIView *passView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)]; + passView.backgroundColor = [UIColor redColor]; + UIImageView *passIcon = [[UIImageView alloc] initWithFrame:CGRectMake(15, 5, 16, 18)]; + passIcon.image = [UIImage imageNamed:@""]; + [passView addSubview:passIcon]; + self.passNewTextField.leftView = passView; + self.passNewTextField.leftViewMode = UITextFieldViewModeAlways; + + self.confirmBtn.layer.masksToBounds = YES; + self.confirmBtn.layer.cornerRadius = self.confirmBtn.frame.size.height / 2; + +} + +- (void)didReceiveMemoryWarning { + [super didReceiveMemoryWarning]; + // Dispose of any resources that can be recreated. +} + +/* +#pragma mark - Navigation + +// In a storyboard-based application, you will often want to do a little preparation before navigation +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. +} +*/ + +@end diff --git a/GIGA/Modules/LogIn/Controller/PassWordResetVC.xib b/GIGA/Modules/LogIn/Controller/PassWordResetVC.xib new file mode 100644 index 0000000..f2267e1 --- /dev/null +++ b/GIGA/Modules/LogIn/Controller/PassWordResetVC.xib @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/GIGA/Modules/Mask/Controller/GiGaAppGaurdVC.h b/GIGA/Modules/Mask/Controller/GiGaAppGaurdVC.h new file mode 100644 index 0000000..ad480b7 --- /dev/null +++ b/GIGA/Modules/Mask/Controller/GiGaAppGaurdVC.h @@ -0,0 +1,13 @@ +// +// GiGaAppGaurdVC.h +// GIGA +// +// Created by lianxiang on 2018/8/21. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import + +@interface GiGaAppGaurdVC : UIViewController + +@end diff --git a/GIGA/Modules/Mask/Controller/GiGaAppGaurdVC.m b/GIGA/Modules/Mask/Controller/GiGaAppGaurdVC.m new file mode 100644 index 0000000..9a0c049 --- /dev/null +++ b/GIGA/Modules/Mask/Controller/GiGaAppGaurdVC.m @@ -0,0 +1,71 @@ +// +// GiGaAppGaurdVC.m +// GIGA +// +// Created by lianxiang on 2018/8/21. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaAppGaurdVC.h" +#import "Masonry.h" +#import "GiGaUserDefault.h" + +@interface GiGaAppGaurdVC () + +@end + +@implementation GiGaAppGaurdVC + +- (void)viewDidLoad { + [super viewDidLoad]; + // Do any additional setup after loading the view. + self.view.backgroundColor = [UIColor lightGrayColor]; + [GiGaUserDefault saveAppGaurdflag:YES]; + [self creatUI]; +} + +-(void)creatUI{ + + UIButton *dismisBtn= [UIButton buttonWithType:UIButtonTypeCustom]; + [dismisBtn setTitle:@"立即体验" forState:UIControlStateNormal]; + dismisBtn.backgroundColor = [UIColor greenColor]; + + [dismisBtn addTarget:self action:@selector(dismisBtnAction) forControlEvents:UIControlEventTouchUpInside]; + [self.view addSubview:dismisBtn]; + + [dismisBtn mas_makeConstraints:^(MASConstraintMaker *make) { + make.width.mas_equalTo(200); + make.height.mas_equalTo(30); + make.centerX.mas_equalTo(self.view.mas_centerX); + make.top.mas_equalTo(self.view.mas_top).offset(200); + }]; + + dismisBtn.layer.masksToBounds = YES; + dismisBtn.layer.cornerRadius = 15; + +} + +-(void)dismisBtnAction{ + + + [self dismissViewControllerAnimated:YES completion:^{ + NC_POST_NAME_OBJECT(APP_GUARD_DISSMISS, nil); + }]; +} + +- (void)didReceiveMemoryWarning { + [super didReceiveMemoryWarning]; + // Dispose of any resources that can be recreated. +} + +/* +#pragma mark - Navigation + +// In a storyboard-based application, you will often want to do a little preparation before navigation +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. +} +*/ + +@end diff --git a/GIGA/Modules/Mask/Controller/GiGaMaskTaskViewController.h b/GIGA/Modules/Mask/Controller/GiGaMaskTaskViewController.h new file mode 100644 index 0000000..922ad5b --- /dev/null +++ b/GIGA/Modules/Mask/Controller/GiGaMaskTaskViewController.h @@ -0,0 +1,13 @@ +// +// GiGaMaskTaskViewController.h +// GIGA +// +// Created by lianxiang on 2018/8/14. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import + +@interface GiGaMaskTaskViewController : UIViewController + +@end diff --git a/GIGA/Modules/Mask/Controller/GiGaMaskTaskViewController.m b/GIGA/Modules/Mask/Controller/GiGaMaskTaskViewController.m new file mode 100644 index 0000000..f551f04 --- /dev/null +++ b/GIGA/Modules/Mask/Controller/GiGaMaskTaskViewController.m @@ -0,0 +1,170 @@ +// +// GiGaMaskTaskViewController.m +// GIGA +// +// Created by lianxiang on 2018/8/14. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaMaskTaskViewController.h" +#import "MaskViewBootomWaringView.h" +#import "GiGaUserLoginVC.h" +#import "UserGuardViewController.h" +#import "GiGaUserDefault.h" +#import "GiGaAppGaurdVC.h" + +@interface GiGaMaskTaskViewController () +@property(nonatomic,strong)MaskViewBootomWaringView *waringView; +@end + +@implementation GiGaMaskTaskViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + // Do any additional setup after loading the view. + [self setUpNav]; + [self addNotify]; + + BOOL canshowGaurd = [GiGaUserDefault isShowedGaurd]; + if (!canshowGaurd) { + NSLog(@"%d",(int)canshowGaurd ); + } + // NSLog(@"%d",(int)canshowGaurd ); +} + +-(void)viewDidAppear:(BOOL)animated{ + [super viewDidAppear:animated]; + + BOOL showAppGaurd = [GiGaUserDefault isShowedAppGaurd]; + + if (!showAppGaurd) { + [self showAPPappGaurdView]; + } +} + +-(void)addNotify{ + + NC_ADD_TARGET_NAME_OBJECT(self, @selector(guardViewDissmiss), USER_GUARD_DISSMISS, nil) ; + NC_ADD_TARGET_NAME_OBJECT(self, @selector(appGauardViewDissmiss),APP_GUARD_DISSMISS, nil) ; +} + +#pragma mark 新手引导消失 +-(void)guardViewDissmiss{ + [self showWaringView]; +} +#pragma mark app引导页消失 +-(void)appGauardViewDissmiss{ + //出现新手引导 + BOOL isshowGaurd = [GiGaUserDefault isShowedGaurd]; + if (!isshowGaurd) { + NSLog(@"%d",(int)isshowGaurd ); + [self showUserGaurdView]; + } +} +-(void)dealloc{ + + NC_REMOVE_NAME(self, USER_GUARD_DISSMISS, nil); + NC_REMOVE_NAME(self, APP_GUARD_DISSMISS, nil); +} + +#pragma mark 新手引导 +-(void)showUserGaurdView{ + + UserGuardViewController *userGuardVC = [[UserGuardViewController alloc] init]; + if (ISIOS8) { + userGuardVC.modalPresentationStyle = UIModalPresentationOverCurrentContext; + }else{ + userGuardVC.modalPresentationStyle = UIModalPresentationCurrentContext; + } + userGuardVC.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5]; + [self presentViewController:userGuardVC animated:NO completion:nil]; +} +#pragma mark App引导页 +-(void)showAPPappGaurdView{ + GiGaAppGaurdVC *gaurdVC = [[GiGaAppGaurdVC alloc] init]; + [self presentViewController:gaurdVC animated:YES completion:nil]; +} +#pragma mark - setUpNav +-(void)setUpNav{ + + //leftItem + UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom]; + leftBtn.frame = CGRectMake(0, 0, 40, 40); + leftBtn.backgroundColor = [UIColor redColor]; + [leftBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal]; + [leftBtn addTarget:self action:@selector(leftBtnAction) forControlEvents:UIControlEventTouchUpInside]; + self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn]; + //rightItem + UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom]; + rightBtn.frame = CGRectMake(0, 0, 40, 40); + rightBtn.backgroundColor = [UIColor blueColor]; + [rightBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal]; + [rightBtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchUpInside]; + self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn]; + +} +#pragma mark 消息 action + +-(void)leftBtnAction{ + + GiGaUserLoginVC *userlogInVC= [[GiGaUserLoginVC alloc] init]; + GiGaBaseNavViewController *baseNav = [[GiGaBaseNavViewController alloc] initWithRootViewController:userlogInVC]; + [self presentViewController:baseNav animated:YES completion:nil]; + +} + +#pragma mark 个人中心 action + +-(void)rightBtnAction{ + +} + +#pragma mark -bottomView +-(void)showWaringView{ + + [UIView animateWithDuration:0.4 animations:^{ + self.waringView.frame = CGRectMake(0,self.view.frame.size.height - 60, self.view.frame.size.width, 60); + }]; + + [self.view addSubview:self.waringView]; + weakify(self); + [self.waringView.dismissBtn initWithBlock:^(UIButton *btn) { + NSLog(@"GIGAdismissBtn"); + [UIView animateWithDuration:0.4 animations:^{ + weakSelf.waringView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.height, 60); + } completion:^(BOOL finished) { + [weakSelf.waringView removeFromSuperview]; + }]; + + } for:UIControlEventTouchUpInside ]; +} + +-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event +{ + [self showWaringView]; +} + +- (MaskViewBootomWaringView *)waringView{ + + if (!_waringView) { + self.waringView = [[MaskViewBootomWaringView alloc] initWithFrame: CGRectMake(0, self.view.frame.size.height, self.view.frame.size.height, 60)]; + } + return _waringView; +} + +- (void)didReceiveMemoryWarning { + [super didReceiveMemoryWarning]; + // Dispose of any resources that can be recreated. +} + +/* +#pragma mark - Navigation + +// In a storyboard-based application, you will often want to do a little preparation before navigation +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. +} +*/ + +@end diff --git a/GIGA/Modules/Mask/Controller/UserGuardViewController.h b/GIGA/Modules/Mask/Controller/UserGuardViewController.h new file mode 100644 index 0000000..5f7febc --- /dev/null +++ b/GIGA/Modules/Mask/Controller/UserGuardViewController.h @@ -0,0 +1,14 @@ +// +// UserGuardViewController.h +// GIGA +// +// Created by lianxiang on 2018/8/21. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import + +@interface UserGuardViewController : UIViewController + + +@end diff --git a/GIGA/Modules/Mask/Controller/UserGuardViewController.m b/GIGA/Modules/Mask/Controller/UserGuardViewController.m new file mode 100644 index 0000000..788cc92 --- /dev/null +++ b/GIGA/Modules/Mask/Controller/UserGuardViewController.m @@ -0,0 +1,70 @@ +// +// UserGuardViewController.m +// GIGA +// +// Created by lianxiang on 2018/8/21. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "UserGuardViewController.h" +#import "Masonry.h" +#import "GiGaUserDefault.h" + +@interface UserGuardViewController () + +@end + +@implementation UserGuardViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + // Do any additional setup after loading the view. + //self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1]; + + [self creatUI]; + +} + + +-(void)creatUI{ + + UIButton *dismisBtn= [UIButton buttonWithType:UIButtonTypeCustom]; + + [dismisBtn setTitle:@"知道了" forState:UIControlStateNormal]; + [dismisBtn setTintColor:[UIColor whiteColor]]; + dismisBtn.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1]; + [dismisBtn addTarget:self action:@selector(dismisBtnAction) forControlEvents:UIControlEventTouchUpInside]; + [self.view addSubview:dismisBtn]; + + [dismisBtn mas_makeConstraints:^(MASConstraintMaker *make) { + make.width.mas_equalTo(100); + make.height.mas_equalTo(60); + make.centerX.mas_equalTo(self.view.mas_centerX); + make.top.mas_equalTo(self.view.mas_top).offset(200); + }]; + +} + +-(void)dismisBtnAction{ + + [GiGaUserDefault saveUsergaurdflag:YES]; + [self dismissViewControllerAnimated:NO completion:^{ + NC_POST_NAME_OBJECT(USER_GUARD_DISSMISS, nil); + }]; +} +- (void)didReceiveMemoryWarning { + [super didReceiveMemoryWarning]; + // Dispose of any resources that can be recreated. +} + +/* +#pragma mark - Navigation + +// In a storyboard-based application, you will often want to do a little preparation before navigation +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. +} +*/ + +@end diff --git a/GIGA/Modules/Mask/View/MaskViewBootomWaringView.h b/GIGA/Modules/Mask/View/MaskViewBootomWaringView.h new file mode 100644 index 0000000..e9666f5 --- /dev/null +++ b/GIGA/Modules/Mask/View/MaskViewBootomWaringView.h @@ -0,0 +1,15 @@ +// +// MaskViewBootomWaringView.h +// GIGA +// +// Created by lianxiang on 2018/8/20. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import +#import "GiGaBlockButton.h" +@interface MaskViewBootomWaringView : UIView +@property(nonatomic,strong) GiGaBlockButton *dismissBtn; + + +@end diff --git a/GIGA/Modules/Mask/View/MaskViewBootomWaringView.m b/GIGA/Modules/Mask/View/MaskViewBootomWaringView.m new file mode 100644 index 0000000..04aa178 --- /dev/null +++ b/GIGA/Modules/Mask/View/MaskViewBootomWaringView.m @@ -0,0 +1,65 @@ +// +// MaskViewBootomWaringView.m +// GIGA +// +// Created by lianxiang on 2018/8/20. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "MaskViewBootomWaringView.h" +#import "Masonry.h" + +@implementation MaskViewBootomWaringView + +-(instancetype)initWithFrame:(CGRect)frame{ + + self = [super initWithFrame:frame]; + if (self) { + self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8]; + + [self setUpUI]; + } + return self; +} + +-(void)setUpUI{ + + UIImageView *iconImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]]; + iconImg.backgroundColor = [UIColor redColor]; + [self addSubview:iconImg]; + [iconImg mas_makeConstraints:^(MASConstraintMaker *make) { + make.width.and.height.mas_equalTo(40); + make.left.mas_equalTo(10); + make.centerY.mas_equalTo(self.mas_centerY); + + }]; + + UILabel *waringLabel = [[UILabel alloc] init]; + waringLabel.text = @"亲爱滴,请您务必要开启手机声音哦"; + waringLabel.textColor = [UIColor whiteColor]; + waringLabel.textAlignment = NSTextAlignmentCenter; + waringLabel.font = [UIFont systemFontOfSize:16]; + [waringLabel sizeToFit]; + [self addSubview:waringLabel]; + [waringLabel mas_makeConstraints:^(MASConstraintMaker *make) { + + make.left.mas_equalTo(iconImg.mas_right).offset(10); + make.centerY.mas_equalTo(self.mas_centerY); + }]; + + GiGaBlockButton *dismisBtn = [GiGaBlockButton buttonWithType:UIButtonTypeCustom]; + [dismisBtn setImage:[UIImage imageNamed:@"maske_dismiss_waring"] forState:UIControlStateNormal]; + [dismisBtn setContentMode:UIViewContentModeScaleAspectFill]; + self.dismissBtn = dismisBtn; + [self addSubview:dismisBtn]; + + [dismisBtn mas_makeConstraints:^(MASConstraintMaker *make) { + make.right.mas_equalTo(self.mas_right).offset(10); + make.centerY.mas_equalTo(self.mas_centerY); + make.width.and.height.mas_equalTo(40); + + }]; +} + + +@end diff --git a/GIGA/Modules/Me/Controller/GiGaUserViewController.h b/GIGA/Modules/Me/Controller/GiGaUserViewController.h new file mode 100644 index 0000000..d96c41e --- /dev/null +++ b/GIGA/Modules/Me/Controller/GiGaUserViewController.h @@ -0,0 +1,13 @@ +// +// GiGaUserViewController.h +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import + +@interface GiGaUserViewController : UIViewController + +@end diff --git a/GIGA/Modules/Me/Controller/GiGaUserViewController.m b/GIGA/Modules/Me/Controller/GiGaUserViewController.m new file mode 100644 index 0000000..c25b6c0 --- /dev/null +++ b/GIGA/Modules/Me/Controller/GiGaUserViewController.m @@ -0,0 +1,37 @@ +// +// GiGaUserViewController.m +// GIGA +// +// Created by lianxiang on 2018/8/13. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaUserViewController.h" + +@interface GiGaUserViewController () + +@end + +@implementation GiGaUserViewController + +- (void)viewDidLoad { + [super viewDidLoad]; + // Do any additional setup after loading the view. +} + +- (void)didReceiveMemoryWarning { + [super didReceiveMemoryWarning]; + // Dispose of any resources that can be recreated. +} + +/* +#pragma mark - Navigation + +// In a storyboard-based application, you will often want to do a little preparation before navigation +- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { + // Get the new view controller using [segue destinationViewController]. + // Pass the selected object to the new view controller. +} +*/ + +@end diff --git a/GIGA/Modules/Me/Model/GiGaUser.h b/GIGA/Modules/Me/Model/GiGaUser.h new file mode 100644 index 0000000..89e7721 --- /dev/null +++ b/GIGA/Modules/Me/Model/GiGaUser.h @@ -0,0 +1,18 @@ +// +// GiGaUser.h +// GIGA +// +// Created by lianxiang on 2018/8/15. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "JSONModel.h" + +@interface GiGaUser : JSONModel + +@property(nonatomic,copy) NSString *userId; +@property(nonatomic,copy) NSString *name; +@property(nonatomic,copy) NSString *avatar; +@property(nonatomic,copy) NSString *tel; + +@end diff --git a/GIGA/Modules/Me/Model/GiGaUser.m b/GIGA/Modules/Me/Model/GiGaUser.m new file mode 100644 index 0000000..ecaf377 --- /dev/null +++ b/GIGA/Modules/Me/Model/GiGaUser.m @@ -0,0 +1,13 @@ +// +// GiGaUser.m +// GIGA +// +// Created by lianxiang on 2018/8/15. +// Copyright © 2018年 com.giga.ios. All rights reserved. +// + +#import "GiGaUser.h" + +@implementation GiGaUser + +@end diff --git a/GIGA/ViewController.m b/GIGA/ViewController.m index 650aa9d..8b40b70 100644 --- a/GIGA/ViewController.m +++ b/GIGA/ViewController.m @@ -7,7 +7,7 @@ // #import "ViewController.h" - +#import "AppDelegate.h" @interface ViewController () @end @@ -16,6 +16,9 @@ - (void)viewDidLoad { [super viewDidLoad]; + + + // Do any additional setup after loading the view, typically from a nib. } diff --git a/Podfile b/Podfile new file mode 100644 index 0000000..eff78e0 --- /dev/null +++ b/Podfile @@ -0,0 +1,25 @@ +source 'https://github.com/CocoaPods/Specs.git' +platform:ios,'8.0' +use_frameworks! + +target 'GIGA' do + + pod 'MBProgressHUD', '~> 0.9.2' + pod 'Masonry', '~> 1.0.0' + pod 'SDWebImage', '~> 4.0' + pod 'MJRefresh' + pod 'AFNetworking', '~> 3.0' + pod 'Toast', '~> 4.0.0' + pod 'JSONModel' + pod 'JPush' + pod 'WechatOpenSDK' + pod 'SocketRocket' + pod 'UITableView+FDTemplateLayoutCell' + pod 'FMDB' + pod 'LKDBHelper' + pod 'YTKKeyValueStore' + pod 'IQKeyboardManager' + pod 'TTTAttributedLabel' + pod 'NJKWebViewProgress' + +end diff --git a/Podfile.lock b/Podfile.lock new file mode 100644 index 0000000..a6e8c16 --- /dev/null +++ b/Podfile.lock @@ -0,0 +1,110 @@ +PODS: + - AFNetworking (3.2.1): + - AFNetworking/NSURLSession (= 3.2.1) + - AFNetworking/Reachability (= 3.2.1) + - AFNetworking/Security (= 3.2.1) + - AFNetworking/Serialization (= 3.2.1) + - AFNetworking/UIKit (= 3.2.1) + - AFNetworking/NSURLSession (3.2.1): + - AFNetworking/Reachability + - AFNetworking/Security + - AFNetworking/Serialization + - AFNetworking/Reachability (3.2.1) + - AFNetworking/Security (3.2.1) + - AFNetworking/Serialization (3.2.1) + - AFNetworking/UIKit (3.2.1): + - AFNetworking/NSURLSession + - FMDB (2.7.2): + - FMDB/standard (= 2.7.2) + - FMDB/standard (2.7.2) + - IQKeyboardManager (6.1.1) + - JCore (1.2.1) + - JPush (3.1.0): + - JCore (~> 1.2.0) + - JSONModel (1.7.0) + - LKDBHelper (2.5.1): + - LKDBHelper/standard (= 2.5.1) + - LKDBHelper/standard (2.5.1): + - FMDB + - Masonry (1.0.2) + - MBProgressHUD (0.9.2) + - MJRefresh (3.1.15.3) + - NJKWebViewProgress (0.2.3): + - NJKWebViewProgress/Core (= 0.2.3) + - NJKWebViewProgress/ProgressView (= 0.2.3) + - NJKWebViewProgress/Core (0.2.3) + - NJKWebViewProgress/ProgressView (0.2.3) + - SDWebImage (4.4.2): + - SDWebImage/Core (= 4.4.2) + - SDWebImage/Core (4.4.2) + - SocketRocket (0.5.1) + - Toast (4.0.0) + - TTTAttributedLabel (2.0.0) + - "UITableView+FDTemplateLayoutCell (1.6)" + - WechatOpenSDK (1.8.2) + - YTKKeyValueStore (0.1.2): + - FMDB (~> 2.0) + +DEPENDENCIES: + - AFNetworking (~> 3.0) + - FMDB + - IQKeyboardManager + - JPush + - JSONModel + - LKDBHelper + - Masonry (~> 1.0.0) + - MBProgressHUD (~> 0.9.2) + - MJRefresh + - NJKWebViewProgress + - SDWebImage (~> 4.0) + - SocketRocket + - Toast (~> 4.0.0) + - TTTAttributedLabel + - "UITableView+FDTemplateLayoutCell" + - WechatOpenSDK + - YTKKeyValueStore + +SPEC REPOS: + https://github.com/CocoaPods/Specs.git: + - AFNetworking + - FMDB + - IQKeyboardManager + - JCore + - JPush + - JSONModel + - LKDBHelper + - Masonry + - MBProgressHUD + - MJRefresh + - NJKWebViewProgress + - SDWebImage + - SocketRocket + - Toast + - TTTAttributedLabel + - "UITableView+FDTemplateLayoutCell" + - WechatOpenSDK + - YTKKeyValueStore + +SPEC CHECKSUMS: + AFNetworking: b6f891fdfaed196b46c7a83cf209e09697b94057 + FMDB: 6198a90e7b6900cfc046e6bc0ef6ebb7be9236aa + IQKeyboardManager: 79c57795f5c2408d259d37b9da2ed07efcbb5225 + JCore: 467b5b56bd367c548f88ee1b5794d94ee07ab319 + JPush: 5921e25ad13e0386351079217b009f2039084eac + JSONModel: 840bc0fcffb24b8454d2c026bf26fea454b8e98d + LKDBHelper: 9a276ba51f2e16263d46a9517e16cc9b03472664 + Masonry: 7c429b56da9d4ee0bbb3ed77a5ea710d6a5df39e + MBProgressHUD: 1569cf7ace17a8bac47aabfbb8580a49690386d1 + MJRefresh: b48380ae2b927b46c4ef000de9adb8dc748e1df7 + NJKWebViewProgress: f481fd424cb5ecc27eacae11b5397db92fba9a4d + SDWebImage: 624d6e296c69b244bcede364c72ae0430ac14681 + SocketRocket: d57c7159b83c3c6655745cd15302aa24b6bae531 + Toast: 91b396c56ee72a5790816f40d3a94dd357abc196 + TTTAttributedLabel: 8cffe8e127e4e82ff3af1e5386d4cd0ad000b656 + "UITableView+FDTemplateLayoutCell": 5c949b4a5059c404b442926c0e80f81d10a2d66f + WechatOpenSDK: 676feec516a11173eafd1fe64b10d27babf28701 + YTKKeyValueStore: 4d002941540dd5108fa23009b71e0f2f937f7a0f + +PODFILE CHECKSUM: dab9f56b1ec7688e11809754299b1b531ddcca86 + +COCOAPODS: 1.5.0 diff --git a/Pods/AFNetworking/AFNetworking/AFCompatibilityMacros.h b/Pods/AFNetworking/AFNetworking/AFCompatibilityMacros.h new file mode 100644 index 0000000..a83d134 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFCompatibilityMacros.h @@ -0,0 +1,37 @@ +// AFCompatibilityMacros.h +// Copyright (c) 2011–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. + +#ifndef AFCompatibilityMacros_h +#define AFCompatibilityMacros_h + +#ifdef API_UNAVAILABLE + #define AF_API_UNAVAILABLE(x) API_UNAVAILABLE(x) +#else + #define AF_API_UNAVAILABLE(x) +#endif // API_UNAVAILABLE + +#if __has_warning("-Wunguarded-availability-new") + #define AF_CAN_USE_AT_AVAILABLE 1 +#else + #define AF_CAN_USE_AT_AVAILABLE 0 +#endif + +#endif /* AFCompatibilityMacros_h */ diff --git a/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h b/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h new file mode 100644 index 0000000..64ee5a8 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h @@ -0,0 +1,304 @@ +// AFHTTPSessionManager.h +// Copyright (c) 2011–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 +#if !TARGET_OS_WATCH +#import +#endif +#import + +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV +#import +#else +#import +#endif + +#import "AFURLSessionManager.h" + +/** + `AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths. + + ## Subclassing Notes + + Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application. + + For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect. + + ## Methods to Override + + To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:`. + + ## Serialization + + Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to ``. + + Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `` + + ## URL Construction Using Relative Paths + + For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`. + + Below are a few examples of how `baseURL` and relative paths interact: + + NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]; + [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo + [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz + [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo + [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo + [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/ + [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/ + + Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash. + + @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. + */ + +NS_ASSUME_NONNULL_BEGIN + +@interface AFHTTPSessionManager : AFURLSessionManager + +/** + The URL used to construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. + */ +@property (readonly, nonatomic, strong, nullable) NSURL *baseURL; + +/** + Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies. + + @warning `requestSerializer` must not be `nil`. + */ +@property (nonatomic, strong) AFHTTPRequestSerializer * requestSerializer; + +/** + Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`. + + @warning `responseSerializer` must not be `nil`. + */ +@property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; + +///------------------------------- +/// @name Managing Security Policy +///------------------------------- + +/** + The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. A security policy configured with `AFSSLPinningModePublicKey` or `AFSSLPinningModeCertificate` can only be applied on a session manager initialized with a secure base URL (i.e. https). Applying a security policy with pinning enabled on an insecure session manager throws an `Invalid Security Policy` exception. + */ +@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns an `AFHTTPSessionManager` object. + */ ++ (instancetype)manager; + +/** + Initializes an `AFHTTPSessionManager` object with the specified base URL. + + @param url The base URL for the HTTP client. + + @return The newly-initialized HTTP client + */ +- (instancetype)initWithBaseURL:(nullable NSURL *)url; + +/** + Initializes an `AFHTTPSessionManager` object with the specified base URL. + + This is the designated initializer. + + @param url The base URL for the HTTP client. + @param configuration The configuration used to create the managed session. + + @return The newly-initialized HTTP client + */ +- (instancetype)initWithBaseURL:(nullable NSURL *)url + sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; + +///--------------------------- +/// @name Making HTTP Requests +///--------------------------- + +/** + Creates and runs an `NSURLSessionDataTask` with a `GET` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; + + +/** + Creates and runs an `NSURLSessionDataTask` with a `GET` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(nullable id)parameters + progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `HEAD` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes a single arguments: the data task. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; + +/** + Creates and runs an `NSURLSessionDataTask` with a `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; + +/** + Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. + @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `PUT` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `PATCH` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `DELETE` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m b/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m new file mode 100644 index 0000000..cab11c2 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m @@ -0,0 +1,372 @@ +// AFHTTPSessionManager.m +// Copyright (c) 2011–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 "AFHTTPSessionManager.h" + +#import "AFURLRequestSerialization.h" +#import "AFURLResponseSerialization.h" + +#import +#import +#import + +#import +#import +#import +#import +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import +#elif TARGET_OS_WATCH +#import +#endif + +@interface AFHTTPSessionManager () +@property (readwrite, nonatomic, strong) NSURL *baseURL; +@end + +@implementation AFHTTPSessionManager +@dynamic responseSerializer; + ++ (instancetype)manager { + return [[[self class] alloc] initWithBaseURL:nil]; +} + +- (instancetype)init { + return [self initWithBaseURL:nil]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url { + return [self initWithBaseURL:url sessionConfiguration:nil]; +} + +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { + return [self initWithBaseURL:nil sessionConfiguration:configuration]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url + sessionConfiguration:(NSURLSessionConfiguration *)configuration +{ + self = [super initWithSessionConfiguration:configuration]; + if (!self) { + return nil; + } + + // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected + if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { + url = [url URLByAppendingPathComponent:@""]; + } + + self.baseURL = url; + + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + self.responseSerializer = [AFJSONResponseSerializer serializer]; + + return self; +} + +#pragma mark - + +- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { + NSParameterAssert(requestSerializer); + + _requestSerializer = requestSerializer; +} + +- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { + NSParameterAssert(responseSerializer); + + [super setResponseSerializer:responseSerializer]; +} + +@dynamic securityPolicy; + +- (void)setSecurityPolicy:(AFSecurityPolicy *)securityPolicy { + if (securityPolicy.SSLPinningMode != AFSSLPinningModeNone && ![self.baseURL.scheme isEqualToString:@"https"]) { + NSString *pinningMode = @"Unknown Pinning Mode"; + switch (securityPolicy.SSLPinningMode) { + case AFSSLPinningModeNone: pinningMode = @"AFSSLPinningModeNone"; break; + case AFSSLPinningModeCertificate: pinningMode = @"AFSSLPinningModeCertificate"; break; + case AFSSLPinningModePublicKey: pinningMode = @"AFSSLPinningModePublicKey"; break; + } + NSString *reason = [NSString stringWithFormat:@"A security policy configured with `%@` can only be applied on a manager with a secure base URL (i.e. https)", pinningMode]; + @throw [NSException exceptionWithName:@"Invalid Security Policy" reason:reason userInfo:nil]; + } + + [super setSecurityPolicy:securityPolicy]; +} + +#pragma mark - + +- (NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + + return [self GET:URLString parameters:parameters progress:nil success:success failure:failure]; +} + +- (NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(id)parameters + progress:(void (^)(NSProgress * _Nonnull))downloadProgress + success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success + failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" + URLString:URLString + parameters:parameters + uploadProgress:nil + downloadProgress:downloadProgress + success:success + failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)HEAD:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) { + if (success) { + success(task); + } + } failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + return [self POST:URLString parameters:parameters progress:nil success:success failure:failure]; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(id)parameters + progress:(void (^)(NSProgress * _Nonnull))uploadProgress + success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success + failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + constructingBodyWithBlock:(nullable void (^)(id _Nonnull))block + success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + return [self POST:URLString parameters:parameters constructingBodyWithBlock:block progress:nil success:success failure:failure]; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(id)parameters + constructingBodyWithBlock:(void (^)(id formData))block + progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSError *serializationError = nil; + NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError]; + if (serializationError) { + if (failure) { + dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ + failure(nil, serializationError); + }); + } + + return nil; + } + + __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { + if (error) { + if (failure) { + failure(task, error); + } + } else { + if (success) { + success(task, responseObject); + } + } + }]; + + [task resume]; + + return task; +} + +- (NSURLSessionDataTask *)PUT:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)PATCH:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)DELETE:(NSString *)URLString + parameters:(id)parameters + success:(void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(id)parameters + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress + success:(void (^)(NSURLSessionDataTask *, id))success + failure:(void (^)(NSURLSessionDataTask *, NSError *))failure +{ + NSError *serializationError = nil; + NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError]; + if (serializationError) { + if (failure) { + dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ + failure(nil, serializationError); + }); + } + + return nil; + } + + __block NSURLSessionDataTask *dataTask = nil; + dataTask = [self dataTaskWithRequest:request + uploadProgress:uploadProgress + downloadProgress:downloadProgress + completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { + if (error) { + if (failure) { + failure(dataTask, error); + } + } else { + if (success) { + success(dataTask, responseObject); + } + } + }]; + + return dataTask; +} + +#pragma mark - NSObject + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue]; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))]; + NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; + if (!configuration) { + NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"]; + if (configurationIdentifier) { +#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1100) + configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier]; +#else + configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier]; +#endif + } + } + + self = [self initWithBaseURL:baseURL sessionConfiguration:configuration]; + if (!self) { + return nil; + } + + self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; + self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; + AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))]; + if (decodedPolicy) { + self.securityPolicy = decodedPolicy; + } + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))]; + if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) { + [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; + } else { + [coder encodeObject:self.session.configuration.identifier forKey:@"identifier"]; + } + [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; + [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; + [coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration]; + + HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; + HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; + HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone]; + return HTTPClient; +} + +@end diff --git a/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h b/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h new file mode 100644 index 0000000..21982a0 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h @@ -0,0 +1,216 @@ +// AFNetworkReachabilityManager.h +// Copyright (c) 2011–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 + +#if !TARGET_OS_WATCH +#import + +typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { + AFNetworkReachabilityStatusUnknown = -1, + AFNetworkReachabilityStatusNotReachable = 0, + AFNetworkReachabilityStatusReachableViaWWAN = 1, + AFNetworkReachabilityStatusReachableViaWiFi = 2, +}; + +NS_ASSUME_NONNULL_BEGIN + +/** + `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. + + Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying 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. + + See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ ) + + @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined. + */ +@interface AFNetworkReachabilityManager : NSObject + +/** + The current network reachability status. + */ +@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; + +/** + Whether or not the network is currently reachable. + */ +@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable; + +/** + Whether or not the network is currently reachable via WWAN. + */ +@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN; + +/** + Whether or not the network is currently reachable via WiFi. + */ +@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Returns the shared network reachability manager. + */ ++ (instancetype)sharedManager; + +/** + Creates and returns a network reachability manager with the default socket address. + + @return An initialized network reachability manager, actively monitoring the default socket address. + */ ++ (instancetype)manager; + +/** + Creates and returns a network reachability manager for the specified domain. + + @param domain The domain used to evaluate network reachability. + + @return An initialized network reachability manager, actively monitoring the specified domain. + */ ++ (instancetype)managerForDomain:(NSString *)domain; + +/** + Creates and returns a network reachability manager for the socket address. + + @param address The socket address (`sockaddr_in6`) used to evaluate network reachability. + + @return An initialized network reachability manager, actively monitoring the specified socket address. + */ ++ (instancetype)managerForAddress:(const void *)address; + +/** + Initializes an instance of a network reachability manager from the specified reachability object. + + @param reachability The reachability object to monitor. + + @return An initialized network reachability manager, actively monitoring the specified reachability. + */ +- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER; + +/** + * Unavailable initializer + */ ++ (instancetype)new NS_UNAVAILABLE; + +/** + * Unavailable initializer + */ +- (instancetype)init NS_UNAVAILABLE; + +///-------------------------------------------------- +/// @name Starting & Stopping Reachability Monitoring +///-------------------------------------------------- + +/** + Starts monitoring for changes in network reachability status. + */ +- (void)startMonitoring; + +/** + Stops monitoring for changes in network reachability status. + */ +- (void)stopMonitoring; + +///------------------------------------------------- +/// @name Getting Localized Reachability Description +///------------------------------------------------- + +/** + Returns a localized string representation of the current network reachability status. + */ +- (NSString *)localizedNetworkReachabilityStatusString; + +///--------------------------------------------------- +/// @name Setting Network Reachability Change Callback +///--------------------------------------------------- + +/** + Sets a callback to be executed when the network availability of the `baseURL` host changes. + + @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`. + */ +- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block; + +@end + +///---------------- +/// @name Constants +///---------------- + +/** + ## Network Reachability + + The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses. + + enum { + AFNetworkReachabilityStatusUnknown, + AFNetworkReachabilityStatusNotReachable, + AFNetworkReachabilityStatusReachableViaWWAN, + AFNetworkReachabilityStatusReachableViaWiFi, + } + + `AFNetworkReachabilityStatusUnknown` + The `baseURL` host reachability is not known. + + `AFNetworkReachabilityStatusNotReachable` + The `baseURL` host cannot be reached. + + `AFNetworkReachabilityStatusReachableViaWWAN` + The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS. + + `AFNetworkReachabilityStatusReachableViaWiFi` + The `baseURL` host can be reached via a Wi-Fi connection. + + ### Keys for Notification UserInfo Dictionary + + Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification. + + `AFNetworkingReachabilityNotificationStatusItem` + A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification. + The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status. + */ + +///-------------------- +/// @name Notifications +///-------------------- + +/** + Posted when network reachability changes. + This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability. + + @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import ` to the header prefix of the project (`Prefix.pch`). + */ +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification; +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem; + +///-------------------- +/// @name Functions +///-------------------- + +/** + Returns a localized string representation of an `AFNetworkReachabilityStatus` value. + */ +FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); + +NS_ASSUME_NONNULL_END +#endif diff --git a/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m b/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m new file mode 100644 index 0000000..ce746c3 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m @@ -0,0 +1,266 @@ +// AFNetworkReachabilityManager.m +// Copyright (c) 2011–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 "AFNetworkReachabilityManager.h" +#if !TARGET_OS_WATCH + +#import +#import +#import +#import +#import + +NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change"; +NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem"; + +typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status); + +NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) { + switch (status) { + case AFNetworkReachabilityStatusNotReachable: + return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil); + case AFNetworkReachabilityStatusReachableViaWWAN: + return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil); + case AFNetworkReachabilityStatusReachableViaWiFi: + return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil); + case AFNetworkReachabilityStatusUnknown: + default: + return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil); + } +} + +static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) { + BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0); + BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0); + BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)); + BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0); + BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction)); + + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown; + if (isNetworkReachable == NO) { + status = AFNetworkReachabilityStatusNotReachable; + } +#if TARGET_OS_IPHONE + else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) { + status = AFNetworkReachabilityStatusReachableViaWWAN; + } +#endif + else { + status = AFNetworkReachabilityStatusReachableViaWiFi; + } + + return status; +} + +/** + * Queue a status change notification for the main thread. + * + * This is done to ensure that the notifications are received in the same order + * as they are sent. If notifications are sent directly, it is possible that + * a queued notification (for an earlier status condition) is processed after + * the later update, resulting in the listener being left in the wrong state. + */ +static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusBlock block) { + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); + dispatch_async(dispatch_get_main_queue(), ^{ + if (block) { + block(status); + } + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) }; + [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo]; + }); +} + +static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { + AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusBlock)info); +} + + +static const void * AFNetworkReachabilityRetainCallback(const void *info) { + return Block_copy(info); +} + +static void AFNetworkReachabilityReleaseCallback(const void *info) { + if (info) { + Block_release(info); + } +} + +@interface AFNetworkReachabilityManager () +@property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability; +@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; +@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; +@end + +@implementation AFNetworkReachabilityManager + ++ (instancetype)sharedManager { + static AFNetworkReachabilityManager *_sharedManager = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _sharedManager = [self manager]; + }); + + return _sharedManager; +} + ++ (instancetype)managerForDomain:(NSString *)domain { + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); + + AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; + + CFRelease(reachability); + + return manager; +} + ++ (instancetype)managerForAddress:(const void *)address { + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address); + AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; + + CFRelease(reachability); + + return manager; +} + ++ (instancetype)manager +{ +#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + struct sockaddr_in6 address; + bzero(&address, sizeof(address)); + address.sin6_len = sizeof(address); + address.sin6_family = AF_INET6; +#else + struct sockaddr_in address; + bzero(&address, sizeof(address)); + address.sin_len = sizeof(address); + address.sin_family = AF_INET; +#endif + return [self managerForAddress:&address]; +} + +- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { + self = [super init]; + if (!self) { + return nil; + } + + _networkReachability = CFRetain(reachability); + self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; + + return self; +} + +- (instancetype)init +{ + @throw [NSException exceptionWithName:NSGenericException + reason:@"`-init` unavailable. Use `-initWithReachability:` instead" + userInfo:nil]; + return nil; +} + +- (void)dealloc { + [self stopMonitoring]; + + if (_networkReachability != NULL) { + CFRelease(_networkReachability); + } +} + +#pragma mark - + +- (BOOL)isReachable { + return [self isReachableViaWWAN] || [self isReachableViaWiFi]; +} + +- (BOOL)isReachableViaWWAN { + return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN; +} + +- (BOOL)isReachableViaWiFi { + return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi; +} + +#pragma mark - + +- (void)startMonitoring { + [self stopMonitoring]; + + if (!self.networkReachability) { + return; + } + + __weak __typeof(self)weakSelf = self; + AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + + strongSelf.networkReachabilityStatus = status; + if (strongSelf.networkReachabilityStatusBlock) { + strongSelf.networkReachabilityStatusBlock(status); + } + + }; + + SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; + SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); + SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ + SCNetworkReachabilityFlags flags; + if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) { + AFPostReachabilityStatusChange(flags, callback); + } + }); +} + +- (void)stopMonitoring { + if (!self.networkReachability) { + return; + } + + SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); +} + +#pragma mark - + +- (NSString *)localizedNetworkReachabilityStatusString { + return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus); +} + +#pragma mark - + +- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block { + self.networkReachabilityStatusBlock = block; +} + +#pragma mark - NSKeyValueObserving + ++ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { + if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) { + return [NSSet setWithObject:@"networkReachabilityStatus"]; + } + + return [super keyPathsForValuesAffectingValueForKey:key]; +} + +@end +#endif diff --git a/Pods/AFNetworking/AFNetworking/AFNetworking.h b/Pods/AFNetworking/AFNetworking/AFNetworking.h new file mode 100644 index 0000000..e2fb2f4 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFNetworking.h @@ -0,0 +1,41 @@ +// AFNetworking.h +// +// Copyright (c) 2013 AFNetworking (http://afnetworking.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. + +#import +#import +#import + +#ifndef _AFNETWORKING_ + #define _AFNETWORKING_ + + #import "AFURLRequestSerialization.h" + #import "AFURLResponseSerialization.h" + #import "AFSecurityPolicy.h" + +#if !TARGET_OS_WATCH + #import "AFNetworkReachabilityManager.h" +#endif + + #import "AFURLSessionManager.h" + #import "AFHTTPSessionManager.h" + +#endif /* _AFNETWORKING_ */ diff --git a/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h b/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h new file mode 100644 index 0000000..c005efa --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h @@ -0,0 +1,154 @@ +// AFSecurityPolicy.h +// Copyright (c) 2011–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 +#import + +typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { + AFSSLPinningModeNone, + AFSSLPinningModePublicKey, + AFSSLPinningModeCertificate, +}; + +/** + `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. + + Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled. + */ + +NS_ASSUME_NONNULL_BEGIN + +@interface AFSecurityPolicy : NSObject + +/** + The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. + */ +@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode; + +/** + The certificates used to evaluate server trust according to the SSL pinning mode. + + By default, this property is set to any (`.cer`) certificates included in the target compiling AFNetworking. Note that if you are using AFNetworking as embedded framework, no certificates will be pinned by default. Use `certificatesInBundle` to load certificates from your target, and then create a new policy by calling `policyWithPinningMode:withPinnedCertificates`. + + Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches. + */ +@property (nonatomic, strong, nullable) NSSet *pinnedCertificates; + +/** + Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. + */ +@property (nonatomic, assign) BOOL allowInvalidCertificates; + +/** + Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`. + */ +@property (nonatomic, assign) BOOL validatesDomainName; + +///----------------------------------------- +/// @name Getting Certificates from the Bundle +///----------------------------------------- + +/** + Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`. + + @return The certificates included in the given bundle. + */ ++ (NSSet *)certificatesInBundle:(NSBundle *)bundle; + +///----------------------------------------- +/// @name Getting Specific Security Policies +///----------------------------------------- + +/** + Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys. + + @return The default security policy. + */ ++ (instancetype)defaultPolicy; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns a security policy with the specified pinning mode. + + @param pinningMode The SSL pinning mode. + + @return A new security policy. + */ ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; + +/** + Creates and returns a security policy with the specified pinning mode. + + @param pinningMode The SSL pinning mode. + @param pinnedCertificates The certificates to pin against. + + @return A new security policy. + */ ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates; + +///------------------------------ +/// @name Evaluating Server Trust +///------------------------------ + +/** + Whether or not the specified server trust should be accepted, based on the security policy. + + This method should be used when responding to an authentication challenge from a server. + + @param serverTrust The X.509 certificate trust of the server. + @param domain The domain of serverTrust. If `nil`, the domain will not be validated. + + @return Whether or not to trust the server. + */ +- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust + forDomain:(nullable NSString *)domain; + +@end + +NS_ASSUME_NONNULL_END + +///---------------- +/// @name Constants +///---------------- + +/** + ## SSL Pinning Modes + + The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes. + + enum { + AFSSLPinningModeNone, + AFSSLPinningModePublicKey, + AFSSLPinningModeCertificate, + } + + `AFSSLPinningModeNone` + Do not used pinned certificates to validate servers. + + `AFSSLPinningModePublicKey` + Validate host certificates against public keys of pinned certificates. + + `AFSSLPinningModeCertificate` + Validate host certificates against pinned certificates. +*/ diff --git a/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m b/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m new file mode 100644 index 0000000..043441a --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m @@ -0,0 +1,344 @@ +// AFSecurityPolicy.m +// Copyright (c) 2011–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 "AFSecurityPolicy.h" + +#import + +#if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV +static NSData * AFSecKeyGetData(SecKeyRef key) { + CFDataRef data = NULL; + + __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out); + + return (__bridge_transfer NSData *)data; + +_out: + if (data) { + CFRelease(data); + } + + return nil; +} +#endif + +static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV + return [(__bridge id)key1 isEqual:(__bridge id)key2]; +#else + return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)]; +#endif +} + +static id AFPublicKeyForCertificate(NSData *certificate) { + id allowedPublicKey = nil; + SecCertificateRef allowedCertificate; + SecPolicyRef policy = nil; + SecTrustRef allowedTrust = nil; + SecTrustResultType result; + + allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); + __Require_Quiet(allowedCertificate != NULL, _out); + + policy = SecPolicyCreateBasicX509(); + __Require_noErr_Quiet(SecTrustCreateWithCertificates(allowedCertificate, policy, &allowedTrust), _out); + __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out); + + allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); + +_out: + if (allowedTrust) { + CFRelease(allowedTrust); + } + + if (policy) { + CFRelease(policy); + } + + if (allowedCertificate) { + CFRelease(allowedCertificate); + } + + return allowedPublicKey; +} + +static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { + BOOL isValid = NO; + SecTrustResultType result; + __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out); + + isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed); + +_out: + return isValid; +} + +static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) { + CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); + NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; + + for (CFIndex i = 0; i < certificateCount; i++) { + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); + [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; + } + + return [NSArray arrayWithArray:trustChain]; +} + +static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { + SecPolicyRef policy = SecPolicyCreateBasicX509(); + CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); + NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; + for (CFIndex i = 0; i < certificateCount; i++) { + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); + + SecCertificateRef someCertificates[] = {certificate}; + CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); + + SecTrustRef trust; + __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); + + SecTrustResultType result; + __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out); + + [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; + + _out: + if (trust) { + CFRelease(trust); + } + + if (certificates) { + CFRelease(certificates); + } + + continue; + } + CFRelease(policy); + + return [NSArray arrayWithArray:trustChain]; +} + +#pragma mark - + +@interface AFSecurityPolicy() +@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode; +@property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys; +@end + +@implementation AFSecurityPolicy + ++ (NSSet *)certificatesInBundle:(NSBundle *)bundle { + NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; + + NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]]; + for (NSString *path in paths) { + NSData *certificateData = [NSData dataWithContentsOfFile:path]; + [certificates addObject:certificateData]; + } + + return [NSSet setWithSet:certificates]; +} + ++ (NSSet *)defaultPinnedCertificates { + static NSSet *_defaultPinnedCertificates = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSBundle *bundle = [NSBundle bundleForClass:[self class]]; + _defaultPinnedCertificates = [self certificatesInBundle:bundle]; + }); + + return _defaultPinnedCertificates; +} + ++ (instancetype)defaultPolicy { + AFSecurityPolicy *securityPolicy = [[self alloc] init]; + securityPolicy.SSLPinningMode = AFSSLPinningModeNone; + + return securityPolicy; +} + ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { + return [self policyWithPinningMode:pinningMode withPinnedCertificates:[self defaultPinnedCertificates]]; +} + ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates { + AFSecurityPolicy *securityPolicy = [[self alloc] init]; + securityPolicy.SSLPinningMode = pinningMode; + + [securityPolicy setPinnedCertificates:pinnedCertificates]; + + return securityPolicy; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.validatesDomainName = YES; + + return self; +} + +- (void)setPinnedCertificates:(NSSet *)pinnedCertificates { + _pinnedCertificates = pinnedCertificates; + + if (self.pinnedCertificates) { + NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]]; + for (NSData *certificate in self.pinnedCertificates) { + id publicKey = AFPublicKeyForCertificate(certificate); + if (!publicKey) { + continue; + } + [mutablePinnedPublicKeys addObject:publicKey]; + } + self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys]; + } else { + self.pinnedPublicKeys = nil; + } +} + +#pragma mark - + +- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust + forDomain:(NSString *)domain +{ + if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) { + // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html + // According to the docs, you should only trust your provided certs for evaluation. + // Pinned certificates are added to the trust. Without pinned certificates, + // there is nothing to evaluate against. + // + // From Apple Docs: + // "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors). + // Instead, add your own (self-signed) CA certificate to the list of trusted anchors." + NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning."); + return NO; + } + + NSMutableArray *policies = [NSMutableArray array]; + if (self.validatesDomainName) { + [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)]; + } else { + [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()]; + } + + SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies); + + if (self.SSLPinningMode == AFSSLPinningModeNone) { + return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust); + } else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) { + return NO; + } + + switch (self.SSLPinningMode) { + case AFSSLPinningModeNone: + default: + return NO; + case AFSSLPinningModeCertificate: { + NSMutableArray *pinnedCertificates = [NSMutableArray array]; + for (NSData *certificateData in self.pinnedCertificates) { + [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)]; + } + SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates); + + if (!AFServerTrustIsValid(serverTrust)) { + return NO; + } + + // obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA) + NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); + + for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) { + if ([self.pinnedCertificates containsObject:trustChainCertificate]) { + return YES; + } + } + + return NO; + } + case AFSSLPinningModePublicKey: { + NSUInteger trustedPublicKeyCount = 0; + NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust); + + for (id trustChainPublicKey in publicKeys) { + for (id pinnedPublicKey in self.pinnedPublicKeys) { + if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) { + trustedPublicKeyCount += 1; + } + } + } + return trustedPublicKeyCount > 0; + } + } + + return NO; +} + +#pragma mark - NSKeyValueObserving + ++ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys { + return [NSSet setWithObject:@"pinnedCertificates"]; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + + self = [self init]; + if (!self) { + return nil; + } + + self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue]; + self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; + self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))]; + self.pinnedCertificates = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(pinnedCertificates))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))]; + [coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; + [coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))]; + [coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init]; + securityPolicy.SSLPinningMode = self.SSLPinningMode; + securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates; + securityPolicy.validatesDomainName = self.validatesDomainName; + securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone]; + + return securityPolicy; +} + +@end diff --git a/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h b/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h new file mode 100644 index 0000000..694696b --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h @@ -0,0 +1,479 @@ +// AFURLRequestSerialization.h +// Copyright (c) 2011–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 +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import +#elif TARGET_OS_WATCH +#import +#endif + +NS_ASSUME_NONNULL_BEGIN + +/** + Returns a percent-escaped string following RFC 3986 for a query string key or value. + RFC 3986 states that the following characters are "reserved" characters. + - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + should be percent-escaped in the query string. + + @param string The string to be percent-escaped. + + @return The percent-escaped string. + */ +FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string); + +/** + A helper method to generate encoded url query parameters for appending to the end of a URL. + + @param parameters A dictionary of key/values to be encoded. + + @return A url encoded query string + */ +FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters); + +/** + The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary. + + For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`. + */ +@protocol AFURLRequestSerialization + +/** + Returns a request with the specified parameters encoded into a copy of the original request. + + @param request The original request. + @param parameters The parameters to be encoded. + @param error The error that occurred while attempting to encode the request parameters. + + @return A serialized request. + */ +- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(nullable id)parameters + error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; + +@end + +#pragma mark - + +/** + + */ +typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) { + AFHTTPRequestQueryStringDefaultStyle = 0, +}; + +@protocol AFMultipartFormData; + +/** + `AFHTTPRequestSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. + + Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior. + */ +@interface AFHTTPRequestSerializer : NSObject + +/** + The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default. + */ +@property (nonatomic, assign) NSStringEncoding stringEncoding; + +/** + Whether created requests can use the device’s cellular radio (if present). `YES` by default. + + @see NSMutableURLRequest -setAllowsCellularAccess: + */ +@property (nonatomic, assign) BOOL allowsCellularAccess; + +/** + The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default. + + @see NSMutableURLRequest -setCachePolicy: + */ +@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy; + +/** + Whether created requests should use the default cookie handling. `YES` by default. + + @see NSMutableURLRequest -setHTTPShouldHandleCookies: + */ +@property (nonatomic, assign) BOOL HTTPShouldHandleCookies; + +/** + Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default + + @see NSMutableURLRequest -setHTTPShouldUsePipelining: + */ +@property (nonatomic, assign) BOOL HTTPShouldUsePipelining; + +/** + The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default. + + @see NSMutableURLRequest -setNetworkServiceType: + */ +@property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType; + +/** + The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds. + + @see NSMutableURLRequest -setTimeoutInterval: + */ +@property (nonatomic, assign) NSTimeInterval timeoutInterval; + +///--------------------------------------- +/// @name Configuring HTTP Request Headers +///--------------------------------------- + +/** + Default HTTP header field values to be applied to serialized requests. By default, these include the following: + + - `Accept-Language` with the contents of `NSLocale +preferredLanguages` + - `User-Agent` with the contents of various bundle identifiers and OS designations + + @discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *HTTPRequestHeaders; + +/** + Creates and returns a serializer with default configuration. + */ ++ (instancetype)serializer; + +/** + Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header. + + @param field The HTTP header to set a default value for + @param value The value set as default for the specified header, or `nil` + */ +- (void)setValue:(nullable NSString *)value +forHTTPHeaderField:(NSString *)field; + +/** + Returns the value for the HTTP headers set in the request serializer. + + @param field The HTTP header to retrieve the default value for + + @return The value set as default for the specified header, or `nil` + */ +- (nullable NSString *)valueForHTTPHeaderField:(NSString *)field; + +/** + Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header. + + @param username The HTTP basic auth username + @param password The HTTP basic auth password + */ +- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username + password:(NSString *)password; + +/** + Clears any existing value for the "Authorization" HTTP header. + */ +- (void)clearAuthorizationHeader; + +///------------------------------------------------------- +/// @name Configuring Query String Parameter Serialization +///------------------------------------------------------- + +/** + HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default. + */ +@property (nonatomic, strong) NSSet *HTTPMethodsEncodingParametersInURI; + +/** + Set the method of query string serialization according to one of the pre-defined styles. + + @param style The serialization style. + + @see AFHTTPRequestQueryStringSerializationStyle + */ +- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style; + +/** + Set the a custom method of query string serialization according to the specified block. + + @param block A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occurred when attempting to encode parameters for the given request. + */ +- (void)setQueryStringSerializationWithBlock:(nullable NSString * (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block; + +///------------------------------- +/// @name Creating Request Objects +///------------------------------- + +/** + Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string. + + If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body. + + @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`. + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body. + @param error The error that occurred while constructing the request. + + @return An `NSMutableURLRequest` object. + */ +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(nullable id)parameters + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2 + + Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream. + + @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`. + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded and set in the request HTTP body. + @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. + @param error The error that occurred while constructing the request. + + @return An `NSMutableURLRequest` object + */ +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(nullable NSDictionary *)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Creates an `NSMutableURLRequest` by removing the `HTTPBodyStream` from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished. + + @param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`. + @param fileURL The file URL to write multipart form contents to. + @param handler A handler block to execute. + + @discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request. + + @see https://github.com/AFNetworking/AFNetworking/issues/1398 + */ +- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request + writingStreamContentsToFile:(NSURL *)fileURL + completionHandler:(nullable void (^)(NSError * _Nullable error))handler; + +@end + +#pragma mark - + +/** + The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`. + */ +@protocol AFMultipartFormData + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary. + + The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively. + + @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param error If an error occurs, upon return contains an `NSError` object that describes the problem. + + @return `YES` if the file data was successfully appended, otherwise `NO`. + */ +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. + + @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`. + @param mimeType The declared MIME type of the file data. This parameter must not be `nil`. + @param error If an error occurs, upon return contains an `NSError` object that describes the problem. + + @return `YES` if the file data was successfully appended otherwise `NO`. + */ +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary. + + @param inputStream The input stream to be appended to the form data + @param name The name to be associated with the specified input stream. This parameter must not be `nil`. + @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`. + @param length The length of the specified input stream in bytes. + @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. + */ +- (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream + name:(NSString *)name + fileName:(NSString *)fileName + length:(int64_t)length + mimeType:(NSString *)mimeType; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. + + @param data The data to be encoded and appended to the form data. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param fileName The filename to be associated with the specified data. This parameter must not be `nil`. + @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. + */ +- (void)appendPartWithFileData:(NSData *)data + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType; + +/** + Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary. + + @param data The data to be encoded and appended to the form data. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + */ + +- (void)appendPartWithFormData:(NSData *)data + name:(NSString *)name; + + +/** + Appends HTTP headers, followed by the encoded data and the multipart form boundary. + + @param headers The HTTP headers to be appended to the form data. + @param body The data to be encoded and appended to the form data. This parameter must not be `nil`. + */ +- (void)appendPartWithHeaders:(nullable NSDictionary *)headers + body:(NSData *)body; + +/** + Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream. + + When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth. + + @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb. + @param delay Duration of delay each time a packet is read. By default, no delay is set. + */ +- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes + delay:(NSTimeInterval)delay; + +@end + +#pragma mark - + +/** + `AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`. + */ +@interface AFJSONRequestSerializer : AFHTTPRequestSerializer + +/** + Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default. + */ +@property (nonatomic, assign) NSJSONWritingOptions writingOptions; + +/** + Creates and returns a JSON serializer with specified reading and writing options. + + @param writingOptions The specified JSON writing options. + */ ++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions; + +@end + +#pragma mark - + +/** + `AFPropertyListRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`. + */ +@interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer + +/** + The property list format. Possible values are described in "NSPropertyListFormat". + */ +@property (nonatomic, assign) NSPropertyListFormat format; + +/** + @warning The `writeOptions` property is currently unused. + */ +@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions; + +/** + Creates and returns a property list serializer with a specified format, read options, and write options. + + @param format The property list format. + @param writeOptions The property list write options. + + @warning The `writeOptions` property is currently unused. + */ ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + writeOptions:(NSPropertyListWriteOptions)writeOptions; + +@end + +#pragma mark - + +///---------------- +/// @name Constants +///---------------- + +/** + ## Error Domains + + The following error domain is predefined. + + - `NSString * const AFURLRequestSerializationErrorDomain` + + ### Constants + + `AFURLRequestSerializationErrorDomain` + AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain; + +/** + ## User info dictionary keys + + These keys may exist in the user info dictionary, in addition to those defined for NSError. + + - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey` + + ### Constants + + `AFNetworkingOperationFailingURLRequestErrorKey` + The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey; + +/** + ## Throttling Bandwidth for HTTP Request Input Streams + + @see -throttleBandwidthWithPacketSize:delay: + + ### Constants + + `kAFUploadStream3GSuggestedPacketSize` + Maximum packet size, in number of bytes. Equal to 16kb. + + `kAFUploadStream3GSuggestedDelay` + Duration of delay each time a packet is read. Equal to 0.2 seconds. + */ +FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize; +FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay; + +NS_ASSUME_NONNULL_END diff --git a/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m b/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m new file mode 100644 index 0000000..a4d5d9d --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m @@ -0,0 +1,1398 @@ +// AFURLRequestSerialization.m +// Copyright (c) 2011–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 "AFURLRequestSerialization.h" + +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV +#import +#else +#import +#endif + +NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request"; +NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response"; + +typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error); + +/** + Returns a percent-escaped string following RFC 3986 for a query string key or value. + RFC 3986 states that the following characters are "reserved" characters. + - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + should be percent-escaped in the query string. + - parameter string: The string to be percent-escaped. + - returns: The percent-escaped string. + */ +NSString * AFPercentEscapedStringFromString(NSString *string) { + static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4 + static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;="; + + NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]]; + + // FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028 + // return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + + static NSUInteger const batchSize = 50; + + NSUInteger index = 0; + NSMutableString *escaped = @"".mutableCopy; + + while (index < string.length) { + NSUInteger length = MIN(string.length - index, batchSize); + NSRange range = NSMakeRange(index, length); + + // To avoid breaking up character sequences such as 👴🏻👮🏽 + range = [string rangeOfComposedCharacterSequencesForRange:range]; + + NSString *substring = [string substringWithRange:range]; + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + [escaped appendString:encoded]; + + index += range.length; + } + + return escaped; +} + +#pragma mark - + +@interface AFQueryStringPair : NSObject +@property (readwrite, nonatomic, strong) id field; +@property (readwrite, nonatomic, strong) id value; + +- (instancetype)initWithField:(id)field value:(id)value; + +- (NSString *)URLEncodedStringValue; +@end + +@implementation AFQueryStringPair + +- (instancetype)initWithField:(id)field value:(id)value { + self = [super init]; + if (!self) { + return nil; + } + + self.field = field; + self.value = value; + + return self; +} + +- (NSString *)URLEncodedStringValue { + if (!self.value || [self.value isEqual:[NSNull null]]) { + return AFPercentEscapedStringFromString([self.field description]); + } else { + return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedStringFromString([self.field description]), AFPercentEscapedStringFromString([self.value description])]; + } +} + +@end + +#pragma mark - + +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); + +NSString * AFQueryStringFromParameters(NSDictionary *parameters) { + NSMutableArray *mutablePairs = [NSMutableArray array]; + for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { + [mutablePairs addObject:[pair URLEncodedStringValue]]; + } + + return [mutablePairs componentsJoinedByString:@"&"]; +} + +NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) { + return AFQueryStringPairsFromKeyAndValue(nil, dictionary); +} + +NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) { + NSMutableArray *mutableQueryStringComponents = [NSMutableArray array]; + + NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)]; + + if ([value isKindOfClass:[NSDictionary class]]) { + NSDictionary *dictionary = value; + // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries + for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { + id nestedValue = dictionary[nestedKey]; + if (nestedValue) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)]; + } + } + } else if ([value isKindOfClass:[NSArray class]]) { + NSArray *array = value; + for (id nestedValue in array) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)]; + } + } else if ([value isKindOfClass:[NSSet class]]) { + NSSet *set = value; + for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)]; + } + } else { + [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]]; + } + + return mutableQueryStringComponents; +} + +#pragma mark - + +@interface AFStreamingMultipartFormData : NSObject +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest + stringEncoding:(NSStringEncoding)encoding; + +- (NSMutableURLRequest *)requestByFinalizingMultipartFormData; +@end + +#pragma mark - + +static NSArray * AFHTTPRequestSerializerObservedKeyPaths() { + static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))]; + }); + + return _AFHTTPRequestSerializerObservedKeyPaths; +} + +static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerObserverContext; + +@interface AFHTTPRequestSerializer () +@property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths; +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders; +@property (readwrite, nonatomic, strong) dispatch_queue_t requestHeaderModificationQueue; +@property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle; +@property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization; +@end + +@implementation AFHTTPRequestSerializer + ++ (instancetype)serializer { + return [[self alloc] init]; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.stringEncoding = NSUTF8StringEncoding; + + self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary]; + self.requestHeaderModificationQueue = dispatch_queue_create("requestHeaderModificationQueue", DISPATCH_QUEUE_CONCURRENT); + + // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 + NSMutableArray *acceptLanguagesComponents = [NSMutableArray array]; + [[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + float q = 1.0f - (idx * 0.1f); + [acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]]; + *stop = q <= 0.5f; + }]; + [self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"]; + + NSString *userAgent = nil; +#if TARGET_OS_IOS + // 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 TARGET_OS_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 defined(__MAC_OS_X_VERSION_MIN_REQUIRED) + 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; + } + } + [self setValue:userAgent forHTTPHeaderField:@"User-Agent"]; + } + + // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html + self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil]; + + self.mutableObservedChangedKeyPaths = [NSMutableSet set]; + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { + if ([self respondsToSelector:NSSelectorFromString(keyPath)]) { + [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext]; + } + } + + return self; +} + +- (void)dealloc { + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { + if ([self respondsToSelector:NSSelectorFromString(keyPath)]) { + [self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext]; + } + } +} + +#pragma mark - + +// Workarounds for crashing behavior using Key-Value Observing with XCTest +// See https://github.com/AFNetworking/AFNetworking/issues/2523 + +- (void)setAllowsCellularAccess:(BOOL)allowsCellularAccess { + [self willChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))]; + _allowsCellularAccess = allowsCellularAccess; + [self didChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))]; +} + +- (void)setCachePolicy:(NSURLRequestCachePolicy)cachePolicy { + [self willChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))]; + _cachePolicy = cachePolicy; + [self didChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))]; +} + +- (void)setHTTPShouldHandleCookies:(BOOL)HTTPShouldHandleCookies { + [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))]; + _HTTPShouldHandleCookies = HTTPShouldHandleCookies; + [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))]; +} + +- (void)setHTTPShouldUsePipelining:(BOOL)HTTPShouldUsePipelining { + [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))]; + _HTTPShouldUsePipelining = HTTPShouldUsePipelining; + [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))]; +} + +- (void)setNetworkServiceType:(NSURLRequestNetworkServiceType)networkServiceType { + [self willChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))]; + _networkServiceType = networkServiceType; + [self didChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))]; +} + +- (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval { + [self willChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))]; + _timeoutInterval = timeoutInterval; + [self didChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))]; +} + +#pragma mark - + +- (NSDictionary *)HTTPRequestHeaders { + NSDictionary __block *value; + dispatch_sync(self.requestHeaderModificationQueue, ^{ + value = [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders]; + }); + return value; +} + +- (void)setValue:(NSString *)value +forHTTPHeaderField:(NSString *)field +{ + dispatch_barrier_async(self.requestHeaderModificationQueue, ^{ + [self.mutableHTTPRequestHeaders setValue:value forKey:field]; + }); +} + +- (NSString *)valueForHTTPHeaderField:(NSString *)field { + NSString __block *value; + dispatch_sync(self.requestHeaderModificationQueue, ^{ + value = [self.mutableHTTPRequestHeaders valueForKey:field]; + }); + return value; +} + +- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username + password:(NSString *)password +{ + NSData *basicAuthCredentials = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding]; + NSString *base64AuthCredentials = [basicAuthCredentials base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0]; + [self setValue:[NSString stringWithFormat:@"Basic %@", base64AuthCredentials] forHTTPHeaderField:@"Authorization"]; +} + +- (void)clearAuthorizationHeader { + dispatch_barrier_async(self.requestHeaderModificationQueue, ^{ + [self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"]; + }); +} + +#pragma mark - + +- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style { + self.queryStringSerializationStyle = style; + self.queryStringSerialization = nil; +} + +- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, id, NSError *__autoreleasing *))block { + self.queryStringSerialization = block; +} + +#pragma mark - + +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(method); + NSParameterAssert(URLString); + + NSURL *url = [NSURL URLWithString:URLString]; + + NSParameterAssert(url); + + NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url]; + mutableRequest.HTTPMethod = method; + + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { + if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) { + [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath]; + } + } + + mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy]; + + return mutableRequest; +} + +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(NSDictionary *)parameters + constructingBodyWithBlock:(void (^)(id formData))block + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(method); + NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]); + + NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error]; + + __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding]; + + if (parameters) { + for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { + NSData *data = nil; + if ([pair.value isKindOfClass:[NSData class]]) { + data = pair.value; + } else if ([pair.value isEqual:[NSNull null]]) { + data = [NSData data]; + } else { + data = [[pair.value description] dataUsingEncoding:self.stringEncoding]; + } + + if (data) { + [formData appendPartWithFormData:data name:[pair.field description]]; + } + } + } + + if (block) { + block(formData); + } + + return [formData requestByFinalizingMultipartFormData]; +} + +- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request + writingStreamContentsToFile:(NSURL *)fileURL + completionHandler:(void (^)(NSError *error))handler +{ + NSParameterAssert(request.HTTPBodyStream); + NSParameterAssert([fileURL isFileURL]); + + NSInputStream *inputStream = request.HTTPBodyStream; + NSOutputStream *outputStream = [[NSOutputStream alloc] initWithURL:fileURL append:NO]; + __block NSError *error = nil; + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + + [inputStream open]; + [outputStream open]; + + while ([inputStream hasBytesAvailable] && [outputStream hasSpaceAvailable]) { + uint8_t buffer[1024]; + + NSInteger bytesRead = [inputStream read:buffer maxLength:1024]; + if (inputStream.streamError || bytesRead < 0) { + error = inputStream.streamError; + break; + } + + NSInteger bytesWritten = [outputStream write:buffer maxLength:(NSUInteger)bytesRead]; + if (outputStream.streamError || bytesWritten < 0) { + error = outputStream.streamError; + break; + } + + if (bytesRead == 0 && bytesWritten == 0) { + break; + } + } + + [outputStream close]; + [inputStream close]; + + if (handler) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler(error); + }); + } + }); + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + mutableRequest.HTTPBodyStream = nil; + + return mutableRequest; +} + +#pragma mark - AFURLRequestSerialization + +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(request); + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { + if (![request valueForHTTPHeaderField:field]) { + [mutableRequest setValue:value forHTTPHeaderField:field]; + } + }]; + + NSString *query = nil; + if (parameters) { + if (self.queryStringSerialization) { + NSError *serializationError; + query = self.queryStringSerialization(request, parameters, &serializationError); + + if (serializationError) { + if (error) { + *error = serializationError; + } + + return nil; + } + } else { + switch (self.queryStringSerializationStyle) { + case AFHTTPRequestQueryStringDefaultStyle: + query = AFQueryStringFromParameters(parameters); + break; + } + } + } + + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + if (query && query.length > 0) { + mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]]; + } + } else { + // #2864: an empty string is a valid x-www-form-urlencoded payload + if (!query) { + query = @""; + } + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { + [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; + } + [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]]; + } + + return mutableRequest; +} + +#pragma mark - NSKeyValueObserving + ++ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key { + if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) { + return NO; + } + + return [super automaticallyNotifiesObserversForKey:key]; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath + ofObject:(__unused id)object + change:(NSDictionary *)change + context:(void *)context +{ + if (context == AFHTTPRequestSerializerObserverContext) { + if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) { + [self.mutableObservedChangedKeyPaths removeObject:keyPath]; + } else { + [self.mutableObservedChangedKeyPaths addObject:keyPath]; + } + } +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [self init]; + if (!self) { + return nil; + } + + self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy]; + self.queryStringSerializationStyle = (AFHTTPRequestQueryStringSerializationStyle)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + dispatch_sync(self.requestHeaderModificationQueue, ^{ + [coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))]; + }); + [coder encodeInteger:self.queryStringSerializationStyle forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init]; + dispatch_sync(self.requestHeaderModificationQueue, ^{ + serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone]; + }); + serializer.queryStringSerializationStyle = self.queryStringSerializationStyle; + serializer.queryStringSerialization = self.queryStringSerialization; + + return serializer; +} + +@end + +#pragma mark - + +static NSString * AFCreateMultipartFormBoundary() { + return [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()]; +} + +static NSString * const kAFMultipartFormCRLF = @"\r\n"; + +static inline NSString * AFMultipartFormInitialBoundary(NSString *boundary) { + return [NSString stringWithFormat:@"--%@%@", boundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFMultipartFormEncapsulationBoundary(NSString *boundary) { + return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) { + return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFContentTypeForPathExtension(NSString *extension) { + NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL); + NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType); + if (!contentType) { + return @"application/octet-stream"; + } else { + return contentType; + } +} + +NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16; +NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; + +@interface AFHTTPBodyPart : NSObject +@property (nonatomic, assign) NSStringEncoding stringEncoding; +@property (nonatomic, strong) NSDictionary *headers; +@property (nonatomic, copy) NSString *boundary; +@property (nonatomic, strong) id body; +@property (nonatomic, assign) unsigned long long bodyContentLength; +@property (nonatomic, strong) NSInputStream *inputStream; + +@property (nonatomic, assign) BOOL hasInitialBoundary; +@property (nonatomic, assign) BOOL hasFinalBoundary; + +@property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable; +@property (readonly, nonatomic, assign) unsigned long long contentLength; + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length; +@end + +@interface AFMultipartBodyStream : NSInputStream +@property (nonatomic, assign) NSUInteger numberOfBytesInPacket; +@property (nonatomic, assign) NSTimeInterval delay; +@property (nonatomic, strong) NSInputStream *inputStream; +@property (readonly, nonatomic, assign) unsigned long long contentLength; +@property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty; + +- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding; +- (void)setInitialAndFinalBoundaries; +- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart; +@end + +#pragma mark - + +@interface AFStreamingMultipartFormData () +@property (readwrite, nonatomic, copy) NSMutableURLRequest *request; +@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; +@property (readwrite, nonatomic, copy) NSString *boundary; +@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream; +@end + +@implementation AFStreamingMultipartFormData + +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest + stringEncoding:(NSStringEncoding)encoding +{ + self = [super init]; + if (!self) { + return nil; + } + + self.request = urlRequest; + self.stringEncoding = encoding; + self.boundary = AFCreateMultipartFormBoundary(); + self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding]; + + return self; +} + +- (void)setRequest:(NSMutableURLRequest *)request +{ + _request = [request mutableCopy]; +} + +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + error:(NSError * __autoreleasing *)error +{ + NSParameterAssert(fileURL); + NSParameterAssert(name); + + NSString *fileName = [fileURL lastPathComponent]; + NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]); + + return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error]; +} + +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType + error:(NSError * __autoreleasing *)error +{ + NSParameterAssert(fileURL); + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + if (![fileURL isFileURL]) { + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil)}; + if (error) { + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; + } + + return NO; + } else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) { + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil)}; + if (error) { + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; + } + + return NO; + } + + NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:error]; + if (!fileAttributes) { + return NO; + } + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = mutableHeaders; + bodyPart.boundary = self.boundary; + bodyPart.body = fileURL; + bodyPart.bodyContentLength = [fileAttributes[NSFileSize] unsignedLongLongValue]; + [self.bodyStream appendHTTPBodyPart:bodyPart]; + + return YES; +} + +- (void)appendPartWithInputStream:(NSInputStream *)inputStream + name:(NSString *)name + fileName:(NSString *)fileName + length:(int64_t)length + mimeType:(NSString *)mimeType +{ + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = mutableHeaders; + bodyPart.boundary = self.boundary; + bodyPart.body = inputStream; + + bodyPart.bodyContentLength = (unsigned long long)length; + + [self.bodyStream appendHTTPBodyPart:bodyPart]; +} + +- (void)appendPartWithFileData:(NSData *)data + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType +{ + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + [self appendPartWithHeaders:mutableHeaders body:data]; +} + +- (void)appendPartWithFormData:(NSData *)data + name:(NSString *)name +{ + NSParameterAssert(name); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"]; + + [self appendPartWithHeaders:mutableHeaders body:data]; +} + +- (void)appendPartWithHeaders:(NSDictionary *)headers + body:(NSData *)body +{ + NSParameterAssert(body); + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = headers; + bodyPart.boundary = self.boundary; + bodyPart.bodyContentLength = [body length]; + bodyPart.body = body; + + [self.bodyStream appendHTTPBodyPart:bodyPart]; +} + +- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes + delay:(NSTimeInterval)delay +{ + self.bodyStream.numberOfBytesInPacket = numberOfBytes; + self.bodyStream.delay = delay; +} + +- (NSMutableURLRequest *)requestByFinalizingMultipartFormData { + if ([self.bodyStream isEmpty]) { + return self.request; + } + + // Reset the initial and final boundaries to ensure correct Content-Length + [self.bodyStream setInitialAndFinalBoundaries]; + [self.request setHTTPBodyStream:self.bodyStream]; + + [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"]; + [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"]; + + return self.request; +} + +@end + +#pragma mark - + +@interface NSStream () +@property (readwrite) NSStreamStatus streamStatus; +@property (readwrite, copy) NSError *streamError; +@end + +@interface AFMultipartBodyStream () +@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; +@property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts; +@property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator; +@property (readwrite, nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart; +@property (readwrite, nonatomic, strong) NSOutputStream *outputStream; +@property (readwrite, nonatomic, strong) NSMutableData *buffer; +@end + +@implementation AFMultipartBodyStream +#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1100) +@synthesize delegate; +#endif +@synthesize streamStatus; +@synthesize streamError; + +- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding { + self = [super init]; + if (!self) { + return nil; + } + + self.stringEncoding = encoding; + self.HTTPBodyParts = [NSMutableArray array]; + self.numberOfBytesInPacket = NSIntegerMax; + + return self; +} + +- (void)setInitialAndFinalBoundaries { + if ([self.HTTPBodyParts count] > 0) { + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + bodyPart.hasInitialBoundary = NO; + bodyPart.hasFinalBoundary = NO; + } + + [[self.HTTPBodyParts firstObject] setHasInitialBoundary:YES]; + [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES]; + } +} + +- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart { + [self.HTTPBodyParts addObject:bodyPart]; +} + +- (BOOL)isEmpty { + return [self.HTTPBodyParts count] == 0; +} + +#pragma mark - NSInputStream + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ + if ([self streamStatus] == NSStreamStatusClosed) { + return 0; + } + + NSInteger totalNumberOfBytesRead = 0; + + while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) { + if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) { + if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) { + break; + } + } else { + NSUInteger maxLength = MIN(length, self.numberOfBytesInPacket) - (NSUInteger)totalNumberOfBytesRead; + NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength]; + if (numberOfBytesRead == -1) { + self.streamError = self.currentHTTPBodyPart.inputStream.streamError; + break; + } else { + totalNumberOfBytesRead += numberOfBytesRead; + + if (self.delay > 0.0f) { + [NSThread sleepForTimeInterval:self.delay]; + } + } + } + } + + return totalNumberOfBytesRead; +} + +- (BOOL)getBuffer:(__unused uint8_t **)buffer + length:(__unused NSUInteger *)len +{ + return NO; +} + +- (BOOL)hasBytesAvailable { + return [self streamStatus] == NSStreamStatusOpen; +} + +#pragma mark - NSStream + +- (void)open { + if (self.streamStatus == NSStreamStatusOpen) { + return; + } + + self.streamStatus = NSStreamStatusOpen; + + [self setInitialAndFinalBoundaries]; + self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator]; +} + +- (void)close { + self.streamStatus = NSStreamStatusClosed; +} + +- (id)propertyForKey:(__unused NSString *)key { + return nil; +} + +- (BOOL)setProperty:(__unused id)property + forKey:(__unused NSString *)key +{ + return NO; +} + +- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop + forMode:(__unused NSString *)mode +{} + +- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop + forMode:(__unused NSString *)mode +{} + +- (unsigned long long)contentLength { + unsigned long long length = 0; + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + length += [bodyPart contentLength]; + } + + return length; +} + +#pragma mark - Undocumented CFReadStream Bridged Methods + +- (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop + forMode:(__unused CFStringRef)aMode +{} + +- (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop + forMode:(__unused CFStringRef)aMode +{} + +- (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags + callback:(__unused CFReadStreamClientCallBack)inCallback + context:(__unused CFStreamClientContext *)inContext { + return NO; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding]; + + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + [bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]]; + } + + [bodyStreamCopy setInitialAndFinalBoundaries]; + + return bodyStreamCopy; +} + +@end + +#pragma mark - + +typedef enum { + AFEncapsulationBoundaryPhase = 1, + AFHeaderPhase = 2, + AFBodyPhase = 3, + AFFinalBoundaryPhase = 4, +} AFHTTPBodyPartReadPhase; + +@interface AFHTTPBodyPart () { + AFHTTPBodyPartReadPhase _phase; + NSInputStream *_inputStream; + unsigned long long _phaseReadOffset; +} + +- (BOOL)transitionToNextPhase; +- (NSInteger)readData:(NSData *)data + intoBuffer:(uint8_t *)buffer + maxLength:(NSUInteger)length; +@end + +@implementation AFHTTPBodyPart + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + [self transitionToNextPhase]; + + return self; +} + +- (void)dealloc { + if (_inputStream) { + [_inputStream close]; + _inputStream = nil; + } +} + +- (NSInputStream *)inputStream { + if (!_inputStream) { + if ([self.body isKindOfClass:[NSData class]]) { + _inputStream = [NSInputStream inputStreamWithData:self.body]; + } else if ([self.body isKindOfClass:[NSURL class]]) { + _inputStream = [NSInputStream inputStreamWithURL:self.body]; + } else if ([self.body isKindOfClass:[NSInputStream class]]) { + _inputStream = self.body; + } else { + _inputStream = [NSInputStream inputStreamWithData:[NSData data]]; + } + } + + return _inputStream; +} + +- (NSString *)stringForHeaders { + NSMutableString *headerString = [NSMutableString string]; + for (NSString *field in [self.headers allKeys]) { + [headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]]; + } + [headerString appendString:kAFMultipartFormCRLF]; + + return [NSString stringWithString:headerString]; +} + +- (unsigned long long)contentLength { + unsigned long long length = 0; + + NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding]; + length += [encapsulationBoundaryData length]; + + NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; + length += [headersData length]; + + length += _bodyContentLength; + + NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]); + length += [closingBoundaryData length]; + + return length; +} + +- (BOOL)hasBytesAvailable { + // Allows `read:maxLength:` to be called again if `AFMultipartFormFinalBoundary` doesn't fit into the available buffer + if (_phase == AFFinalBoundaryPhase) { + return YES; + } + + switch (self.inputStream.streamStatus) { + case NSStreamStatusNotOpen: + case NSStreamStatusOpening: + case NSStreamStatusOpen: + case NSStreamStatusReading: + case NSStreamStatusWriting: + return YES; + case NSStreamStatusAtEnd: + case NSStreamStatusClosed: + case NSStreamStatusError: + default: + return NO; + } +} + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ + NSInteger totalNumberOfBytesRead = 0; + + if (_phase == AFEncapsulationBoundaryPhase) { + NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding]; + totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + if (_phase == AFHeaderPhase) { + NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; + totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + if (_phase == AFBodyPhase) { + NSInteger numberOfBytesRead = 0; + + numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + if (numberOfBytesRead == -1) { + return -1; + } else { + totalNumberOfBytesRead += numberOfBytesRead; + + if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) { + [self transitionToNextPhase]; + } + } + } + + if (_phase == AFFinalBoundaryPhase) { + NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]); + totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + return totalNumberOfBytesRead; +} + +- (NSInteger)readData:(NSData *)data + intoBuffer:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ + NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length)); + [data getBytes:buffer range:range]; + + _phaseReadOffset += range.length; + + if (((NSUInteger)_phaseReadOffset) >= [data length]) { + [self transitionToNextPhase]; + } + + return (NSInteger)range.length; +} + +- (BOOL)transitionToNextPhase { + if (![[NSThread currentThread] isMainThread]) { + dispatch_sync(dispatch_get_main_queue(), ^{ + [self transitionToNextPhase]; + }); + return YES; + } + + switch (_phase) { + case AFEncapsulationBoundaryPhase: + _phase = AFHeaderPhase; + break; + case AFHeaderPhase: + [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; + [self.inputStream open]; + _phase = AFBodyPhase; + break; + case AFBodyPhase: + [self.inputStream close]; + _phase = AFFinalBoundaryPhase; + break; + case AFFinalBoundaryPhase: + default: + _phase = AFEncapsulationBoundaryPhase; + break; + } + _phaseReadOffset = 0; + + return YES; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init]; + + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = self.headers; + bodyPart.bodyContentLength = self.bodyContentLength; + bodyPart.body = self.body; + bodyPart.boundary = self.boundary; + + return bodyPart; +} + +@end + +#pragma mark - + +@implementation AFJSONRequestSerializer + ++ (instancetype)serializer { + return [self serializerWithWritingOptions:(NSJSONWritingOptions)0]; +} + ++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions +{ + AFJSONRequestSerializer *serializer = [[self alloc] init]; + serializer.writingOptions = writingOptions; + + return serializer; +} + +#pragma mark - AFURLRequestSerialization + +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(request); + + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + return [super requestBySerializingRequest:request withParameters:parameters error:error]; + } + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { + if (![request valueForHTTPHeaderField:field]) { + [mutableRequest setValue:value forHTTPHeaderField:field]; + } + }]; + + if (parameters) { + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { + [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; + } + + if (![NSJSONSerialization isValidJSONObject:parameters]) { + if (error) { + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"The `parameters` argument is not valid JSON.", @"AFNetworking", nil)}; + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo]; + } + return nil; + } + + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]; + + if (!jsonData) { + return nil; + } + + [mutableRequest setHTTPBody:jsonData]; + } + + return mutableRequest; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.writingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writingOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeInteger:self.writingOptions forKey:NSStringFromSelector(@selector(writingOptions))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFJSONRequestSerializer *serializer = [super copyWithZone:zone]; + serializer.writingOptions = self.writingOptions; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFPropertyListRequestSerializer + ++ (instancetype)serializer { + return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0]; +} + ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + writeOptions:(NSPropertyListWriteOptions)writeOptions +{ + AFPropertyListRequestSerializer *serializer = [[self alloc] init]; + serializer.format = format; + serializer.writeOptions = writeOptions; + + return serializer; +} + +#pragma mark - AFURLRequestSerializer + +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(request); + + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + return [super requestBySerializingRequest:request withParameters:parameters error:error]; + } + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { + if (![request valueForHTTPHeaderField:field]) { + [mutableRequest setValue:value forHTTPHeaderField:field]; + } + }]; + + if (parameters) { + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { + [mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"]; + } + + NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error]; + + if (!plistData) { + return nil; + } + + [mutableRequest setHTTPBody:plistData]; + } + + return mutableRequest; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; + self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeInteger:self.format forKey:NSStringFromSelector(@selector(format))]; + [coder encodeObject:@(self.writeOptions) forKey:NSStringFromSelector(@selector(writeOptions))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone]; + serializer.format = self.format; + serializer.writeOptions = self.writeOptions; + + return serializer; +} + +@end diff --git a/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h b/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h new file mode 100644 index 0000000..24800a3 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h @@ -0,0 +1,310 @@ +// AFURLResponseSerialization.h +// Copyright (c) 2011–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 +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data. + + For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object. + */ +@protocol AFURLResponseSerialization + +/** + The response object decoded from the data associated with a specified response. + + @param response The response to be processed. + @param data The response data to be decoded. + @param error The error that occurred while attempting to decode the response data. + + @return The object decoded from the specified response data. + */ +- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response + data:(nullable NSData *)data + error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; + +@end + +#pragma mark - + +/** + `AFHTTPResponseSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. + + Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior. + */ +@interface AFHTTPResponseSerializer : NSObject + +- (instancetype)init; + +@property (nonatomic, assign) NSStringEncoding stringEncoding DEPRECATED_MSG_ATTRIBUTE("The string encoding is never used. AFHTTPResponseSerializer only validates status codes and content types but does not try to decode the received data in any way."); + +/** + Creates and returns a serializer with default configuration. + */ ++ (instancetype)serializer; + +///----------------------------------------- +/// @name Configuring Response Serialization +///----------------------------------------- + +/** + The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation. + + See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html + */ +@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes; + +/** + The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation. + */ +@property (nonatomic, copy, nullable) NSSet *acceptableContentTypes; + +/** + Validates the specified response and data. + + In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks. + + @param response The response to be validated. + @param data The data associated with the response. + @param error The error that occurred while attempting to validate the response. + + @return `YES` if the response is valid, otherwise `NO`. + */ +- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response + data:(nullable NSData *)data + error:(NSError * _Nullable __autoreleasing *)error; + +@end + +#pragma mark - + + +/** + `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses. + + By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types: + + - `application/json` + - `text/json` + - `text/javascript` + + In RFC 7159 - Section 8.1, it states that JSON text is required to be encoded in UTF-8, UTF-16, or UTF-32, and the default encoding is UTF-8. NSJSONSerialization provides support for all the encodings listed in the specification, and recommends UTF-8 for efficiency. Using an unsupported encoding will result in serialization error. See the `NSJSONSerialization` documentation for more details. + */ +@interface AFJSONResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. + */ +@property (nonatomic, assign) NSJSONReadingOptions readingOptions; + +/** + Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`. + */ +@property (nonatomic, assign) BOOL removesKeysWithNullValues; + +/** + Creates and returns a JSON serializer with specified reading and writing options. + + @param readingOptions The specified JSON reading options. + */ ++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions; + +@end + +#pragma mark - + +/** + `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects. + + By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: + + - `application/xml` + - `text/xml` + */ +@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer + +@end + +#pragma mark - + +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED + +/** + `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. + + By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: + + - `application/xml` + - `text/xml` + */ +@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSXMLDocument` documentation section "Input and Output Options". `0` by default. + */ +@property (nonatomic, assign) NSUInteger options; + +/** + Creates and returns an XML document serializer with the specified options. + + @param mask The XML document options. + */ ++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask; + +@end + +#endif + +#pragma mark - + +/** + `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. + + By default, `AFPropertyListResponseSerializer` accepts the following MIME types: + + - `application/x-plist` + */ +@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + The property list format. Possible values are described in "NSPropertyListFormat". + */ +@property (nonatomic, assign) NSPropertyListFormat format; + +/** + The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions." + */ +@property (nonatomic, assign) NSPropertyListReadOptions readOptions; + +/** + Creates and returns a property list serializer with a specified format, read options, and write options. + + @param format The property list format. + @param readOptions The property list reading options. + */ ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + readOptions:(NSPropertyListReadOptions)readOptions; + +@end + +#pragma mark - + +/** + `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses. + + By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: + + - `image/tiff` + - `image/jpeg` + - `image/gif` + - `image/png` + - `image/ico` + - `image/x-icon` + - `image/bmp` + - `image/x-bmp` + - `image/x-xbitmap` + - `image/x-win-bitmap` + */ +@interface AFImageResponseSerializer : AFHTTPResponseSerializer + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH +/** + The scale factor used when interpreting the image data to construct `responseImage`. Specifying 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. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. + */ +@property (nonatomic, assign) CGFloat imageScale; + +/** + Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default. + */ +@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage; +#endif + +@end + +#pragma mark - + +/** + `AFCompoundSerializer` is a subclass of `AFHTTPResponseSerializer` that delegates the response serialization to the first `AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer. + */ +@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer + +/** + The component response serializers. + */ +@property (readonly, nonatomic, copy) NSArray > *responseSerializers; + +/** + Creates and returns a compound serializer comprised of the specified response serializers. + + @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`. + */ ++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray > *)responseSerializers; + +@end + +///---------------- +/// @name Constants +///---------------- + +/** + ## Error Domains + + The following error domain is predefined. + + - `NSString * const AFURLResponseSerializationErrorDomain` + + ### Constants + + `AFURLResponseSerializationErrorDomain` + AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain; + +/** + ## User info dictionary keys + + These keys may exist in the user info dictionary, in addition to those defined for NSError. + + - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` + - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey` + + ### Constants + + `AFNetworkingOperationFailingURLResponseErrorKey` + The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. + + `AFNetworkingOperationFailingURLResponseDataErrorKey` + The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey; + +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; + +NS_ASSUME_NONNULL_END diff --git a/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m b/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m new file mode 100755 index 0000000..b7be3d4 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m @@ -0,0 +1,817 @@ +// AFURLResponseSerialization.m +// Copyright (c) 2011–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 "AFURLResponseSerialization.h" + +#import + +#if TARGET_OS_IOS +#import +#elif TARGET_OS_WATCH +#import +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +#import +#endif + +NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response"; +NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response"; +NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data"; + +static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) { + if (!error) { + return underlyingError; + } + + if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) { + return error; + } + + NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy]; + mutableUserInfo[NSUnderlyingErrorKey] = underlyingError; + + return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo]; +} + +static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) { + if ([error.domain isEqualToString:domain] && error.code == code) { + return YES; + } else if (error.userInfo[NSUnderlyingErrorKey]) { + return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain); + } + + return NO; +} + +static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) { + if ([JSONObject isKindOfClass:[NSArray class]]) { + NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]]; + for (id value in (NSArray *)JSONObject) { + [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)]; + } + + return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray]; + } else if ([JSONObject isKindOfClass:[NSDictionary class]]) { + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject]; + for (id key in [(NSDictionary *)JSONObject allKeys]) { + id value = (NSDictionary *)JSONObject[key]; + if (!value || [value isEqual:[NSNull null]]) { + [mutableDictionary removeObjectForKey:key]; + } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) { + mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions); + } + } + + return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary]; + } + + return JSONObject; +} + +@implementation AFHTTPResponseSerializer + ++ (instancetype)serializer { + return [[self alloc] init]; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; + self.acceptableContentTypes = nil; + + return self; +} + +#pragma mark - + +- (BOOL)validateResponse:(NSHTTPURLResponse *)response + data:(NSData *)data + error:(NSError * __autoreleasing *)error +{ + BOOL responseIsValid = YES; + NSError *validationError = nil; + + if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) { + if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]] && + !([response MIMEType] == nil && [data length] == 0)) { + + if ([data length] > 0 && [response URL]) { + NSMutableDictionary *mutableUserInfo = [@{ + NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]], + NSURLErrorFailingURLErrorKey:[response URL], + AFNetworkingOperationFailingURLResponseErrorKey: response, + } mutableCopy]; + if (data) { + mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; + } + + validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError); + } + + responseIsValid = NO; + } + + if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) { + NSMutableDictionary *mutableUserInfo = [@{ + NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode], + NSURLErrorFailingURLErrorKey:[response URL], + AFNetworkingOperationFailingURLResponseErrorKey: response, + } mutableCopy]; + + if (data) { + mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; + } + + validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError); + + responseIsValid = NO; + } + } + + if (error && !responseIsValid) { + *error = validationError; + } + + return responseIsValid; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + [self validateResponse:(NSHTTPURLResponse *)response data:data error:error]; + + return data; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [self init]; + if (!self) { + return nil; + } + + self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; + self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; + [coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone]; + serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone]; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFJSONResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithReadingOptions:(NSJSONReadingOptions)0]; +} + ++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions { + AFJSONResponseSerializer *serializer = [[self alloc] init]; + serializer.readingOptions = readingOptions; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization. + // See https://github.com/rails/rails/issues/1742 + BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]]; + + if (data.length == 0 || isSpace) { + return nil; + } + + NSError *serializationError = nil; + + id responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError]; + + if (!responseObject) + { + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + return nil; + } + + if (self.removesKeysWithNullValues) { + return AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions); + } + + return responseObject; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue]; + self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))]; + [coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFJSONResponseSerializer *serializer = [super copyWithZone:zone]; + serializer.readingOptions = self.readingOptions; + serializer.removesKeysWithNullValues = self.removesKeysWithNullValues; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFXMLParserResponseSerializer + ++ (instancetype)serializer { + AFXMLParserResponseSerializer *serializer = [[self alloc] init]; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSHTTPURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + return [[NSXMLParser alloc] initWithData:data]; +} + +@end + +#pragma mark - + +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED + +@implementation AFXMLDocumentResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithXMLDocumentOptions:0]; +} + ++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask { + AFXMLDocumentResponseSerializer *serializer = [[self alloc] init]; + serializer.options = mask; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + NSError *serializationError = nil; + NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError]; + + if (!document) + { + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + return nil; + } + + return document; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFXMLDocumentResponseSerializer *serializer = [super copyWithZone:zone]; + serializer.options = self.options; + + return serializer; +} + +@end + +#endif + +#pragma mark - + +@implementation AFPropertyListResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0]; +} + ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + readOptions:(NSPropertyListReadOptions)readOptions +{ + AFPropertyListResponseSerializer *serializer = [[self alloc] init]; + serializer.format = format; + serializer.readOptions = readOptions; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + if (!data) { + return nil; + } + + NSError *serializationError = nil; + + id responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError]; + + if (!responseObject) + { + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + return nil; + } + + return responseObject; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; + self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))]; + [coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFPropertyListResponseSerializer *serializer = [super copyWithZone:zone]; + serializer.format = self.format; + serializer.readOptions = self.readOptions; + + return serializer; +} + +@end + +#pragma mark - + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH +#import +#import + +@interface UIImage (AFNetworkingSafeImageLoading) ++ (UIImage *)af_safeImageWithData:(NSData *)data; +@end + +static NSLock* imageLock = nil; + +@implementation UIImage (AFNetworkingSafeImageLoading) + ++ (UIImage *)af_safeImageWithData:(NSData *)data { + UIImage* image = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + imageLock = [[NSLock alloc] init]; + }); + + [imageLock lock]; + image = [UIImage imageWithData:data]; + [imageLock unlock]; + return image; +} + +@end + +static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) { + UIImage *image = [UIImage af_safeImageWithData:data]; + if (image.images) { + return image; + } + + return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation]; +} + +static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) { + if (!data || [data length] == 0) { + return nil; + } + + CGImageRef imageRef = NULL; + CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data); + + if ([response.MIMEType isEqualToString:@"image/png"]) { + imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); + } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) { + imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); + + if (imageRef) { + CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef); + CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace); + + // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale + if (imageColorSpaceModel == kCGColorSpaceModelCMYK) { + CGImageRelease(imageRef); + imageRef = NULL; + } + } + } + + CGDataProviderRelease(dataProvider); + + UIImage *image = AFImageWithDataAtScale(data, scale); + if (!imageRef) { + if (image.images || !image) { + return image; + } + + imageRef = CGImageCreateCopy([image CGImage]); + if (!imageRef) { + return nil; + } + } + + size_t width = CGImageGetWidth(imageRef); + size_t height = CGImageGetHeight(imageRef); + size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef); + + if (width * height > 1024 * 1024 || bitsPerComponent > 8) { + CGImageRelease(imageRef); + + return image; + } + + // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate + size_t bytesPerRow = 0; + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace); + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); + + if (colorSpaceModel == kCGColorSpaceModelRGB) { + uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask); +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wassign-enum" + if (alpha == kCGImageAlphaNone) { + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaNoneSkipFirst; + } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) { + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaPremultipliedFirst; + } +#pragma clang diagnostic pop + } + + CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo); + + CGColorSpaceRelease(colorSpace); + + if (!context) { + CGImageRelease(imageRef); + + return image; + } + + CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef); + CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context); + + CGContextRelease(context); + + UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation]; + + CGImageRelease(inflatedImageRef); + CGImageRelease(imageRef); + + return inflatedImage; +} +#endif + + +@implementation AFImageResponseSerializer + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; + +#if TARGET_OS_IOS || TARGET_OS_TV + self.imageScale = [[UIScreen mainScreen] scale]; + self.automaticallyInflatesResponseImage = YES; +#elif TARGET_OS_WATCH + self.imageScale = [[WKInterfaceDevice currentDevice] screenScale]; + self.automaticallyInflatesResponseImage = YES; +#endif + + return self; +} + +#pragma mark - AFURLResponseSerializer + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + if (self.automaticallyInflatesResponseImage) { + return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale); + } else { + return AFImageWithDataAtScale(data, self.imageScale); + } +#else + // Ensure that the image is set to it's correct pixel width and height + NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data]; + NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])]; + [image addRepresentation:bitimage]; + + return image; +#endif + + return nil; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))]; +#if CGFLOAT_IS_DOUBLE + self.imageScale = [imageScale doubleValue]; +#else + self.imageScale = [imageScale floatValue]; +#endif + + self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; +#endif + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))]; + [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; +#endif +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFImageResponseSerializer *serializer = [super copyWithZone:zone]; + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + serializer.imageScale = self.imageScale; + serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage; +#endif + + return serializer; +} + +@end + +#pragma mark - + +@interface AFCompoundResponseSerializer () +@property (readwrite, nonatomic, copy) NSArray *responseSerializers; +@end + +@implementation AFCompoundResponseSerializer + ++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers { + AFCompoundResponseSerializer *serializer = [[self alloc] init]; + serializer.responseSerializers = responseSerializers; + + return serializer; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + for (id serializer in self.responseSerializers) { + if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) { + continue; + } + + NSError *serializerError = nil; + id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError]; + if (responseObject) { + if (error) { + *error = AFErrorWithUnderlyingError(serializerError, *error); + } + + return responseObject; + } + } + + return [super responseObjectForResponse:response data:data error:error]; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.responseSerializers = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(responseSerializers))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFCompoundResponseSerializer *serializer = [super copyWithZone:zone]; + serializer.responseSerializers = self.responseSerializers; + + return serializer; +} + +@end diff --git a/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h b/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h new file mode 100644 index 0000000..e7ae0d8 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h @@ -0,0 +1,501 @@ +// AFURLSessionManager.h +// Copyright (c) 2011–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 + +#import "AFURLResponseSerialization.h" +#import "AFURLRequestSerialization.h" +#import "AFSecurityPolicy.h" +#import "AFCompatibilityMacros.h" +#if !TARGET_OS_WATCH +#import "AFNetworkReachabilityManager.h" +#endif + +/** + `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. + + ## Subclassing Notes + + This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead. + + ## NSURLSession & NSURLSessionTask Delegate Methods + + `AFURLSessionManager` implements the following delegate methods: + + ### `NSURLSessionDelegate` + + - `URLSession:didBecomeInvalidWithError:` + - `URLSession:didReceiveChallenge:completionHandler:` + - `URLSessionDidFinishEventsForBackgroundURLSession:` + + ### `NSURLSessionTaskDelegate` + + - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:` + - `URLSession:task:didReceiveChallenge:completionHandler:` + - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:` + - `URLSession:task:needNewBodyStream:` + - `URLSession:task:didCompleteWithError:` + + ### `NSURLSessionDataDelegate` + + - `URLSession:dataTask:didReceiveResponse:completionHandler:` + - `URLSession:dataTask:didBecomeDownloadTask:` + - `URLSession:dataTask:didReceiveData:` + - `URLSession:dataTask:willCacheResponse:completionHandler:` + + ### `NSURLSessionDownloadDelegate` + + - `URLSession:downloadTask:didFinishDownloadingToURL:` + - `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:` + - `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:` + + If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. + + ## Network Reachability Monitoring + + Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details. + + ## NSCoding Caveats + + - Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`. + + ## NSCopying Caveats + + - `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original. + - Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied. + + @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. + */ + +NS_ASSUME_NONNULL_BEGIN + +@interface AFURLSessionManager : NSObject + +/** + The managed session. + */ +@property (readonly, nonatomic, strong) NSURLSession *session; + +/** + The operation queue on which delegate callbacks are run. + */ +@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue; + +/** + Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`. + + @warning `responseSerializer` must not be `nil`. + */ +@property (nonatomic, strong) id responseSerializer; + +///------------------------------- +/// @name Managing Security Policy +///------------------------------- + +/** + The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. + */ +@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; + +#if !TARGET_OS_WATCH +///-------------------------------------- +/// @name Monitoring Network Reachability +///-------------------------------------- + +/** + The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default. + */ +@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; +#endif + +///---------------------------- +/// @name Getting Session Tasks +///---------------------------- + +/** + The data, upload, and download tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *tasks; + +/** + The data tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *dataTasks; + +/** + The upload tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *uploadTasks; + +/** + The download tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *downloadTasks; + +///------------------------------- +/// @name Managing Callback Queues +///------------------------------- + +/** + The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. + */ +@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; + +/** + The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. + */ +@property (nonatomic, strong, nullable) dispatch_group_t completionGroup; + +///--------------------------------- +/// @name Working Around System Bugs +///--------------------------------- + +/** + Whether to attempt to retry creation of upload tasks for background sessions when initial call returns `nil`. `NO` by default. + + @bug As of iOS 7.0, there is a bug where upload tasks created for background tasks are sometimes `nil`. As a workaround, if this property is `YES`, AFNetworking will follow Apple's recommendation to try creating the task again. + + @see https://github.com/AFNetworking/AFNetworking/issues/1675 + */ +@property (nonatomic, assign) BOOL attemptsToRecreateUploadTasksForBackgroundSessions; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns a manager for a session created with the specified configuration. This is the designated initializer. + + @param configuration The configuration used to create the managed session. + + @return A manager for a newly-created session. + */ +- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; + +/** + Invalidates the managed session, optionally canceling pending tasks. + + @param cancelPendingTasks Whether or not to cancel pending tasks. + */ +- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks; + +///------------------------- +/// @name Running Data Tasks +///------------------------- + +/** + Creates an `NSURLSessionDataTask` with the specified request. + + @param request The HTTP request for the request. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler DEPRECATED_ATTRIBUTE; + +/** + Creates an `NSURLSessionDataTask` with the specified request. + + @param request The HTTP request for the request. + @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +///--------------------------- +/// @name Running Upload Tasks +///--------------------------- + +/** + Creates an `NSURLSessionUploadTask` with the specified request for a local file. + + @param request The HTTP request for the request. + @param fileURL A URL to the local file to be uploaded. + @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + + @see `attemptsToRecreateUploadTasksForBackgroundSessions` + */ +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromFile:(NSURL *)fileURL + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body. + + @param request The HTTP request for the request. + @param bodyData A data object containing the HTTP body to be uploaded. + @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromData:(nullable NSData *)bodyData + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionUploadTask` with the specified streaming request. + + @param request The HTTP request for the request. + @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +///----------------------------- +/// @name Running Download Tasks +///----------------------------- + +/** + Creates an `NSURLSessionDownloadTask` with the specified request. + + @param request The HTTP request for the request. + @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. + @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. + + @warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method. + */ +- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request + progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock + destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionDownloadTask` with the specified resume data. + + @param resumeData The data used to resume downloading. + @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. + @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. + */ +- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData + progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock + destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; + +///--------------------------------- +/// @name Getting Progress for Tasks +///--------------------------------- + +/** + Returns the upload progress of the specified task. + + @param task The session task. Must not be `nil`. + + @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable. + */ +- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task; + +/** + Returns the download progress of the specified task. + + @param task The session task. Must not be `nil`. + + @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable. + */ +- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task; + +///----------------------------------------- +/// @name Setting Session Delegate Callbacks +///----------------------------------------- + +/** + Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`. + + @param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation. + */ +- (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block; + +/** + Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`. + + @param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. + */ +- (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; + +///-------------------------------------- +/// @name Setting Task Delegate Callbacks +///-------------------------------------- + +/** + Sets a block to be executed when a task requires a new request body stream to send to the remote server, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:needNewBodyStream:`. + + @param block A block object to be executed when a task requires a new request body stream. + */ +- (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block; + +/** + Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`. + + @param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response. + */ +- (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * _Nullable (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block; + +/** + Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`. + + @param block A block object to be executed when a session task has received a request specific authentication challenge. The block returns the disposition of the authentication challenge, and takes four arguments: the session, the task, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. + */ +- (void)setTaskDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; + +/** + Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. + + @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes five arguments: the session, the task, the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread. + */ +- (void)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block; + +/** + Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`. + + @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task. + */ +- (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block; + +///------------------------------------------- +/// @name Setting Data Task Delegate Callbacks +///------------------------------------------- + +/** + Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`. + + @param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response. + */ +- (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block; + +/** + Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`. + + @param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become. + */ +- (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block; + +/** + Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`. + + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue. + */ +- (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block; + +/** + Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`. + + @param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response. + */ +- (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block; + +/** + Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`. + + @param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session. + */ +- (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block AF_API_UNAVAILABLE(macos); + +///----------------------------------------------- +/// @name Setting Download Task Delegate Callbacks +///----------------------------------------------- + +/** + Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`. + + @param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error. + */ +- (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block; + +/** + Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`. + + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue. + */ +- (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block; + +/** + Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. + + @param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded. + */ +- (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block; + +@end + +///-------------------- +/// @name Notifications +///-------------------- + +/** + Posted when a task resumes. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification; + +/** + Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification; + +/** + Posted when a task suspends its execution. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification; + +/** + Posted when a session is invalidated. + */ +FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification; + +/** + Posted when a session download task encountered an error when moving the temporary download file to a specified destination. + */ +FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification; + +/** + The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey; + +/** + The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey; + +/** + The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey; + +/** + The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an the response data has been stored directly to disk. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey; + +/** + Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey; + +NS_ASSUME_NONNULL_END diff --git a/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m b/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m new file mode 100644 index 0000000..aeb1af3 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m @@ -0,0 +1,1238 @@ +// AFURLSessionManager.m +// Copyright (c) 2011–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 "AFURLSessionManager.h" +#import + +#ifndef NSFoundationVersionNumber_iOS_8_0 +#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug 1140.11 +#else +#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug NSFoundationVersionNumber_iOS_8_0 +#endif + +static dispatch_queue_t url_session_manager_creation_queue() { + static dispatch_queue_t af_url_session_manager_creation_queue; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_url_session_manager_creation_queue = dispatch_queue_create("com.alamofire.networking.session.manager.creation", DISPATCH_QUEUE_SERIAL); + }); + + return af_url_session_manager_creation_queue; +} + +static void url_session_manager_create_task_safely(dispatch_block_t block) { + if (NSFoundationVersionNumber < NSFoundationVersionNumber_With_Fixed_5871104061079552_bug) { + // Fix of bug + // Open Radar:http://openradar.appspot.com/radar?id=5871104061079552 (status: Fixed in iOS8) + // Issue about:https://github.com/AFNetworking/AFNetworking/issues/2093 + dispatch_sync(url_session_manager_creation_queue(), block); + } else { + block(); + } +} + +static dispatch_queue_t url_session_manager_processing_queue() { + static dispatch_queue_t af_url_session_manager_processing_queue; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_url_session_manager_processing_queue = dispatch_queue_create("com.alamofire.networking.session.manager.processing", DISPATCH_QUEUE_CONCURRENT); + }); + + return af_url_session_manager_processing_queue; +} + +static dispatch_group_t url_session_manager_completion_group() { + static dispatch_group_t af_url_session_manager_completion_group; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_url_session_manager_completion_group = dispatch_group_create(); + }); + + return af_url_session_manager_completion_group; +} + +NSString * const AFNetworkingTaskDidResumeNotification = @"com.alamofire.networking.task.resume"; +NSString * const AFNetworkingTaskDidCompleteNotification = @"com.alamofire.networking.task.complete"; +NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend"; +NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate"; +NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error"; + +NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; +NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; +NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; +NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error"; +NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; + +static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock"; + +static NSUInteger const AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask = 3; + +typedef void (^AFURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error); +typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); + +typedef NSURLRequest * (^AFURLSessionTaskWillPerformHTTPRedirectionBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request); +typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionTaskDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); +typedef void (^AFURLSessionDidFinishEventsForBackgroundURLSessionBlock)(NSURLSession *session); + +typedef NSInputStream * (^AFURLSessionTaskNeedNewBodyStreamBlock)(NSURLSession *session, NSURLSessionTask *task); +typedef void (^AFURLSessionTaskDidSendBodyDataBlock)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend); +typedef void (^AFURLSessionTaskDidCompleteBlock)(NSURLSession *session, NSURLSessionTask *task, NSError *error); + +typedef NSURLSessionResponseDisposition (^AFURLSessionDataTaskDidReceiveResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response); +typedef void (^AFURLSessionDataTaskDidBecomeDownloadTaskBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask); +typedef void (^AFURLSessionDataTaskDidReceiveDataBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data); +typedef NSCachedURLResponse * (^AFURLSessionDataTaskWillCacheResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse); + +typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location); +typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite); +typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes); +typedef void (^AFURLSessionTaskProgressBlock)(NSProgress *); + +typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error); + + +#pragma mark - + +@interface AFURLSessionManagerTaskDelegate : NSObject +- (instancetype)initWithTask:(NSURLSessionTask *)task; +@property (nonatomic, weak) AFURLSessionManager *manager; +@property (nonatomic, strong) NSMutableData *mutableData; +@property (nonatomic, strong) NSProgress *uploadProgress; +@property (nonatomic, strong) NSProgress *downloadProgress; +@property (nonatomic, copy) NSURL *downloadFileURL; +@property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; +@property (nonatomic, copy) AFURLSessionTaskProgressBlock uploadProgressBlock; +@property (nonatomic, copy) AFURLSessionTaskProgressBlock downloadProgressBlock; +@property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler; +@end + +@implementation AFURLSessionManagerTaskDelegate + +- (instancetype)initWithTask:(NSURLSessionTask *)task { + self = [super init]; + if (!self) { + return nil; + } + + _mutableData = [NSMutableData data]; + _uploadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; + _downloadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; + + __weak __typeof__(task) weakTask = task; + for (NSProgress *progress in @[ _uploadProgress, _downloadProgress ]) + { + progress.totalUnitCount = NSURLSessionTransferSizeUnknown; + progress.cancellable = YES; + progress.cancellationHandler = ^{ + [weakTask cancel]; + }; + progress.pausable = YES; + progress.pausingHandler = ^{ + [weakTask suspend]; + }; +#if AF_CAN_USE_AT_AVAILABLE + if (@available(iOS 9, macOS 10.11, *)) +#else + if ([progress respondsToSelector:@selector(setResumingHandler:)]) +#endif + { + progress.resumingHandler = ^{ + [weakTask resume]; + }; + } + + [progress addObserver:self + forKeyPath:NSStringFromSelector(@selector(fractionCompleted)) + options:NSKeyValueObservingOptionNew + context:NULL]; + } + return self; +} + +- (void)dealloc { + [self.downloadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))]; + [self.uploadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))]; +} + +#pragma mark - NSProgress Tracking + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + if ([object isEqual:self.downloadProgress]) { + if (self.downloadProgressBlock) { + self.downloadProgressBlock(object); + } + } + else if ([object isEqual:self.uploadProgress]) { + if (self.uploadProgressBlock) { + self.uploadProgressBlock(object); + } + } +} + +#pragma mark - NSURLSessionTaskDelegate + +- (void)URLSession:(__unused NSURLSession *)session + task:(NSURLSessionTask *)task +didCompleteWithError:(NSError *)error +{ + __strong AFURLSessionManager *manager = self.manager; + + __block id responseObject = nil; + + __block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer; + + //Performance Improvement from #2672 + NSData *data = nil; + if (self.mutableData) { + data = [self.mutableData copy]; + //We no longer need the reference, so nil it out to gain back some memory. + self.mutableData = nil; + } + + if (self.downloadFileURL) { + userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL; + } else if (data) { + userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data; + } + + if (error) { + userInfo[AFNetworkingTaskDidCompleteErrorKey] = error; + + dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{ + if (self.completionHandler) { + self.completionHandler(task.response, responseObject, error); + } + + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; + }); + }); + } else { + dispatch_async(url_session_manager_processing_queue(), ^{ + NSError *serializationError = nil; + responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError]; + + if (self.downloadFileURL) { + responseObject = self.downloadFileURL; + } + + if (responseObject) { + userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject; + } + + if (serializationError) { + userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError; + } + + dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{ + if (self.completionHandler) { + self.completionHandler(task.response, responseObject, serializationError); + } + + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; + }); + }); + }); + } +} + +#pragma mark - NSURLSessionDataDelegate + +- (void)URLSession:(__unused NSURLSession *)session + dataTask:(__unused NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data +{ + self.downloadProgress.totalUnitCount = dataTask.countOfBytesExpectedToReceive; + self.downloadProgress.completedUnitCount = dataTask.countOfBytesReceived; + + [self.mutableData appendData:data]; +} + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task + didSendBodyData:(int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent +totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{ + + self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend; + self.uploadProgress.completedUnitCount = task.countOfBytesSent; +} + +#pragma mark - NSURLSessionDownloadDelegate + +- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask + didWriteData:(int64_t)bytesWritten + totalBytesWritten:(int64_t)totalBytesWritten +totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{ + + self.downloadProgress.totalUnitCount = totalBytesExpectedToWrite; + self.downloadProgress.completedUnitCount = totalBytesWritten; +} + +- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask + didResumeAtOffset:(int64_t)fileOffset +expectedTotalBytes:(int64_t)expectedTotalBytes{ + + self.downloadProgress.totalUnitCount = expectedTotalBytes; + self.downloadProgress.completedUnitCount = fileOffset; +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask +didFinishDownloadingToURL:(NSURL *)location +{ + self.downloadFileURL = nil; + + if (self.downloadTaskDidFinishDownloading) { + self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); + if (self.downloadFileURL) { + NSError *fileManagerError = nil; + + if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError]) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo]; + } + } + } +} + +@end + +#pragma mark - + +/** + * A workaround for issues related to key-value observing the `state` of an `NSURLSessionTask`. + * + * See: + * - https://github.com/AFNetworking/AFNetworking/issues/1477 + * - https://github.com/AFNetworking/AFNetworking/issues/2638 + * - https://github.com/AFNetworking/AFNetworking/pull/2702 + */ + +static inline void af_swizzleSelector(Class theClass, SEL originalSelector, SEL swizzledSelector) { + Method originalMethod = class_getInstanceMethod(theClass, originalSelector); + Method swizzledMethod = class_getInstanceMethod(theClass, swizzledSelector); + method_exchangeImplementations(originalMethod, swizzledMethod); +} + +static inline BOOL af_addMethod(Class theClass, SEL selector, Method method) { + return class_addMethod(theClass, selector, method_getImplementation(method), method_getTypeEncoding(method)); +} + +static NSString * const AFNSURLSessionTaskDidResumeNotification = @"com.alamofire.networking.nsurlsessiontask.resume"; +static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofire.networking.nsurlsessiontask.suspend"; + +@interface _AFURLSessionTaskSwizzling : NSObject + +@end + +@implementation _AFURLSessionTaskSwizzling + ++ (void)load { + /** + WARNING: Trouble Ahead + https://github.com/AFNetworking/AFNetworking/pull/2702 + */ + + if (NSClassFromString(@"NSURLSessionTask")) { + /** + iOS 7 and iOS 8 differ in NSURLSessionTask implementation, which makes the next bit of code a bit tricky. + Many Unit Tests have been built to validate as much of this behavior has possible. + Here is what we know: + - NSURLSessionTasks are implemented with class clusters, meaning the class you request from the API isn't actually the type of class you will get back. + - Simply referencing `[NSURLSessionTask class]` will not work. You need to ask an `NSURLSession` to actually create an object, and grab the class from there. + - On iOS 7, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `__NSCFURLSessionTask`. + - On iOS 8, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `NSURLSessionTask`. + - On iOS 7, `__NSCFLocalSessionTask` and `__NSCFURLSessionTask` are the only two classes that have their own implementations of `resume` and `suspend`, and `__NSCFLocalSessionTask` DOES NOT CALL SUPER. This means both classes need to be swizzled. + - On iOS 8, `NSURLSessionTask` is the only class that implements `resume` and `suspend`. This means this is the only class that needs to be swizzled. + - Because `NSURLSessionTask` is not involved in the class hierarchy for every version of iOS, its easier to add the swizzled methods to a dummy class and manage them there. + + Some Assumptions: + - No implementations of `resume` or `suspend` call super. If this were to change in a future version of iOS, we'd need to handle it. + - No background task classes override `resume` or `suspend` + + The current solution: + 1) Grab an instance of `__NSCFLocalDataTask` by asking an instance of `NSURLSession` for a data task. + 2) Grab a pointer to the original implementation of `af_resume` + 3) Check to see if the current class has an implementation of resume. If so, continue to step 4. + 4) Grab the super class of the current class. + 5) Grab a pointer for the current class to the current implementation of `resume`. + 6) Grab a pointer for the super class to the current implementation of `resume`. + 7) If the current class implementation of `resume` is not equal to the super class implementation of `resume` AND the current implementation of `resume` is not equal to the original implementation of `af_resume`, THEN swizzle the methods + 8) Set the current class to the super class, and repeat steps 3-8 + */ + NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration]; + NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration]; +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnonnull" + NSURLSessionDataTask *localDataTask = [session dataTaskWithURL:nil]; +#pragma clang diagnostic pop + IMP originalAFResumeIMP = method_getImplementation(class_getInstanceMethod([self class], @selector(af_resume))); + Class currentClass = [localDataTask class]; + + while (class_getInstanceMethod(currentClass, @selector(resume))) { + Class superClass = [currentClass superclass]; + IMP classResumeIMP = method_getImplementation(class_getInstanceMethod(currentClass, @selector(resume))); + IMP superclassResumeIMP = method_getImplementation(class_getInstanceMethod(superClass, @selector(resume))); + if (classResumeIMP != superclassResumeIMP && + originalAFResumeIMP != classResumeIMP) { + [self swizzleResumeAndSuspendMethodForClass:currentClass]; + } + currentClass = [currentClass superclass]; + } + + [localDataTask cancel]; + [session finishTasksAndInvalidate]; + } +} + ++ (void)swizzleResumeAndSuspendMethodForClass:(Class)theClass { + Method afResumeMethod = class_getInstanceMethod(self, @selector(af_resume)); + Method afSuspendMethod = class_getInstanceMethod(self, @selector(af_suspend)); + + if (af_addMethod(theClass, @selector(af_resume), afResumeMethod)) { + af_swizzleSelector(theClass, @selector(resume), @selector(af_resume)); + } + + if (af_addMethod(theClass, @selector(af_suspend), afSuspendMethod)) { + af_swizzleSelector(theClass, @selector(suspend), @selector(af_suspend)); + } +} + +- (NSURLSessionTaskState)state { + NSAssert(NO, @"State method should never be called in the actual dummy class"); + return NSURLSessionTaskStateCanceling; +} + +- (void)af_resume { + NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state"); + NSURLSessionTaskState state = [self state]; + [self af_resume]; + + if (state != NSURLSessionTaskStateRunning) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidResumeNotification object:self]; + } +} + +- (void)af_suspend { + NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state"); + NSURLSessionTaskState state = [self state]; + [self af_suspend]; + + if (state != NSURLSessionTaskStateSuspended) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidSuspendNotification object:self]; + } +} +@end + +#pragma mark - + +@interface AFURLSessionManager () +@property (readwrite, nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration; +@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue; +@property (readwrite, nonatomic, strong) NSURLSession *session; +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier; +@property (readonly, nonatomic, copy) NSString *taskDescriptionForSessionTasks; +@property (readwrite, nonatomic, strong) NSLock *lock; +@property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid; +@property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge; +@property (readwrite, nonatomic, copy) AFURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession AF_API_UNAVAILABLE(macos); +@property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection; +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidReceiveAuthenticationChallengeBlock taskDidReceiveAuthenticationChallenge; +@property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream; +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidSendBodyDataBlock taskDidSendBodyData; +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidCompleteBlock taskDidComplete; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveResponseBlock dataTaskDidReceiveResponse; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidBecomeDownloadTaskBlock dataTaskDidBecomeDownloadTask; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveDataBlock dataTaskDidReceiveData; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskWillCacheResponseBlock dataTaskWillCacheResponse; +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidWriteDataBlock downloadTaskDidWriteData; +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidResumeBlock downloadTaskDidResume; +@end + +@implementation AFURLSessionManager + +- (instancetype)init { + return [self initWithSessionConfiguration:nil]; +} + +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { + self = [super init]; + if (!self) { + return nil; + } + + if (!configuration) { + configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; + } + + self.sessionConfiguration = configuration; + + self.operationQueue = [[NSOperationQueue alloc] init]; + self.operationQueue.maxConcurrentOperationCount = 1; + + self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue]; + + self.responseSerializer = [AFJSONResponseSerializer serializer]; + + self.securityPolicy = [AFSecurityPolicy defaultPolicy]; + +#if !TARGET_OS_WATCH + self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; +#endif + + self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init]; + + self.lock = [[NSLock alloc] init]; + self.lock.name = AFURLSessionManagerLockName; + + [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { + for (NSURLSessionDataTask *task in dataTasks) { + [self addDelegateForDataTask:task uploadProgress:nil downloadProgress:nil completionHandler:nil]; + } + + for (NSURLSessionUploadTask *uploadTask in uploadTasks) { + [self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil]; + } + + for (NSURLSessionDownloadTask *downloadTask in downloadTasks) { + [self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil]; + } + }]; + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +#pragma mark - + +- (NSString *)taskDescriptionForSessionTasks { + return [NSString stringWithFormat:@"%p", self]; +} + +- (void)taskDidResume:(NSNotification *)notification { + NSURLSessionTask *task = notification.object; + if ([task respondsToSelector:@selector(taskDescription)]) { + if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidResumeNotification object:task]; + }); + } + } +} + +- (void)taskDidSuspend:(NSNotification *)notification { + NSURLSessionTask *task = notification.object; + if ([task respondsToSelector:@selector(taskDescription)]) { + if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidSuspendNotification object:task]; + }); + } + } +} + +#pragma mark - + +- (AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task { + NSParameterAssert(task); + + AFURLSessionManagerTaskDelegate *delegate = nil; + [self.lock lock]; + delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)]; + [self.lock unlock]; + + return delegate; +} + +- (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate + forTask:(NSURLSessionTask *)task +{ + NSParameterAssert(task); + NSParameterAssert(delegate); + + [self.lock lock]; + self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate; + [self addNotificationObserverForTask:task]; + [self.lock unlock]; +} + +- (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:dataTask]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + dataTask.taskDescription = self.taskDescriptionForSessionTasks; + [self setDelegate:delegate forTask:dataTask]; + + delegate.uploadProgressBlock = uploadProgressBlock; + delegate.downloadProgressBlock = downloadProgressBlock; +} + +- (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:uploadTask]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + uploadTask.taskDescription = self.taskDescriptionForSessionTasks; + + [self setDelegate:delegate forTask:uploadTask]; + + delegate.uploadProgressBlock = uploadProgressBlock; +} + +- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:downloadTask]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + if (destination) { + delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session, NSURLSessionDownloadTask *task, NSURL *location) { + return destination(location, task.response); + }; + } + + downloadTask.taskDescription = self.taskDescriptionForSessionTasks; + + [self setDelegate:delegate forTask:downloadTask]; + + delegate.downloadProgressBlock = downloadProgressBlock; +} + +- (void)removeDelegateForTask:(NSURLSessionTask *)task { + NSParameterAssert(task); + + [self.lock lock]; + [self removeNotificationObserverForTask:task]; + [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)]; + [self.lock unlock]; +} + +#pragma mark - + +- (NSArray *)tasksForKeyPath:(NSString *)keyPath { + __block NSArray *tasks = nil; + dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); + [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) { + tasks = dataTasks; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) { + tasks = uploadTasks; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) { + tasks = downloadTasks; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) { + tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"]; + } + + dispatch_semaphore_signal(semaphore); + }]; + + dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); + + return tasks; +} + +- (NSArray *)tasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +- (NSArray *)dataTasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +- (NSArray *)uploadTasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +- (NSArray *)downloadTasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +#pragma mark - + +- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks { + if (cancelPendingTasks) { + [self.session invalidateAndCancel]; + } else { + [self.session finishTasksAndInvalidate]; + } +} + +#pragma mark - + +- (void)setResponseSerializer:(id )responseSerializer { + NSParameterAssert(responseSerializer); + + _responseSerializer = responseSerializer; +} + +#pragma mark - +- (void)addNotificationObserverForTask:(NSURLSessionTask *)task { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:task]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:task]; +} + +- (void)removeNotificationObserverForTask:(NSURLSessionTask *)task { + [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidSuspendNotification object:task]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidResumeNotification object:task]; +} + +#pragma mark - + +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + return [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:completionHandler]; +} + +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler { + + __block NSURLSessionDataTask *dataTask = nil; + url_session_manager_create_task_safely(^{ + dataTask = [self.session dataTaskWithRequest:request]; + }); + + [self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler]; + + return dataTask; +} + +#pragma mark - + +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromFile:(NSURL *)fileURL + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + __block NSURLSessionUploadTask *uploadTask = nil; + url_session_manager_create_task_safely(^{ + uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; + + // uploadTask may be nil on iOS7 because uploadTaskWithRequest:fromFile: may return nil despite being documented as nonnull (https://devforums.apple.com/message/926113#926113) + if (!uploadTask && self.attemptsToRecreateUploadTasksForBackgroundSessions && self.session.configuration.identifier) { + for (NSUInteger attempts = 0; !uploadTask && attempts < AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask; attempts++) { + uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; + } + } + }); + + if (uploadTask) { + [self addDelegateForUploadTask:uploadTask + progress:uploadProgressBlock + completionHandler:completionHandler]; + } + + return uploadTask; +} + +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromData:(NSData *)bodyData + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + __block NSURLSessionUploadTask *uploadTask = nil; + url_session_manager_create_task_safely(^{ + uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData]; + }); + + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; + + return uploadTask; +} + +- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + __block NSURLSessionUploadTask *uploadTask = nil; + url_session_manager_create_task_safely(^{ + uploadTask = [self.session uploadTaskWithStreamedRequest:request]; + }); + + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; + + return uploadTask; +} + +#pragma mark - + +- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + __block NSURLSessionDownloadTask *downloadTask = nil; + url_session_manager_create_task_safely(^{ + downloadTask = [self.session downloadTaskWithRequest:request]; + }); + + [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler]; + + return downloadTask; +} + +- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + __block NSURLSessionDownloadTask *downloadTask = nil; + url_session_manager_create_task_safely(^{ + downloadTask = [self.session downloadTaskWithResumeData:resumeData]; + }); + + [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler]; + + return downloadTask; +} + +#pragma mark - +- (NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task { + return [[self delegateForTask:task] uploadProgress]; +} + +- (NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task { + return [[self delegateForTask:task] downloadProgress]; +} + +#pragma mark - + +- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block { + self.sessionDidBecomeInvalid = block; +} + +- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block { + self.sessionDidReceiveAuthenticationChallenge = block; +} + +#if !TARGET_OS_OSX +- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block { + self.didFinishEventsForBackgroundURLSession = block; +} +#endif + +#pragma mark - + +- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block { + self.taskNeedNewBodyStream = block; +} + +- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block { + self.taskWillPerformHTTPRedirection = block; +} + +- (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block { + self.taskDidReceiveAuthenticationChallenge = block; +} + +- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block { + self.taskDidSendBodyData = block; +} + +- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block { + self.taskDidComplete = block; +} + +#pragma mark - + +- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block { + self.dataTaskDidReceiveResponse = block; +} + +- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block { + self.dataTaskDidBecomeDownloadTask = block; +} + +- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block { + self.dataTaskDidReceiveData = block; +} + +- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block { + self.dataTaskWillCacheResponse = block; +} + +#pragma mark - + +- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block { + self.downloadTaskDidFinishDownloading = block; +} + +- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block { + self.downloadTaskDidWriteData = block; +} + +- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block { + self.downloadTaskDidResume = block; +} + +#pragma mark - NSObject + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, self.session, self.operationQueue]; +} + +- (BOOL)respondsToSelector:(SEL)selector { + if (selector == @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)) { + return self.taskWillPerformHTTPRedirection != nil; + } else if (selector == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) { + return self.dataTaskDidReceiveResponse != nil; + } else if (selector == @selector(URLSession:dataTask:willCacheResponse:completionHandler:)) { + return self.dataTaskWillCacheResponse != nil; + } +#if !TARGET_OS_OSX + else if (selector == @selector(URLSessionDidFinishEventsForBackgroundURLSession:)) { + return self.didFinishEventsForBackgroundURLSession != nil; + } +#endif + + return [[self class] instancesRespondToSelector:selector]; +} + +#pragma mark - NSURLSessionDelegate + +- (void)URLSession:(NSURLSession *)session +didBecomeInvalidWithError:(NSError *)error +{ + if (self.sessionDidBecomeInvalid) { + self.sessionDidBecomeInvalid(session, error); + } + + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session]; +} + +- (void)URLSession:(NSURLSession *)session +didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler +{ + NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; + __block NSURLCredential *credential = nil; + + if (self.sessionDidReceiveAuthenticationChallenge) { + disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential); + } else { + if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { + if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { + credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; + if (credential) { + disposition = NSURLSessionAuthChallengeUseCredential; + } else { + disposition = NSURLSessionAuthChallengePerformDefaultHandling; + } + } else { + disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; + } + } else { + disposition = NSURLSessionAuthChallengePerformDefaultHandling; + } + } + + if (completionHandler) { + completionHandler(disposition, credential); + } +} + +#pragma mark - NSURLSessionTaskDelegate + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +willPerformHTTPRedirection:(NSHTTPURLResponse *)response + newRequest:(NSURLRequest *)request + completionHandler:(void (^)(NSURLRequest *))completionHandler +{ + NSURLRequest *redirectRequest = request; + + if (self.taskWillPerformHTTPRedirection) { + redirectRequest = self.taskWillPerformHTTPRedirection(session, task, response, request); + } + + if (completionHandler) { + completionHandler(redirectRequest); + } +} + +- (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 (self.taskDidReceiveAuthenticationChallenge) { + disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential); + } else { + if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { + if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { + disposition = NSURLSessionAuthChallengeUseCredential; + credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; + } else { + disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; + } + } else { + disposition = NSURLSessionAuthChallengePerformDefaultHandling; + } + } + + if (completionHandler) { + completionHandler(disposition, credential); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler +{ + NSInputStream *inputStream = nil; + + if (self.taskNeedNewBodyStream) { + inputStream = self.taskNeedNewBodyStream(session, task); + } else if (task.originalRequest.HTTPBodyStream && [task.originalRequest.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) { + inputStream = [task.originalRequest.HTTPBodyStream copy]; + } + + if (completionHandler) { + completionHandler(inputStream); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + didSendBodyData:(int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent +totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend +{ + + int64_t totalUnitCount = totalBytesExpectedToSend; + if(totalUnitCount == NSURLSessionTransferSizeUnknown) { + NSString *contentLength = [task.originalRequest valueForHTTPHeaderField:@"Content-Length"]; + if(contentLength) { + totalUnitCount = (int64_t) [contentLength longLongValue]; + } + } + + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; + + if (delegate) { + [delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalBytesExpectedToSend]; + } + + if (self.taskDidSendBodyData) { + self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalUnitCount); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didCompleteWithError:(NSError *)error +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; + + // delegate may be nil when completing a task in the background + if (delegate) { + [delegate URLSession:session task:task didCompleteWithError:error]; + + [self removeDelegateForTask:task]; + } + + if (self.taskDidComplete) { + self.taskDidComplete(session, task, error); + } +} + +#pragma mark - NSURLSessionDataDelegate + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didReceiveResponse:(NSURLResponse *)response + completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler +{ + NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow; + + if (self.dataTaskDidReceiveResponse) { + disposition = self.dataTaskDidReceiveResponse(session, dataTask, response); + } + + if (completionHandler) { + completionHandler(disposition); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; + if (delegate) { + [self removeDelegateForTask:dataTask]; + [self setDelegate:delegate forTask:downloadTask]; + } + + if (self.dataTaskDidBecomeDownloadTask) { + self.dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data +{ + + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; + [delegate URLSession:session dataTask:dataTask didReceiveData:data]; + + if (self.dataTaskDidReceiveData) { + self.dataTaskDidReceiveData(session, dataTask, data); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + willCacheResponse:(NSCachedURLResponse *)proposedResponse + completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler +{ + NSCachedURLResponse *cachedResponse = proposedResponse; + + if (self.dataTaskWillCacheResponse) { + cachedResponse = self.dataTaskWillCacheResponse(session, dataTask, proposedResponse); + } + + if (completionHandler) { + completionHandler(cachedResponse); + } +} + +#if !TARGET_OS_OSX +- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session { + if (self.didFinishEventsForBackgroundURLSession) { + dispatch_async(dispatch_get_main_queue(), ^{ + self.didFinishEventsForBackgroundURLSession(session); + }); + } +} +#endif + +#pragma mark - NSURLSessionDownloadDelegate + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask +didFinishDownloadingToURL:(NSURL *)location +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; + if (self.downloadTaskDidFinishDownloading) { + NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); + if (fileURL) { + delegate.downloadFileURL = fileURL; + NSError *error = nil; + + if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error]) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo]; + } + + return; + } + } + + if (delegate) { + [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location]; + } +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didWriteData:(int64_t)bytesWritten + totalBytesWritten:(int64_t)totalBytesWritten +totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite +{ + + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; + + if (delegate) { + [delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite]; + } + + if (self.downloadTaskDidWriteData) { + self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); + } +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didResumeAtOffset:(int64_t)fileOffset +expectedTotalBytes:(int64_t)expectedTotalBytes +{ + + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; + + if (delegate) { + [delegate URLSession:session downloadTask:downloadTask didResumeAtOffset:fileOffset expectedTotalBytes:expectedTotalBytes]; + } + + if (self.downloadTaskDidResume) { + self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes); + } +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; + + self = [self initWithSessionConfiguration:configuration]; + if (!self) { + return nil; + } + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration]; +} + +@end diff --git a/Pods/AFNetworking/LICENSE b/Pods/AFNetworking/LICENSE new file mode 100644 index 0000000..d707626 --- /dev/null +++ b/Pods/AFNetworking/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011-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. diff --git a/Pods/AFNetworking/README.md b/Pods/AFNetworking/README.md new file mode 100644 index 0000000..6a7d2cd --- /dev/null +++ b/Pods/AFNetworking/README.md @@ -0,0 +1,322 @@ +

+ AFNetworking +

+ +[![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.svg)](https://travis-ci.org/AFNetworking/AFNetworking) +[![codecov.io](https://codecov.io/github/AFNetworking/AFNetworking/coverage.svg?branch=master)](https://codecov.io/github/AFNetworking/AFNetworking?branch=master) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/AFNetworking.svg)](https://img.shields.io/cocoapods/v/AFNetworking.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/AFNetworking.svg?style=flat)](http://cocoadocs.org/docsets/AFNetworking) +[![Twitter](https://img.shields.io/badge/twitter-@AFNetworking-blue.svg?style=flat)](http://twitter.com/AFNetworking) + +AFNetworking is a delightful networking library for iOS, macOS, watchOS, and tvOS. It's built on top of the [Foundation URL Loading System](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html), extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. + +Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac. + +Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did! + +## How To Get Started + +- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/archive/master.zip) and try out the included Mac and iPhone example apps +- Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles on the Wiki](https://github.com/AFNetworking/AFNetworking/wiki) +- Check out the [documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at all of the APIs available in AFNetworking +- Read the [AFNetworking 3.0 Migration Guide](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-3.0-Migration-Guide) for an overview of the architectural changes from 2.0. + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). (Tag 'afnetworking') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). +- If you **found a bug**, _and can provide steps to reliably reproduce it_, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + +## Installation +AFNetworking supports multiple methods for installing the library in a 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 like AFNetworking in your projects. See the ["Getting Started" guide for more information](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking). You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 0.39.0+ is required to build AFNetworking 3.0.0+. + +#### Podfile + +To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '8.0' + +target 'TargetName' do +pod 'AFNetworking', '~> 3.0' +end +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Installation with Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](http://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate AFNetworking into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "AFNetworking/AFNetworking" ~> 3.0 +``` + +Run `carthage` to build the framework and drag the built `AFNetworking.framework` into your Xcode project. + +## Requirements + +| AFNetworking Version | Minimum iOS Target | Minimum macOS Target | Minimum watchOS Target | Minimum tvOS Target | Notes | +|:--------------------:|:---------------------------:|:----------------------------:|:----------------------------:|:----------------------------:|:-------------------------------------------------------------------------:| +| 3.x | iOS 7 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Xcode 7+ is required. `NSURLConnectionOperation` support has been removed. | +| 2.6 -> 2.6.3 | iOS 7 | OS X 10.9 | watchOS 2.0 | n/a | Xcode 7+ is required. | +| 2.0 -> 2.5.4 | iOS 6 | OS X 10.8 | n/a | n/a | Xcode 5+ is required. `NSURLSession` subspec requires iOS 7 or OS X 10.9. | +| 1.x | iOS 5 | Mac OS X 10.7 | n/a | n/a | +| 0.10.x | iOS 4 | Mac OS X 10.6 | n/a | n/a | + +(macOS projects must support [64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)). + +> Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs. + +## Architecture + +### NSURLSession + +- `AFURLSessionManager` +- `AFHTTPSessionManager` + +### Serialization + +* `` + - `AFHTTPRequestSerializer` + - `AFJSONRequestSerializer` + - `AFPropertyListRequestSerializer` +* `` + - `AFHTTPResponseSerializer` + - `AFJSONResponseSerializer` + - `AFXMLParserResponseSerializer` + - `AFXMLDocumentResponseSerializer` _(macOS)_ + - `AFPropertyListResponseSerializer` + - `AFImageResponseSerializer` + - `AFCompoundResponseSerializer` + +### Additional Functionality + +- `AFSecurityPolicy` +- `AFNetworkReachabilityManager` + +## Usage + +### AFURLSessionManager + +`AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. + +#### Creating a Download Task + +```objective-c +NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + +NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"]; +NSURLRequest *request = [NSURLRequest requestWithURL:URL]; + +NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { + NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; + return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; +} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { + NSLog(@"File downloaded to: %@", filePath); +}]; +[downloadTask resume]; +``` + +#### Creating an Upload Task + +```objective-c +NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + +NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"]; +NSURLRequest *request = [NSURLRequest requestWithURL:URL]; + +NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"]; +NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + if (error) { + NSLog(@"Error: %@", error); + } else { + NSLog(@"Success: %@ %@", response, responseObject); + } +}]; +[uploadTask resume]; +``` + +#### Creating an Upload Task for a Multi-Part Request, with Progress + +```objective-c +NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) { + [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil]; + } error:nil]; + +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + +NSURLSessionUploadTask *uploadTask; +uploadTask = [manager + uploadTaskWithStreamedRequest:request + progress:^(NSProgress * _Nonnull uploadProgress) { + // This is not called back on the main queue. + // You are responsible for dispatching to the main queue for UI updates + dispatch_async(dispatch_get_main_queue(), ^{ + //Update the progress view + [progressView setProgress:uploadProgress.fractionCompleted]; + }); + } + completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + if (error) { + NSLog(@"Error: %@", error); + } else { + NSLog(@"%@ %@", response, responseObject); + } + }]; + +[uploadTask resume]; +``` + +#### Creating a Data Task + +```objective-c +NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + +NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"]; +NSURLRequest *request = [NSURLRequest requestWithURL:URL]; + +NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + if (error) { + NSLog(@"Error: %@", error); + } else { + NSLog(@"%@ %@", response, responseObject); + } +}]; +[dataTask resume]; +``` + +--- + +### Request Serialization + +Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body. + +```objective-c +NSString *URLString = @"http://example.com"; +NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]}; +``` + +#### Query String Parameter Encoding + +```objective-c +[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil]; +``` + + GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3 + +#### URL Form Parameter Encoding + +```objective-c +[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; +``` + + POST http://example.com/ + Content-Type: application/x-www-form-urlencoded + + foo=bar&baz[]=1&baz[]=2&baz[]=3 + +#### JSON Parameter Encoding + +```objective-c +[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; +``` + + POST http://example.com/ + Content-Type: application/json + + {"foo": "bar", "baz": [1,2,3]} + +--- + +### Network Reachability Manager + +`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. + +* Do not use Reachability to determine if the original request should be sent. + * You should try to send it. +* You can use Reachability to determine when a request should be automatically retried. + * Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something. +* Network reachability is a useful tool for determining why a request might have failed. + * After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out." + +See also [WWDC 2012 session 706, "Networking Best Practices."](https://developer.apple.com/videos/play/wwdc2012-706/). + +#### Shared Network Reachability + +```objective-c +[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status)); +}]; + +[[AFNetworkReachabilityManager sharedManager] startMonitoring]; +``` + +--- + +### Security Policy + +`AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. + +Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled. + +#### Allowing Invalid SSL Certificates + +```objective-c +AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; +manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production +``` + +--- + +## Unit Tests + +AFNetworking includes a suite of unit tests within the Tests subdirectory. These tests can be run simply be executed the test action on the platform framework you would like to test. + +## Credits + +AFNetworking is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). + +AFNetworking was originally created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla). + +AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/). + +And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors). + +### Security Disclosure + +If you believe you have identified a security vulnerability with AFNetworking, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## License + +AFNetworking is released under the MIT license. See [LICENSE](https://github.com/AFNetworking/AFNetworking/blob/master/LICENSE) for details. diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h b/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h new file mode 100644 index 0000000..1a27bb4 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h @@ -0,0 +1,160 @@ +// AFAutoPurgingImageCache.h +// Copyright (c) 2011–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 +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + The `AFImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously. + */ +@protocol AFImageCache + +/** + Adds the image to the cache with the given identifier. + + @param image The image to cache. + @param identifier The unique identifier for the image in the cache. + */ +- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier; + +/** + Removes the image from the cache matching the given identifier. + + @param identifier The unique identifier for the image in the cache. + + @return A BOOL indicating whether or not the image was removed from the cache. + */ +- (BOOL)removeImageWithIdentifier:(NSString *)identifier; + +/** + Removes all images from the cache. + + @return A BOOL indicating whether or not all images were removed from the cache. + */ +- (BOOL)removeAllImages; + +/** + Returns the image in the cache associated with the given identifier. + + @param identifier The unique identifier for the image in the cache. + + @return An image for the matching identifier, or nil. + */ +- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier; +@end + + +/** + The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and fetching images from a cache given an `NSURLRequest` and additional identifier. + */ +@protocol AFImageRequestCache + +/** + Asks if the image should be cached using an identifier created from the request and additional identifier. + + @param image The image to be cached. + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + + @return A BOOL indicating whether or not the image should be added to the cache. YES will cache, NO will prevent caching. + */ +- (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +/** + Adds the image to the cache using an identifier created from the request and additional identifier. + + @param image The image to cache. + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + */ +- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +/** + Removes the image from the cache using an identifier created from the request and additional identifier. + + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + + @return A BOOL indicating whether or not all images were removed from the cache. + */ +- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +/** + Returns the image from the cache associated with an identifier created from the request and additional identifier. + + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + + @return An image for the matching request and identifier, or nil. + */ +- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +@end + +/** + The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated. + */ +@interface AFAutoPurgingImageCache : NSObject + +/** + The total memory capacity of the cache in bytes. + */ +@property (nonatomic, assign) UInt64 memoryCapacity; + +/** + The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit. + */ +@property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge; + +/** + The current total memory usage in bytes of all images stored within the cache. + */ +@property (nonatomic, assign, readonly) UInt64 memoryUsage; + +/** + Initialies the `AutoPurgingImageCache` instance with default values for memory capacity and preferred memory usage after purge limit. `memoryCapcity` defaults to `100 MB`. `preferredMemoryUsageAfterPurge` defaults to `60 MB`. + + @return The new `AutoPurgingImageCache` instance. + */ +- (instancetype)init; + +/** + Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage + after purge limit. + + @param memoryCapacity The total memory capacity of the cache in bytes. + @param preferredMemoryCapacity The preferred memory usage after purge in bytes. + + @return The new `AutoPurgingImageCache` instance. + */ +- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity; + +@end + +NS_ASSUME_NONNULL_END + +#endif + diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m b/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m new file mode 100644 index 0000000..374eeac --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m @@ -0,0 +1,205 @@ +// AFAutoPurgingImageCache.m +// Copyright (c) 2011–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 + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFAutoPurgingImageCache.h" + +@interface AFCachedImage : NSObject + +@property (nonatomic, strong) UIImage *image; +@property (nonatomic, strong) NSString *identifier; +@property (nonatomic, assign) UInt64 totalBytes; +@property (nonatomic, strong) NSDate *lastAccessDate; +@property (nonatomic, assign) UInt64 currentMemoryUsage; + +@end + +@implementation AFCachedImage + +-(instancetype)initWithImage:(UIImage *)image identifier:(NSString *)identifier { + if (self = [self init]) { + self.image = image; + self.identifier = identifier; + + CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale); + CGFloat bytesPerPixel = 4.0; + CGFloat bytesPerSize = imageSize.width * imageSize.height; + self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerSize; + self.lastAccessDate = [NSDate date]; + } + return self; +} + +- (UIImage*)accessImage { + self.lastAccessDate = [NSDate date]; + return self.image; +} + +- (NSString *)description { + NSString *descriptionString = [NSString stringWithFormat:@"Idenfitier: %@ lastAccessDate: %@ ", self.identifier, self.lastAccessDate]; + return descriptionString; + +} + +@end + +@interface AFAutoPurgingImageCache () +@property (nonatomic, strong) NSMutableDictionary *cachedImages; +@property (nonatomic, assign) UInt64 currentMemoryUsage; +@property (nonatomic, strong) dispatch_queue_t synchronizationQueue; +@end + +@implementation AFAutoPurgingImageCache + +- (instancetype)init { + return [self initWithMemoryCapacity:100 * 1024 * 1024 preferredMemoryCapacity:60 * 1024 * 1024]; +} + +- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity { + if (self = [super init]) { + self.memoryCapacity = memoryCapacity; + self.preferredMemoryUsageAfterPurge = preferredMemoryCapacity; + self.cachedImages = [[NSMutableDictionary alloc] init]; + + NSString *queueName = [NSString stringWithFormat:@"com.alamofire.autopurgingimagecache-%@", [[NSUUID UUID] UUIDString]]; + self.synchronizationQueue = dispatch_queue_create([queueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT); + + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(removeAllImages) + name:UIApplicationDidReceiveMemoryWarningNotification + object:nil]; + + } + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +- (UInt64)memoryUsage { + __block UInt64 result = 0; + dispatch_sync(self.synchronizationQueue, ^{ + result = self.currentMemoryUsage; + }); + return result; +} + +- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier { + dispatch_barrier_async(self.synchronizationQueue, ^{ + AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier]; + + AFCachedImage *previousCachedImage = self.cachedImages[identifier]; + if (previousCachedImage != nil) { + self.currentMemoryUsage -= previousCachedImage.totalBytes; + } + + self.cachedImages[identifier] = cacheImage; + self.currentMemoryUsage += cacheImage.totalBytes; + }); + + dispatch_barrier_async(self.synchronizationQueue, ^{ + if (self.currentMemoryUsage > self.memoryCapacity) { + UInt64 bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge; + NSMutableArray *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues]; + NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate" + ascending:YES]; + [sortedImages sortUsingDescriptors:@[sortDescriptor]]; + + UInt64 bytesPurged = 0; + + for (AFCachedImage *cachedImage in sortedImages) { + [self.cachedImages removeObjectForKey:cachedImage.identifier]; + bytesPurged += cachedImage.totalBytes; + if (bytesPurged >= bytesToPurge) { + break ; + } + } + self.currentMemoryUsage -= bytesPurged; + } + }); +} + +- (BOOL)removeImageWithIdentifier:(NSString *)identifier { + __block BOOL removed = NO; + dispatch_barrier_sync(self.synchronizationQueue, ^{ + AFCachedImage *cachedImage = self.cachedImages[identifier]; + if (cachedImage != nil) { + [self.cachedImages removeObjectForKey:identifier]; + self.currentMemoryUsage -= cachedImage.totalBytes; + removed = YES; + } + }); + return removed; +} + +- (BOOL)removeAllImages { + __block BOOL removed = NO; + dispatch_barrier_sync(self.synchronizationQueue, ^{ + if (self.cachedImages.count > 0) { + [self.cachedImages removeAllObjects]; + self.currentMemoryUsage = 0; + removed = YES; + } + }); + return removed; +} + +- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier { + __block UIImage *image = nil; + dispatch_sync(self.synchronizationQueue, ^{ + AFCachedImage *cachedImage = self.cachedImages[identifier]; + image = [cachedImage accessImage]; + }); + return image; +} + +- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { + [self addImage:image withIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; +} + +- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { + return [self removeImageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; +} + +- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { + return [self imageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; +} + +- (NSString *)imageCacheKeyFromURLRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)additionalIdentifier { + NSString *key = request.URL.absoluteString; + if (additionalIdentifier != nil) { + key = [key stringByAppendingString:additionalIdentifier]; + } + return key; +} + +- (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier { + return YES; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h b/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h new file mode 100644 index 0000000..7e25e37 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h @@ -0,0 +1,171 @@ +// AFImageDownloader.h +// Copyright (c) 2011–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 + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import +#import "AFAutoPurgingImageCache.h" +#import "AFHTTPSessionManager.h" + +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSInteger, AFImageDownloadPrioritization) { + AFImageDownloadPrioritizationFIFO, + AFImageDownloadPrioritizationLIFO +}; + +/** + The `AFImageDownloadReceipt` is an object vended by the `AFImageDownloader` when starting a data task. It can be used to cancel active tasks running on the `AFImageDownloader` session. As a general rule, image data tasks should be cancelled using the `AFImageDownloadReceipt` instead of calling `cancel` directly on the `task` itself. The `AFImageDownloader` is optimized to handle duplicate task scenarios as well as pending versus active downloads. + */ +@interface AFImageDownloadReceipt : NSObject + +/** + The data task created by the `AFImageDownloader`. +*/ +@property (nonatomic, strong) NSURLSessionDataTask *task; + +/** + The unique identifier for the success and failure blocks when duplicate requests are made. + */ +@property (nonatomic, strong) NSUUID *receiptID; +@end + +/** The `AFImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying `NSURLCache` as well as the in-memory image cache. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation. + */ +@interface AFImageDownloader : NSObject + +/** + The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default. + */ +@property (nonatomic, strong, nullable) id imageCache; + +/** + The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads. + */ +@property (nonatomic, strong) AFHTTPSessionManager *sessionManager; + +/** + Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default. + */ +@property (nonatomic, assign) AFImageDownloadPrioritization downloadPrioritizaton; + +/** + The shared default instance of `AFImageDownloader` initialized with default values. + */ ++ (instancetype)defaultInstance; + +/** + Creates a default `NSURLCache` with common usage parameter values. + + @returns The default `NSURLCache` instance. + */ ++ (NSURLCache *)defaultURLCache; + +/** + The default `NSURLSessionConfiguration` with common usage parameter values. + */ ++ (NSURLSessionConfiguration *)defaultURLSessionConfiguration; + +/** + Default initializer + + @return An instance of `AFImageDownloader` initialized with default values. + */ +- (instancetype)init; + +/** + Initializer with specific `URLSessionConfiguration` + + @param configuration The `NSURLSessionConfiguration` to be be used + + @return An instance of `AFImageDownloader` initialized with default values and custom `NSURLSessionConfiguration` + */ +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration; + +/** + Initializes the `AFImageDownloader` instance with the given session manager, download prioritization, maximum active download count and image cache. + + @param sessionManager The session manager to use to download images. + @param downloadPrioritization The download prioritization of the download queue. + @param maximumActiveDownloads The maximum number of active downloads allowed at any given time. Recommend `4`. + @param imageCache The image cache used to store all downloaded images in. + + @return The new `AFImageDownloader` instance. + */ +- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager + downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization + maximumActiveDownloads:(NSInteger)maximumActiveDownloads + imageCache:(nullable id )imageCache; + +/** + Creates a data task using the `sessionManager` instance for the specified URL request. + + If the same data task is already in the queue or currently being downloaded, the success and failure blocks are + appended to the already existing task. Once the task completes, all success or failure blocks attached to the + task are executed in the order they were added. + + @param request The URL request. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + + @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. + cache and the URL request cache policy allows the cache to be used. + */ +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + +/** + Creates a data task using the `sessionManager` instance for the specified URL request. + + If the same data task is already in the queue or currently being downloaded, the success and failure blocks are + appended to the already existing task. Once the task completes, all success or failure blocks attached to the + task are executed in the order they were added. + + @param request The URL request. + @param receiptID The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + + @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. + cache and the URL request cache policy allows the cache to be used. + */ +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + withReceiptID:(NSUUID *)receiptID + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + +/** + Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary. + + If the data task is pending in the queue, it will be cancelled if no other success and failure blocks are registered with the data task. If the data task is currently executing or is already completed, the success and failure blocks are removed and will not be called when the task finishes. + + @param imageDownloadReceipt The image download receipt to cancel. + */ +- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt; + +@end + +#endif + +NS_ASSUME_NONNULL_END diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m b/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m new file mode 100644 index 0000000..36745b5 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m @@ -0,0 +1,409 @@ +// AFImageDownloader.m +// Copyright (c) 2011–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 + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFImageDownloader.h" +#import "AFHTTPSessionManager.h" + +@interface AFImageDownloaderResponseHandler : NSObject +@property (nonatomic, strong) NSUUID *uuid; +@property (nonatomic, copy) void (^successBlock)(NSURLRequest*, NSHTTPURLResponse*, UIImage*); +@property (nonatomic, copy) void (^failureBlock)(NSURLRequest*, NSHTTPURLResponse*, NSError*); +@end + +@implementation AFImageDownloaderResponseHandler + +- (instancetype)initWithUUID:(NSUUID *)uuid + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure { + if (self = [self init]) { + self.uuid = uuid; + self.successBlock = success; + self.failureBlock = failure; + } + return self; +} + +- (NSString *)description { + return [NSString stringWithFormat: @"UUID: %@", [self.uuid UUIDString]]; +} + +@end + +@interface AFImageDownloaderMergedTask : NSObject +@property (nonatomic, strong) NSString *URLIdentifier; +@property (nonatomic, strong) NSUUID *identifier; +@property (nonatomic, strong) NSURLSessionDataTask *task; +@property (nonatomic, strong) NSMutableArray *responseHandlers; + +@end + +@implementation AFImageDownloaderMergedTask + +- (instancetype)initWithURLIdentifier:(NSString *)URLIdentifier identifier:(NSUUID *)identifier task:(NSURLSessionDataTask *)task { + if (self = [self init]) { + self.URLIdentifier = URLIdentifier; + self.task = task; + self.identifier = identifier; + self.responseHandlers = [[NSMutableArray alloc] init]; + } + return self; +} + +- (void)addResponseHandler:(AFImageDownloaderResponseHandler*)handler { + [self.responseHandlers addObject:handler]; +} + +- (void)removeResponseHandler:(AFImageDownloaderResponseHandler*)handler { + [self.responseHandlers removeObject:handler]; +} + +@end + +@implementation AFImageDownloadReceipt + +- (instancetype)initWithReceiptID:(NSUUID *)receiptID task:(NSURLSessionDataTask *)task { + if (self = [self init]) { + self.receiptID = receiptID; + self.task = task; + } + return self; +} + +@end + +@interface AFImageDownloader () + +@property (nonatomic, strong) dispatch_queue_t synchronizationQueue; +@property (nonatomic, strong) dispatch_queue_t responseQueue; + +@property (nonatomic, assign) NSInteger maximumActiveDownloads; +@property (nonatomic, assign) NSInteger activeRequestCount; + +@property (nonatomic, strong) NSMutableArray *queuedMergedTasks; +@property (nonatomic, strong) NSMutableDictionary *mergedTasks; + +@end + +@implementation AFImageDownloader + ++ (NSURLCache *)defaultURLCache { + + // It's been discovered that a crash will occur on certain versions + // of iOS if you customize the cache. + // + // More info can be found here: https://devforums.apple.com/message/1102182#1102182 + // + // When iOS 7 support is dropped, this should be modified to use + // NSProcessInfo methods instead. + if ([[[UIDevice currentDevice] systemVersion] compare:@"8.2" options:NSNumericSearch] == NSOrderedAscending) { + return [NSURLCache sharedURLCache]; + } + return [[NSURLCache alloc] initWithMemoryCapacity:20 * 1024 * 1024 + diskCapacity:150 * 1024 * 1024 + diskPath:@"com.alamofire.imagedownloader"]; +} + ++ (NSURLSessionConfiguration *)defaultURLSessionConfiguration { + NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; + + //TODO set the default HTTP headers + + configuration.HTTPShouldSetCookies = YES; + configuration.HTTPShouldUsePipelining = NO; + + configuration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy; + configuration.allowsCellularAccess = YES; + configuration.timeoutIntervalForRequest = 60.0; + configuration.URLCache = [AFImageDownloader defaultURLCache]; + + return configuration; +} + +- (instancetype)init { + NSURLSessionConfiguration *defaultConfiguration = [self.class defaultURLSessionConfiguration]; + return [self initWithSessionConfiguration:defaultConfiguration]; +} + +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { + AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration]; + sessionManager.responseSerializer = [AFImageResponseSerializer serializer]; + + return [self initWithSessionManager:sessionManager + downloadPrioritization:AFImageDownloadPrioritizationFIFO + maximumActiveDownloads:4 + imageCache:[[AFAutoPurgingImageCache alloc] init]]; +} + +- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager + downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization + maximumActiveDownloads:(NSInteger)maximumActiveDownloads + imageCache:(id )imageCache { + if (self = [super init]) { + self.sessionManager = sessionManager; + + self.downloadPrioritizaton = downloadPrioritization; + self.maximumActiveDownloads = maximumActiveDownloads; + self.imageCache = imageCache; + + self.queuedMergedTasks = [[NSMutableArray alloc] init]; + self.mergedTasks = [[NSMutableDictionary alloc] init]; + self.activeRequestCount = 0; + + NSString *name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.synchronizationqueue-%@", [[NSUUID UUID] UUIDString]]; + self.synchronizationQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL); + + name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.responsequeue-%@", [[NSUUID UUID] UUIDString]]; + self.responseQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT); + } + + return self; +} + ++ (instancetype)defaultInstance { + static AFImageDownloader *sharedInstance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedInstance = [[self alloc] init]; + }); + return sharedInstance; +} + +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + success:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, UIImage * _Nonnull))success + failure:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, NSError * _Nonnull))failure { + return [self downloadImageForURLRequest:request withReceiptID:[NSUUID UUID] success:success failure:failure]; +} + +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + withReceiptID:(nonnull NSUUID *)receiptID + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure { + __block NSURLSessionDataTask *task = nil; + dispatch_sync(self.synchronizationQueue, ^{ + NSString *URLIdentifier = request.URL.absoluteString; + if (URLIdentifier == nil) { + if (failure) { + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil]; + dispatch_async(dispatch_get_main_queue(), ^{ + failure(request, nil, error); + }); + } + return; + } + + // 1) Append the success and failure blocks to a pre-existing request if it already exists + AFImageDownloaderMergedTask *existingMergedTask = self.mergedTasks[URLIdentifier]; + if (existingMergedTask != nil) { + AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID success:success failure:failure]; + [existingMergedTask addResponseHandler:handler]; + task = existingMergedTask.task; + return; + } + + // 2) Attempt to load the image from the image cache if the cache policy allows it + switch (request.cachePolicy) { + case NSURLRequestUseProtocolCachePolicy: + case NSURLRequestReturnCacheDataElseLoad: + case NSURLRequestReturnCacheDataDontLoad: { + UIImage *cachedImage = [self.imageCache imageforRequest:request withAdditionalIdentifier:nil]; + if (cachedImage != nil) { + if (success) { + dispatch_async(dispatch_get_main_queue(), ^{ + success(request, nil, cachedImage); + }); + } + return; + } + break; + } + default: + break; + } + + // 3) Create the request and set up authentication, validation and response serialization + NSUUID *mergedTaskIdentifier = [NSUUID UUID]; + NSURLSessionDataTask *createdTask; + __weak __typeof__(self) weakSelf = self; + + createdTask = [self.sessionManager + dataTaskWithRequest:request + uploadProgress:nil + downloadProgress:nil + completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + dispatch_async(self.responseQueue, ^{ + __strong __typeof__(weakSelf) strongSelf = weakSelf; + AFImageDownloaderMergedTask *mergedTask = strongSelf.mergedTasks[URLIdentifier]; + if ([mergedTask.identifier isEqual:mergedTaskIdentifier]) { + mergedTask = [strongSelf safelyRemoveMergedTaskWithURLIdentifier:URLIdentifier]; + if (error) { + for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) { + if (handler.failureBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler.failureBlock(request, (NSHTTPURLResponse*)response, error); + }); + } + } + } else { + if ([strongSelf.imageCache shouldCacheImage:responseObject forRequest:request withAdditionalIdentifier:nil]) { + [strongSelf.imageCache addImage:responseObject forRequest:request withAdditionalIdentifier:nil]; + } + + for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) { + if (handler.successBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler.successBlock(request, (NSHTTPURLResponse*)response, responseObject); + }); + } + } + + } + } + [strongSelf safelyDecrementActiveTaskCount]; + [strongSelf safelyStartNextTaskIfNecessary]; + }); + }]; + + // 4) Store the response handler for use when the request completes + AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID + success:success + failure:failure]; + AFImageDownloaderMergedTask *mergedTask = [[AFImageDownloaderMergedTask alloc] + initWithURLIdentifier:URLIdentifier + identifier:mergedTaskIdentifier + task:createdTask]; + [mergedTask addResponseHandler:handler]; + self.mergedTasks[URLIdentifier] = mergedTask; + + // 5) Either start the request or enqueue it depending on the current active request count + if ([self isActiveRequestCountBelowMaximumLimit]) { + [self startMergedTask:mergedTask]; + } else { + [self enqueueMergedTask:mergedTask]; + } + + task = mergedTask.task; + }); + if (task) { + return [[AFImageDownloadReceipt alloc] initWithReceiptID:receiptID task:task]; + } else { + return nil; + } +} + +- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt { + dispatch_sync(self.synchronizationQueue, ^{ + NSString *URLIdentifier = imageDownloadReceipt.task.originalRequest.URL.absoluteString; + AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier]; + NSUInteger index = [mergedTask.responseHandlers indexOfObjectPassingTest:^BOOL(AFImageDownloaderResponseHandler * _Nonnull handler, __unused NSUInteger idx, __unused BOOL * _Nonnull stop) { + return handler.uuid == imageDownloadReceipt.receiptID; + }]; + + if (index != NSNotFound) { + AFImageDownloaderResponseHandler *handler = mergedTask.responseHandlers[index]; + [mergedTask removeResponseHandler:handler]; + NSString *failureReason = [NSString stringWithFormat:@"ImageDownloader cancelled URL request: %@",imageDownloadReceipt.task.originalRequest.URL.absoluteString]; + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey:failureReason}; + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; + if (handler.failureBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler.failureBlock(imageDownloadReceipt.task.originalRequest, nil, error); + }); + } + } + + if (mergedTask.responseHandlers.count == 0 && mergedTask.task.state == NSURLSessionTaskStateSuspended) { + [mergedTask.task cancel]; + [self removeMergedTaskWithURLIdentifier:URLIdentifier]; + } + }); +} + +- (AFImageDownloaderMergedTask*)safelyRemoveMergedTaskWithURLIdentifier:(NSString *)URLIdentifier { + __block AFImageDownloaderMergedTask *mergedTask = nil; + dispatch_sync(self.synchronizationQueue, ^{ + mergedTask = [self removeMergedTaskWithURLIdentifier:URLIdentifier]; + }); + return mergedTask; +} + +//This method should only be called from safely within the synchronizationQueue +- (AFImageDownloaderMergedTask *)removeMergedTaskWithURLIdentifier:(NSString *)URLIdentifier { + AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier]; + [self.mergedTasks removeObjectForKey:URLIdentifier]; + return mergedTask; +} + +- (void)safelyDecrementActiveTaskCount { + dispatch_sync(self.synchronizationQueue, ^{ + if (self.activeRequestCount > 0) { + self.activeRequestCount -= 1; + } + }); +} + +- (void)safelyStartNextTaskIfNecessary { + dispatch_sync(self.synchronizationQueue, ^{ + if ([self isActiveRequestCountBelowMaximumLimit]) { + while (self.queuedMergedTasks.count > 0) { + AFImageDownloaderMergedTask *mergedTask = [self dequeueMergedTask]; + if (mergedTask.task.state == NSURLSessionTaskStateSuspended) { + [self startMergedTask:mergedTask]; + break; + } + } + } + }); +} + +- (void)startMergedTask:(AFImageDownloaderMergedTask *)mergedTask { + [mergedTask.task resume]; + ++self.activeRequestCount; +} + +- (void)enqueueMergedTask:(AFImageDownloaderMergedTask *)mergedTask { + switch (self.downloadPrioritizaton) { + case AFImageDownloadPrioritizationFIFO: + [self.queuedMergedTasks addObject:mergedTask]; + break; + case AFImageDownloadPrioritizationLIFO: + [self.queuedMergedTasks insertObject:mergedTask atIndex:0]; + break; + } +} + +- (AFImageDownloaderMergedTask *)dequeueMergedTask { + AFImageDownloaderMergedTask *mergedTask = nil; + mergedTask = [self.queuedMergedTasks firstObject]; + [self.queuedMergedTasks removeObject:mergedTask]; + return mergedTask; +} + +- (BOOL)isActiveRequestCountBelowMaximumLimit { + return self.activeRequestCount < self.maximumActiveDownloads; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h b/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h new file mode 100644 index 0000000..3bcf289 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h @@ -0,0 +1,103 @@ +// AFNetworkActivityIndicatorManager.h +// Copyright (c) 2011–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 + +#import + +#if TARGET_OS_IOS + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a session task has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero. + + You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code: + + [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; + + By setting `enabled` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself. + + See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information: + http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44 + */ +NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.") +@interface AFNetworkActivityIndicatorManager : NSObject + +/** + A Boolean value indicating whether the manager is enabled. + + If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO. + */ +@property (nonatomic, assign, getter = isEnabled) BOOL enabled; + +/** + A Boolean value indicating whether the network activity indicator manager is currently active. +*/ +@property (readonly, nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; + +/** + A time interval indicating the minimum duration of networking activity that should occur before the activity indicator is displayed. The default value 1 second. If the network activity indicator should be displayed immediately when network activity occurs, this value should be set to 0 seconds. + + Apple's HIG describes the following: + + > Display the network activity indicator to provide feedback when your app accesses the network for more than a couple of seconds. If the operation finishes sooner than that, you don’t have to show the network activity indicator, because the indicator is likely to disappear before users notice its presence. + + */ +@property (nonatomic, assign) NSTimeInterval activationDelay; + +/** + A time interval indicating the duration of time of no networking activity required before the activity indicator is disabled. This allows for continuous display of the network activity indicator across multiple requests. The default value is 0.17 seconds. + */ + +@property (nonatomic, assign) NSTimeInterval completionDelay; + +/** + Returns the shared network activity indicator manager object for the system. + + @return The systemwide network activity indicator manager. + */ ++ (instancetype)sharedManager; + +/** + Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator. + */ +- (void)incrementActivityCount; + +/** + Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator. + */ +- (void)decrementActivityCount; + +/** + Set the a custom method to be executed when the network activity indicator manager should be hidden/shown. By default, this is null, and the UIApplication Network Activity Indicator will be managed automatically. If this block is set, it is the responsiblity of the caller to manager the network activity indicator going forward. + + @param block A block to be executed when the network activity indicator status changes. + */ +- (void)setNetworkingActivityActionWithBlock:(nullable void (^)(BOOL networkActivityIndicatorVisible))block; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m b/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m new file mode 100644 index 0000000..e6f9b65 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m @@ -0,0 +1,259 @@ +// AFNetworkActivityIndicatorManager.m +// Copyright (c) 2011–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 "AFNetworkActivityIndicatorManager.h" + +#if TARGET_OS_IOS +#import "AFURLSessionManager.h" + +typedef NS_ENUM(NSInteger, AFNetworkActivityManagerState) { + AFNetworkActivityManagerStateNotActive, + AFNetworkActivityManagerStateDelayingStart, + AFNetworkActivityManagerStateActive, + AFNetworkActivityManagerStateDelayingEnd +}; + +static NSTimeInterval const kDefaultAFNetworkActivityManagerActivationDelay = 1.0; +static NSTimeInterval const kDefaultAFNetworkActivityManagerCompletionDelay = 0.17; + +static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) { + if ([[notification object] respondsToSelector:@selector(originalRequest)]) { + return [(NSURLSessionTask *)[notification object] originalRequest]; + } else { + return nil; + } +} + +typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisible); + +@interface AFNetworkActivityIndicatorManager () +@property (readwrite, nonatomic, assign) NSInteger activityCount; +@property (readwrite, nonatomic, strong) NSTimer *activationDelayTimer; +@property (readwrite, nonatomic, strong) NSTimer *completionDelayTimer; +@property (readonly, nonatomic, getter = isNetworkActivityOccurring) BOOL networkActivityOccurring; +@property (nonatomic, copy) AFNetworkActivityActionBlock networkActivityActionBlock; +@property (nonatomic, assign) AFNetworkActivityManagerState currentState; +@property (nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; + +- (void)updateCurrentStateForNetworkActivityChange; +@end + +@implementation AFNetworkActivityIndicatorManager + ++ (instancetype)sharedManager { + static AFNetworkActivityIndicatorManager *_sharedManager = nil; + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + _sharedManager = [[self alloc] init]; + }); + + return _sharedManager; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + self.currentState = AFNetworkActivityManagerStateNotActive; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil]; + self.activationDelay = kDefaultAFNetworkActivityManagerActivationDelay; + self.completionDelay = kDefaultAFNetworkActivityManagerCompletionDelay; + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; + + [_activationDelayTimer invalidate]; + [_completionDelayTimer invalidate]; +} + +- (void)setEnabled:(BOOL)enabled { + _enabled = enabled; + if (enabled == NO) { + [self setCurrentState:AFNetworkActivityManagerStateNotActive]; + } +} + +- (void)setNetworkingActivityActionWithBlock:(void (^)(BOOL networkActivityIndicatorVisible))block { + self.networkActivityActionBlock = block; +} + +- (BOOL)isNetworkActivityOccurring { + @synchronized(self) { + return self.activityCount > 0; + } +} + +- (void)setNetworkActivityIndicatorVisible:(BOOL)networkActivityIndicatorVisible { + if (_networkActivityIndicatorVisible != networkActivityIndicatorVisible) { + [self willChangeValueForKey:@"networkActivityIndicatorVisible"]; + @synchronized(self) { + _networkActivityIndicatorVisible = networkActivityIndicatorVisible; + } + [self didChangeValueForKey:@"networkActivityIndicatorVisible"]; + if (self.networkActivityActionBlock) { + self.networkActivityActionBlock(networkActivityIndicatorVisible); + } else { + [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:networkActivityIndicatorVisible]; + } + } +} + +- (void)setActivityCount:(NSInteger)activityCount { + @synchronized(self) { + _activityCount = activityCount; + } + + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateCurrentStateForNetworkActivityChange]; + }); +} + +- (void)incrementActivityCount { + [self willChangeValueForKey:@"activityCount"]; + @synchronized(self) { + _activityCount++; + } + [self didChangeValueForKey:@"activityCount"]; + + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateCurrentStateForNetworkActivityChange]; + }); +} + +- (void)decrementActivityCount { + [self willChangeValueForKey:@"activityCount"]; + @synchronized(self) { + _activityCount = MAX(_activityCount - 1, 0); + } + [self didChangeValueForKey:@"activityCount"]; + + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateCurrentStateForNetworkActivityChange]; + }); +} + +- (void)networkRequestDidStart:(NSNotification *)notification { + if ([AFNetworkRequestFromNotification(notification) URL]) { + [self incrementActivityCount]; + } +} + +- (void)networkRequestDidFinish:(NSNotification *)notification { + if ([AFNetworkRequestFromNotification(notification) URL]) { + [self decrementActivityCount]; + } +} + +#pragma mark - Internal State Management +- (void)setCurrentState:(AFNetworkActivityManagerState)currentState { + @synchronized(self) { + if (_currentState != currentState) { + [self willChangeValueForKey:@"currentState"]; + _currentState = currentState; + switch (currentState) { + case AFNetworkActivityManagerStateNotActive: + [self cancelActivationDelayTimer]; + [self cancelCompletionDelayTimer]; + [self setNetworkActivityIndicatorVisible:NO]; + break; + case AFNetworkActivityManagerStateDelayingStart: + [self startActivationDelayTimer]; + break; + case AFNetworkActivityManagerStateActive: + [self cancelCompletionDelayTimer]; + [self setNetworkActivityIndicatorVisible:YES]; + break; + case AFNetworkActivityManagerStateDelayingEnd: + [self startCompletionDelayTimer]; + break; + } + [self didChangeValueForKey:@"currentState"]; + } + + } +} + +- (void)updateCurrentStateForNetworkActivityChange { + if (self.enabled) { + switch (self.currentState) { + case AFNetworkActivityManagerStateNotActive: + if (self.isNetworkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateDelayingStart]; + } + break; + case AFNetworkActivityManagerStateDelayingStart: + //No op. Let the delay timer finish out. + break; + case AFNetworkActivityManagerStateActive: + if (!self.isNetworkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateDelayingEnd]; + } + break; + case AFNetworkActivityManagerStateDelayingEnd: + if (self.isNetworkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateActive]; + } + break; + } + } +} + +- (void)startActivationDelayTimer { + self.activationDelayTimer = [NSTimer + timerWithTimeInterval:self.activationDelay target:self selector:@selector(activationDelayTimerFired) userInfo:nil repeats:NO]; + [[NSRunLoop mainRunLoop] addTimer:self.activationDelayTimer forMode:NSRunLoopCommonModes]; +} + +- (void)activationDelayTimerFired { + if (self.networkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateActive]; + } else { + [self setCurrentState:AFNetworkActivityManagerStateNotActive]; + } +} + +- (void)startCompletionDelayTimer { + [self.completionDelayTimer invalidate]; + self.completionDelayTimer = [NSTimer timerWithTimeInterval:self.completionDelay target:self selector:@selector(completionDelayTimerFired) userInfo:nil repeats:NO]; + [[NSRunLoop mainRunLoop] addTimer:self.completionDelayTimer forMode:NSRunLoopCommonModes]; +} + +- (void)completionDelayTimerFired { + [self setCurrentState:AFNetworkActivityManagerStateNotActive]; +} + +- (void)cancelActivationDelayTimer { + [self.activationDelayTimer invalidate]; +} + +- (void)cancelCompletionDelayTimer { + [self.completionDelayTimer invalidate]; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h new file mode 100644 index 0000000..d424c9b --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h @@ -0,0 +1,48 @@ +// UIActivityIndicatorView+AFNetworking.h +// Copyright (c) 2011–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 + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +/** + This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a session task. + */ +@interface UIActivityIndicatorView (AFNetworking) + +///---------------------------------- +/// @name Animating for Session Tasks +///---------------------------------- + +/** + Binds the animating state to the state of the specified task. + + @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. + */ +- (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task; + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m new file mode 100644 index 0000000..602a72d --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m @@ -0,0 +1,114 @@ +// UIActivityIndicatorView+AFNetworking.m +// Copyright (c) 2011–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 "UIActivityIndicatorView+AFNetworking.h" +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFURLSessionManager.h" + +@interface AFActivityIndicatorViewNotificationObserver : NSObject +@property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView; +- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView; + +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task; + +@end + +@implementation UIActivityIndicatorView (AFNetworking) + +- (AFActivityIndicatorViewNotificationObserver *)af_notificationObserver { + AFActivityIndicatorViewNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); + if (notificationObserver == nil) { + notificationObserver = [[AFActivityIndicatorViewNotificationObserver alloc] initWithActivityIndicatorView:self]; + objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return notificationObserver; +} + +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { + [[self af_notificationObserver] setAnimatingWithStateOfTask:task]; +} + +@end + +@implementation AFActivityIndicatorViewNotificationObserver + +- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView +{ + self = [super init]; + if (self) { + _activityIndicatorView = activityIndicatorView; + } + return self; +} + +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + + if (task) { + if (task.state != NSURLSessionTaskStateCompleted) { + UIActivityIndicatorView *activityIndicatorView = self.activityIndicatorView; + if (task.state == NSURLSessionTaskStateRunning) { + [activityIndicatorView startAnimating]; + } else { + [activityIndicatorView stopAnimating]; + } + + [notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidSuspendNotification object:task]; + } + } +} + +#pragma mark - + +- (void)af_startAnimating { + dispatch_async(dispatch_get_main_queue(), ^{ + [self.activityIndicatorView startAnimating]; + }); +} + +- (void)af_stopAnimating { + dispatch_async(dispatch_get_main_queue(), ^{ + [self.activityIndicatorView stopAnimating]; + }); +} + +#pragma mark - + +- (void)dealloc { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h new file mode 100644 index 0000000..d33e0d4 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h @@ -0,0 +1,175 @@ +// UIButton+AFNetworking.h +// Copyright (c) 2011–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 + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFImageDownloader; + +/** + This category adds methods to the UIKit framework's `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL. + + @warning Compound values for control `state` (such as `UIControlStateHighlighted | UIControlStateDisabled`) are unsupported. + */ +@interface UIButton (AFNetworking) + +///------------------------------------ +/// @name Accessing the Image Downloader +///------------------------------------ + +/** + Set the shared image downloader used to download images. + + @param imageDownloader The shared image downloader used to download images. +*/ ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; + +/** + The shared image downloader used to download images. + */ ++ (AFImageDownloader *)sharedImageDownloader; + +///-------------------- +/// @name Setting Image +///-------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the image request. + */ +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. + */ +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setImage:forState:` is applied. + + @param state The control state. + @param urlRequest The URL request used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + */ +- (void)setImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + + +///------------------------------- +/// @name Setting Background Image +///------------------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous background image request for the receiver will be cancelled. + + If the background image is cached locally, the background image is set immediately, otherwise the specified placeholder background image will be set immediately, and then the remote background image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the background image request. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the background image request. + @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setBackgroundImage:forState:` is applied. + + @param state The control state. + @param urlRequest The URL request used for the image request. + @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + + +///------------------------------ +/// @name Canceling Image Loading +///------------------------------ + +/** + Cancels any executing image task for the specified control state of the receiver, if one exists. + + @param state The control state. + */ +- (void)cancelImageDownloadTaskForState:(UIControlState)state; + +/** + Cancels any executing background image task for the specified control state of the receiver, if one exists. + + @param state The control state. + */ +- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m new file mode 100644 index 0000000..2da6012 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m @@ -0,0 +1,302 @@ +// UIButton+AFNetworking.m +// Copyright (c) 2011–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 "UIButton+AFNetworking.h" + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "UIImageView+AFNetworking.h" +#import "AFImageDownloader.h" + +@interface UIButton (_AFNetworking) +@end + +@implementation UIButton (_AFNetworking) + +#pragma mark - + +static char AFImageDownloadReceiptNormal; +static char AFImageDownloadReceiptHighlighted; +static char AFImageDownloadReceiptSelected; +static char AFImageDownloadReceiptDisabled; + +static const char * af_imageDownloadReceiptKeyForState(UIControlState state) { + switch (state) { + case UIControlStateHighlighted: + return &AFImageDownloadReceiptHighlighted; + case UIControlStateSelected: + return &AFImageDownloadReceiptSelected; + case UIControlStateDisabled: + return &AFImageDownloadReceiptDisabled; + case UIControlStateNormal: + default: + return &AFImageDownloadReceiptNormal; + } +} + +- (AFImageDownloadReceipt *)af_imageDownloadReceiptForState:(UIControlState)state { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_imageDownloadReceiptKeyForState(state)); +} + +- (void)af_setImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt + forState:(UIControlState)state +{ + objc_setAssociatedObject(self, af_imageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +static char AFBackgroundImageDownloadReceiptNormal; +static char AFBackgroundImageDownloadReceiptHighlighted; +static char AFBackgroundImageDownloadReceiptSelected; +static char AFBackgroundImageDownloadReceiptDisabled; + +static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState state) { + switch (state) { + case UIControlStateHighlighted: + return &AFBackgroundImageDownloadReceiptHighlighted; + case UIControlStateSelected: + return &AFBackgroundImageDownloadReceiptSelected; + case UIControlStateDisabled: + return &AFBackgroundImageDownloadReceiptDisabled; + case UIControlStateNormal: + default: + return &AFBackgroundImageDownloadReceiptNormal; + } +} + +- (AFImageDownloadReceipt *)af_backgroundImageDownloadReceiptForState:(UIControlState)state { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state)); +} + +- (void)af_setBackgroundImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt + forState:(UIControlState)state +{ + objc_setAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation UIButton (AFNetworking) + ++ (AFImageDownloader *)sharedImageDownloader { + + return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; +} + ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { + objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url +{ + [self setImageForState:state withURL:url placeholderImage:nil]; +} + +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure +{ + if ([self isActiveTaskURLEqualToURLRequest:urlRequest forState:state]) { + return; + } + + [self cancelImageDownloadTaskForState:state]; + + AFImageDownloader *downloader = [[self class] sharedImageDownloader]; + id imageCache = downloader.imageCache; + + //Use the image from the image cache if it exists + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; + if (cachedImage) { + if (success) { + success(urlRequest, nil, cachedImage); + } else { + [self setImage:cachedImage forState:state]; + } + [self af_setImageDownloadReceipt:nil forState:state]; + } else { + if (placeholderImage) { + [self setImage:placeholderImage forState:state]; + } + + __weak __typeof(self)weakSelf = self; + NSUUID *downloadID = [NSUUID UUID]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + withReceiptID:downloadID + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (success) { + success(request, response, responseObject); + } else if(responseObject) { + [strongSelf setImage:responseObject forState:state]; + } + [strongSelf af_setImageDownloadReceipt:nil forState:state]; + } + + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (failure) { + failure(request, response, error); + } + [strongSelf af_setImageDownloadReceipt:nil forState:state]; + } + }]; + + [self af_setImageDownloadReceipt:receipt forState:state]; + } +} + +#pragma mark - + +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url +{ + [self setBackgroundImageForState:state withURL:url placeholderImage:nil]; +} + +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setBackgroundImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setBackgroundImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure +{ + if ([self isActiveBackgroundTaskURLEqualToURLRequest:urlRequest forState:state]) { + return; + } + + [self cancelBackgroundImageDownloadTaskForState:state]; + + AFImageDownloader *downloader = [[self class] sharedImageDownloader]; + id imageCache = downloader.imageCache; + + //Use the image from the image cache if it exists + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; + if (cachedImage) { + if (success) { + success(urlRequest, nil, cachedImage); + } else { + [self setBackgroundImage:cachedImage forState:state]; + } + [self af_setBackgroundImageDownloadReceipt:nil forState:state]; + } else { + if (placeholderImage) { + [self setBackgroundImage:placeholderImage forState:state]; + } + + __weak __typeof(self)weakSelf = self; + NSUUID *downloadID = [NSUUID UUID]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + withReceiptID:downloadID + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (success) { + success(request, response, responseObject); + } else if(responseObject) { + [strongSelf setBackgroundImage:responseObject forState:state]; + } + [strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state]; + } + + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (failure) { + failure(request, response, error); + } + [strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state]; + } + }]; + + [self af_setBackgroundImageDownloadReceipt:receipt forState:state]; + } +} + +#pragma mark - + +- (void)cancelImageDownloadTaskForState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state]; + if (receipt != nil) { + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt]; + [self af_setImageDownloadReceipt:nil forState:state]; + } +} + +- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state]; + if (receipt != nil) { + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt]; + [self af_setBackgroundImageDownloadReceipt:nil forState:state]; + } +} + +- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state]; + return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; +} + +- (BOOL)isActiveBackgroundTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state]; + return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; +} + + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h new file mode 100644 index 0000000..14744cd --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h @@ -0,0 +1,35 @@ +// +// UIImage+AFNetworking.h +// +// +// Created by Paulo Ferreira on 08/07/15. +// +// 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 TARGET_OS_IOS || TARGET_OS_TV + +#import + +@interface UIImage (AFNetworking) + ++ (UIImage*) safeImageWithData:(NSData*)data; + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h new file mode 100644 index 0000000..8929252 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h @@ -0,0 +1,109 @@ +// UIImageView+AFNetworking.h +// Copyright (c) 2011–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 + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFImageDownloader; + +/** + This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL. + */ +@interface UIImageView (AFNetworking) + +///------------------------------------ +/// @name Accessing the Image Downloader +///------------------------------------ + +/** + Set the shared image downloader used to download images. + + @param imageDownloader The shared image downloader used to download images. + */ ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; + +/** + The shared image downloader used to download images. + */ ++ (AFImageDownloader *)sharedImageDownloader; + +///-------------------- +/// @name Setting Image +///-------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` + + @param url The URL used for the image request. + */ +- (void)setImageWithURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` + + @param url The URL used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. + */ +- (void)setImageWithURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is applied. + + @param urlRequest The URL request used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + */ +- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + +/** + Cancels any executing image operation for the receiver, if one exists. + */ +- (void)cancelImageDownloadTask; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m new file mode 100644 index 0000000..41c18a6 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m @@ -0,0 +1,160 @@ +// UIImageView+AFNetworking.m +// Copyright (c) 2011–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 "UIImageView+AFNetworking.h" + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFImageDownloader.h" + +@interface UIImageView (_AFNetworking) +@property (readwrite, nonatomic, strong, setter = af_setActiveImageDownloadReceipt:) AFImageDownloadReceipt *af_activeImageDownloadReceipt; +@end + +@implementation UIImageView (_AFNetworking) + +- (AFImageDownloadReceipt *)af_activeImageDownloadReceipt { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(af_activeImageDownloadReceipt)); +} + +- (void)af_setActiveImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt { + objc_setAssociatedObject(self, @selector(af_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation UIImageView (AFNetworking) + ++ (AFImageDownloader *)sharedImageDownloader { + return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; +} + ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { + objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)setImageWithURL:(NSURL *)url { + [self setImageWithURL:url placeholderImage:nil]; +} + +- (void)setImageWithURL:(NSURL *)url + placeholderImage:(UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(UIImage *)placeholderImage + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure +{ + + if ([urlRequest URL] == nil) { + self.image = placeholderImage; + if (failure) { + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil]; + failure(urlRequest, nil, error); + } + return; + } + + if ([self isActiveTaskURLEqualToURLRequest:urlRequest]){ + return; + } + + [self cancelImageDownloadTask]; + + AFImageDownloader *downloader = [[self class] sharedImageDownloader]; + id imageCache = downloader.imageCache; + + //Use the image from the image cache if it exists + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; + if (cachedImage) { + if (success) { + success(urlRequest, nil, cachedImage); + } else { + self.image = cachedImage; + } + [self clearActiveDownloadInformation]; + } else { + if (placeholderImage) { + self.image = placeholderImage; + } + + __weak __typeof(self)weakSelf = self; + NSUUID *downloadID = [NSUUID UUID]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + withReceiptID:downloadID + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { + if (success) { + success(request, response, responseObject); + } else if(responseObject) { + strongSelf.image = responseObject; + } + [strongSelf clearActiveDownloadInformation]; + } + + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { + if (failure) { + failure(request, response, error); + } + [strongSelf clearActiveDownloadInformation]; + } + }]; + + self.af_activeImageDownloadReceipt = receipt; + } +} + +- (void)cancelImageDownloadTask { + if (self.af_activeImageDownloadReceipt != nil) { + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt]; + [self clearActiveDownloadInformation]; + } +} + +- (void)clearActiveDownloadInformation { + self.af_activeImageDownloadReceipt = nil; +} + +- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest { + return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h new file mode 100644 index 0000000..febacfc --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h @@ -0,0 +1,42 @@ +// UIKit+AFNetworking.h +// +// Copyright (c) 2011–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. + +#if TARGET_OS_IOS || TARGET_OS_TV +#import + +#ifndef _UIKIT_AFNETWORKING_ + #define _UIKIT_AFNETWORKING_ + +#if TARGET_OS_IOS + #import "AFAutoPurgingImageCache.h" + #import "AFImageDownloader.h" + #import "AFNetworkActivityIndicatorManager.h" + #import "UIRefreshControl+AFNetworking.h" + #import "UIWebView+AFNetworking.h" +#endif + + #import "UIActivityIndicatorView+AFNetworking.h" + #import "UIButton+AFNetworking.h" + #import "UIImageView+AFNetworking.h" + #import "UIProgressView+AFNetworking.h" +#endif /* _UIKIT_AFNETWORKING_ */ +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h new file mode 100644 index 0000000..8ea0a73 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h @@ -0,0 +1,64 @@ +// UIProgressView+AFNetworking.h +// Copyright (c) 2011–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 + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +NS_ASSUME_NONNULL_BEGIN + + +/** + This category adds methods to the UIKit framework's `UIProgressView` class. The methods in this category provide support for binding the progress to the upload and download progress of a session task. + */ +@interface UIProgressView (AFNetworking) + +///------------------------------------ +/// @name Setting Session Task Progress +///------------------------------------ + +/** + Binds the progress to the upload progress of the specified session task. + + @param task The session task. + @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. + */ +- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task + animated:(BOOL)animated; + +/** + Binds the progress to the download progress of the specified session task. + + @param task The session task. + @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. + */ +- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task + animated:(BOOL)animated; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m new file mode 100644 index 0000000..2ae753e --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m @@ -0,0 +1,126 @@ +// UIProgressView+AFNetworking.m +// Copyright (c) 2011–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 "UIProgressView+AFNetworking.h" + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFURLSessionManager.h" + +static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext; +static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext; + +#pragma mark - + +@implementation UIProgressView (AFNetworking) + +- (BOOL)af_uploadProgressAnimated { + return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_uploadProgressAnimated)) boolValue]; +} + +- (void)af_setUploadProgressAnimated:(BOOL)animated { + objc_setAssociatedObject(self, @selector(af_uploadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (BOOL)af_downloadProgressAnimated { + return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_downloadProgressAnimated)) boolValue]; +} + +- (void)af_setDownloadProgressAnimated:(BOOL)animated { + objc_setAssociatedObject(self, @selector(af_downloadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task + animated:(BOOL)animated +{ + if (task.state == NSURLSessionTaskStateCompleted) { + return; + } + + [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; + [task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; + + [self af_setUploadProgressAnimated:animated]; +} + +- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task + animated:(BOOL)animated +{ + if (task.state == NSURLSessionTaskStateCompleted) { + return; + } + + [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; + [task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; + + [self af_setDownloadProgressAnimated:animated]; +} + +#pragma mark - NSKeyValueObserving + +- (void)observeValueForKeyPath:(NSString *)keyPath + ofObject:(id)object + change:(__unused NSDictionary *)change + context:(void *)context +{ + if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) { + if ([object countOfBytesExpectedToSend] > 0) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self setProgress:[object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f) animated:self.af_uploadProgressAnimated]; + }); + } + } + + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) { + if ([object countOfBytesExpectedToReceive] > 0) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self setProgress:[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f) animated:self.af_downloadProgressAnimated]; + }); + } + } + + if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) { + if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) { + @try { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))]; + + if (context == AFTaskCountOfBytesSentContext) { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))]; + } + + if (context == AFTaskCountOfBytesReceivedContext) { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))]; + } + } + @catch (NSException * __unused exception) {} + } + } + } +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h new file mode 100644 index 0000000..215eafc --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h @@ -0,0 +1,53 @@ +// UIRefreshControl+AFNetworking.m +// +// Copyright (c) 2011–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 + +#import + +#if TARGET_OS_IOS + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically beginning and ending refreshing depending on the loading state of a session task. + */ +@interface UIRefreshControl (AFNetworking) + +///----------------------------------- +/// @name Refreshing for Session Tasks +///----------------------------------- + +/** + Binds the refreshing state to the state of the specified task. + + @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. + */ +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m new file mode 100644 index 0000000..cd46916 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m @@ -0,0 +1,113 @@ +// UIRefreshControl+AFNetworking.m +// +// Copyright (c) 2011–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 "UIRefreshControl+AFNetworking.h" +#import + +#if TARGET_OS_IOS + +#import "AFURLSessionManager.h" + +@interface AFRefreshControlNotificationObserver : NSObject +@property (readonly, nonatomic, weak) UIRefreshControl *refreshControl; +- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl; + +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; + +@end + +@implementation UIRefreshControl (AFNetworking) + +- (AFRefreshControlNotificationObserver *)af_notificationObserver { + AFRefreshControlNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); + if (notificationObserver == nil) { + notificationObserver = [[AFRefreshControlNotificationObserver alloc] initWithActivityRefreshControl:self]; + objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return notificationObserver; +} + +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { + [[self af_notificationObserver] setRefreshingWithStateOfTask:task]; +} + +@end + +@implementation AFRefreshControlNotificationObserver + +- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl +{ + self = [super init]; + if (self) { + _refreshControl = refreshControl; + } + return self; +} + +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + + if (task) { + UIRefreshControl *refreshControl = self.refreshControl; + if (task.state == NSURLSessionTaskStateRunning) { + [refreshControl beginRefreshing]; + + [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task]; + } else { + [refreshControl endRefreshing]; + } + } +} + +#pragma mark - + +- (void)af_beginRefreshing { + dispatch_async(dispatch_get_main_queue(), ^{ + [self.refreshControl beginRefreshing]; + }); +} + +- (void)af_endRefreshing { + dispatch_async(dispatch_get_main_queue(), ^{ + [self.refreshControl endRefreshing]; + }); +} + +#pragma mark - + +- (void)dealloc { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h new file mode 100644 index 0000000..b9a56af --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h @@ -0,0 +1,80 @@ +// UIWebView+AFNetworking.h +// Copyright (c) 2011–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 + +#import + +#if TARGET_OS_IOS + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFHTTPSessionManager; + +/** + This category adds methods to the UIKit framework's `UIWebView` class. The methods in this category provide increased control over the request cycle, including progress monitoring and success / failure handling. + + @discussion When using these category methods, make sure to assign `delegate` for the web view, which implements `–webView:shouldStartLoadWithRequest:navigationType:` appropriately. This allows for tapped links to be loaded through AFNetworking, and can ensure that `canGoBack` & `canGoForward` update their values correctly. + */ +@interface UIWebView (AFNetworking) + +/** + The session manager used to download all requests. + */ +@property (nonatomic, strong) AFHTTPSessionManager *sessionManager; + +/** + Asynchronously loads the specified request. + + @param request A URL request identifying the location of the content to load. This must not be `nil`. + @param progress A progress object monitoring the current download progress. + @param success A block object to be executed when the request finishes loading successfully. This block returns the HTML string to be loaded by the web view, and takes two arguments: the response, and the response string. + @param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred. + */ +- (void)loadRequest:(NSURLRequest *)request + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success + failure:(nullable void (^)(NSError *error))failure; + +/** + Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding. + + @param request A URL request identifying the location of the content to load. This must not be `nil`. + @param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified. + @param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified. +@param progress A progress object monitoring the current download progress. + @param success A block object to be executed when the request finishes loading successfully. This block returns the data to be loaded by the web view and takes two arguments: the response, and the downloaded data. + @param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred. + */ +- (void)loadRequest:(NSURLRequest *)request + MIMEType:(nullable NSString *)MIMEType + textEncodingName:(nullable NSString *)textEncodingName + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success + failure:(nullable void (^)(NSError *error))failure; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m new file mode 100644 index 0000000..030c3e9 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m @@ -0,0 +1,157 @@ +// UIWebView+AFNetworking.m +// Copyright (c) 2011–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 "UIWebView+AFNetworking.h" + +#import + +#if TARGET_OS_IOS + +#import "AFHTTPSessionManager.h" +#import "AFURLResponseSerialization.h" +#import "AFURLRequestSerialization.h" + +@interface UIWebView (_AFNetworking) +@property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask; +@end + +@implementation UIWebView (_AFNetworking) + +- (NSURLSessionDataTask *)af_URLSessionTask { + return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask)); +} + +- (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask { + objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation UIWebView (AFNetworking) + +- (AFHTTPSessionManager *)sessionManager { + static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + _af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer]; + _af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer]; + }); + + return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager; +} + +- (void)setSessionManager:(AFHTTPSessionManager *)sessionManager { + objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (AFHTTPResponseSerializer *)responseSerializer { + static AFHTTPResponseSerializer *_af_defaultResponseSerializer = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer]; + }); + + return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer; +} + +- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { + objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)loadRequest:(NSURLRequest *)request + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success + failure:(void (^)(NSError *error))failure +{ + [self loadRequest:request MIMEType:nil textEncodingName:nil progress:progress success:^NSData *(NSHTTPURLResponse *response, NSData *data) { + NSStringEncoding stringEncoding = NSUTF8StringEncoding; + if (response.textEncodingName) { + CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName); + if (encoding != kCFStringEncodingInvalidId) { + stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); + } + } + + NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding]; + if (success) { + string = success(response, string); + } + + return [string dataUsingEncoding:stringEncoding]; + } failure:failure]; +} + +- (void)loadRequest:(NSURLRequest *)request + MIMEType:(NSString *)MIMEType + textEncodingName:(NSString *)textEncodingName + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success + failure:(void (^)(NSError *error))failure +{ + NSParameterAssert(request); + + if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) { + [self.af_URLSessionTask cancel]; + } + self.af_URLSessionTask = nil; + + __weak __typeof(self)weakSelf = self; + __block NSURLSessionDataTask *dataTask; + dataTask = [self.sessionManager + dataTaskWithRequest:request + uploadProgress:nil + downloadProgress:nil + completionHandler:^(NSURLResponse * _Nonnull response, id _Nonnull responseObject, NSError * _Nullable error) { + __strong __typeof(weakSelf) strongSelf = weakSelf; + if (error) { + if (failure) { + failure(error); + } + } else { + if (success) { + success((NSHTTPURLResponse *)response, responseObject); + } + [strongSelf loadData:responseObject MIMEType:MIMEType textEncodingName:textEncodingName baseURL:[dataTask.currentRequest URL]]; + + if ([strongSelf.delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) { + [strongSelf.delegate webViewDidFinishLoad:strongSelf]; + } + } + }]; + self.af_URLSessionTask = dataTask; + if (progress != nil) { + *progress = [self.sessionManager downloadProgressForTask:dataTask]; + } + [self.af_URLSessionTask resume]; + + if ([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { + [self.delegate webViewDidStartLoad:self]; + } +} + +@end + +#endif diff --git a/Pods/FMDB/LICENSE.txt b/Pods/FMDB/LICENSE.txt new file mode 100644 index 0000000..addfc1a --- /dev/null +++ b/Pods/FMDB/LICENSE.txt @@ -0,0 +1,28 @@ +If you are using FMDB in your project, I'd love to hear about it. Let Gus know +by sending an email to gus@flyingmeat.com. + +And if you happen to come across either Gus Mueller or Rob Ryan in a bar, you +might consider purchasing a drink of their choosing if FMDB has been useful to +you. + +Finally, and shortly, this is the MIT License. + +Copyright (c) 2008-2014 Flying Meat Inc. + +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/Pods/FMDB/README.markdown b/Pods/FMDB/README.markdown new file mode 100644 index 0000000..d351def --- /dev/null +++ b/Pods/FMDB/README.markdown @@ -0,0 +1,541 @@ +# FMDB v2.7 + +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/FMDB.svg)](https://img.shields.io/cocoapods/v/FMDB.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) + +This is an Objective-C wrapper around SQLite: http://sqlite.org/ + +## The FMDB Mailing List: +http://groups.google.com/group/fmdb + +## Read the SQLite FAQ: +http://www.sqlite.org/faq.html + +Since FMDB is built on top of SQLite, you're going to want to read this page top to bottom at least once. And while you're there, make sure to bookmark the SQLite Documentation page: http://www.sqlite.org/docs.html + +## Contributing +Do you have an awesome idea that deserves to be in FMDB? You might consider pinging ccgus first to make sure he hasn't already ruled it out for some reason. Otherwise pull requests are great, and make sure you stick to the local coding conventions. However, please be patient and if you haven't heard anything from ccgus for a week or more, you might want to send a note asking what's up. + +## Installing + +### CocoaPods + +[![Dependency Status](https://www.versioneye.com/objective-c/fmdb/2.3/badge.svg?style=flat)](https://www.versioneye.com/objective-c/fmdb/2.3) +[![Reference Status](https://www.versioneye.com/objective-c/fmdb/reference_badge.svg?style=flat)](https://www.versioneye.com/objective-c/fmdb/references) + +FMDB can be installed using [CocoaPods](https://cocoapods.org/). + +If you haven't done so already, you might want to initialize the project, to have it produce a `Podfile` template for you: + +``` +$ pod init +``` + +Then, edit the `Podfile`, adding `FMDB`: + +```ruby +# Uncomment the next line to define a global platform for your project +# platform :ios, '9.0' + +target 'MyApp' do + # Comment the next line if you're not using Swift and don't want to use dynamic frameworks + use_frameworks! + + # Pods for MyApp2 + + pod 'FMDB' + # pod 'FMDB/FTS' # FMDB with FTS + # pod 'FMDB/standalone' # FMDB with latest SQLite amalgamation source + # pod 'FMDB/standalone/FTS' # FMDB with latest SQLite amalgamation source and FTS + # pod 'FMDB/SQLCipher' # FMDB with SQLCipher +end +``` + +Then install the pods: + +``` +$ pod install +``` + +Then open the `.xcworkspace` rather than the `.xcodeproj`. + +For more information on Cocoapods visit https://cocoapods.org. + +**If using FMDB with [SQLCipher](https://www.zetetic.net/sqlcipher/) you must use the FMDB/SQLCipher subspec. The FMDB/SQLCipher subspec declares SQLCipher as a dependency, allowing FMDB to be compiled with the `-DSQLITE_HAS_CODEC` flag.** + +### Carthage + +Once you make sure you have [the latest version of Carthage](https://github.com/Carthage/Carthage/releases), you can open up a command line terminal, navigate to your project's main directory, and then do the following commands: + +``` +$ echo ' github "ccgus/fmdb" ' > ./Cartfile +$ carthage update +``` + +You can then configure your project as outlined in Carthage's [Getting Started](https://github.com/Carthage/Carthage#getting-started) (i.e. for iOS, adding the framework to the "Link Binary with Libraries" in your target and adding the `copy-frameworks` script; in macOS, adding the framework to the list of "Embedded Binaries"). + +## FMDB Class Reference: +http://ccgus.github.io/fmdb/html/index.html + +## Automatic Reference Counting (ARC) or Manual Memory Management? +You can use either style in your Cocoa project. FMDB will figure out which you are using at compile time and do the right thing. + +## What's New in FMDB 2.7 + +FMDB 2.7 attempts to support a more natural interface. This represents a fairly significant change for Swift developers (audited for nullability; shifted to properties in external interfaces where possible rather than methods; etc.). For Objective-C developers, this should be a fairly seamless transition (unless you were using the ivars that were previously exposed in the public interface, which you shouldn't have been doing, anyway!). + +### Nullability and Swift Optionals + +FMDB 2.7 is largely the same as prior versions, but has been audited for nullability. For Objective-C users, this simply means that if you perform a static analysis of your FMDB-based project, you may receive more meaningful warnings as you review your project, but there are likely to be few, if any, changes necessary in your code. + +For Swift users, this nullability audit results in changes that are not entirely backward compatible with FMDB 2.6, but is a little more Swifty. Before FMDB was audited for nullability, Swift was forced to defensively assume that variables were optional, but the library now more accurately knows which properties and method parameters are optional, and which are not. + +This means, though, that Swift code written for FMDB 2.7 may require changes. For example, consider the following Swift 3/Swift 4 code for FMDB 2.6: +```swift + +guard let queue = FMDatabaseQueue(path: fileURL.path) else { + print("Unable to create FMDatabaseQueue") + return +} + +queue.inTransaction { db, rollback in + do { + guard let db == db else { + // handle error here + return + } + + try db.executeUpdate("INSERT INTO foo (bar) VALUES (?)", values: [1]) + try db.executeUpdate("INSERT INTO foo (bar) VALUES (?)", values: [2]) + } catch { + rollback?.pointee = true + } +} +``` + +Because FMDB 2.6 was not audited for nullability, Swift inferred that `db` and `rollback` were optionals. But, now, in FMDB 2.7, Swift now knows that, for example, neither `db` nor `rollback` above can be `nil`, so they are no longer optionals. Thus it becomes: + +```swift + +let queue = FMDatabaseQueue(url: fileURL) + +queue.inTransaction { db, rollback in + do { + try db.executeUpdate("INSERT INTO foo (bar) VALUES (?)", values: [1]) + try db.executeUpdate("INSERT INTO foo (bar) VALUES (?)", values: [2]) + } catch { + rollback.pointee = true + } +} +``` + +### Custom Functions + +In the past, when writing custom functions, you would have to generally include your own `@autoreleasepool` block to avoid problems when writing functions that scanned through a large table. Now, FMDB will automatically wrap it in an autorelease pool, so you don't have to. + +Also, in the past, when retrieving the values passed to the function, you had to drop down to the SQLite C API and include your own `sqlite3_value_XXX` calls. There are now `FMDatabase` methods, `valueInt`, `valueString`, etc., so you can stay within Swift and/or Objective-C, without needing to call the C functions yourself. Likewise, when specifying the return values, you no longer need to call `sqlite3_result_XXX` C API, but rather you can use `FMDatabase` methods, `resultInt`, `resultString`, etc. There is a new `enum` for `valueType` called `SqliteValueType`, which can be used for checking the type of parameter passed to the custom function. + +Thus, you can do something like (as of Swift 3): + +```swift +db.makeFunctionNamed("RemoveDiacritics", arguments: 1) { context, argc, argv in + guard db.valueType(argv[0]) == .text || db.valueType(argv[0]) == .null else { + db.resultError("Expected string parameter", context: context) + return + } + + if let string = db.valueString(argv[0])?.folding(options: .diacriticInsensitive, locale: nil) { + db.resultString(string, context: context) + } else { + db.resultNull(context: context) + } +} +``` + +And you can then use that function in your SQL (in this case, matching both "Jose" and "José"): + +```sql +SELECT * FROM employees WHERE RemoveDiacritics(first_name) LIKE 'jose' +``` + +Note, the method `makeFunctionNamed:maximumArguments:withBlock:` has been renamed to `makeFunctionNamed:arguments:block:`, to more accurately reflect the functional intent of the second parameter. + +### API Changes + +In addition to the `makeFunctionNamed` noted above, there are a few other API changes. Specifically, + + - To become consistent with the rest of the API, the methods `objectForColumnName` and `UTF8StringForColumnName` have been renamed to `objectForColumn` and `UTF8StringForColumn`. + + - Note, the `objectForColumn` (and the associted subscript operator) now returns `nil` if an invalid column name/index is passed to it. It used to return `NSNull`. + + - To avoid confusion with `FMDatabaseQueue` method `inTransaction`, which performs transactions, the `FMDatabase` method to determine whether you are in a transaction or not, `inTransaction`, has been replaced with a read-only property, `isInTransaction`. + + - Several functions have been converted to properties, namely, `databasePath`, `maxBusyRetryTimeInterval`, `shouldCacheStatements`, `sqliteHandle`, `hasOpenResultSets`, `lastInsertRowId`, `changes`, `goodConnection`, `columnCount`, `resultDictionary`, `applicationID`, `applicationIDString`, `userVersion`, `countOfCheckedInDatabases`, `countOfCheckedOutDatabases`, and `countOfOpenDatabases`. For Objective-C users, this has little material impact, but for Swift users, it results in a slightly more natural interface. Note: For Objective-C developers, previously versions of FMDB exposed many ivars (but we hope you weren't using them directly, anyway!), but the implmentation details for these are no longer exposed. + +### URL Methods + +In keeping with Apple's shift from paths to URLs, there are now `NSURL` renditions of the various `init` methods, previously only accepting paths. + +## Usage +There are three main classes in FMDB: + +1. `FMDatabase` - Represents a single SQLite database. Used for executing SQL statements. +2. `FMResultSet` - Represents the results of executing a query on an `FMDatabase`. +3. `FMDatabaseQueue` - If you're wanting to perform queries and updates on multiple threads, you'll want to use this class. It's described in the "Thread Safety" section below. + +### Database Creation +An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: + +1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. +2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed. +3. `NULL`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. + +(For more information on temporary and in-memory databases, read the sqlite documentation on the subject: http://www.sqlite.org/inmemorydb.html) + +```objc +NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"tmp.db"]; +FMDatabase *db = [FMDatabase databaseWithPath:path]; +``` + +### Opening + +Before you can interact with the database, it must be opened. Opening fails if there are insufficient resources or permissions to open and/or create the database. + +```objc +if (![db open]) { + // [db release]; // uncomment this line in manual referencing code; in ARC, this is not necessary/permitted + db = nil; + return; +} +``` + +### Executing Updates + +Any sort of SQL statement which is not a `SELECT` statement qualifies as an update. This includes `CREATE`, `UPDATE`, `INSERT`, `ALTER`, `COMMIT`, `BEGIN`, `DETACH`, `DELETE`, `DROP`, `END`, `EXPLAIN`, `VACUUM`, and `REPLACE` statements (plus many more). Basically, if your SQL statement does not begin with `SELECT`, it is an update statement. + +Executing updates returns a single value, a `BOOL`. A return value of `YES` means the update was successfully executed, and a return value of `NO` means that some error was encountered. You may invoke the `-lastErrorMessage` and `-lastErrorCode` methods to retrieve more information. + +### Executing Queries + +A `SELECT` statement is a query and is executed via one of the `-executeQuery...` methods. + +Executing queries returns an `FMResultSet` object if successful, and `nil` upon failure. You should use the `-lastErrorMessage` and `-lastErrorCode` methods to determine why a query failed. + +In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" from one record to the other. With FMDB, the easiest way to do that is like this: + +```objc +FMResultSet *s = [db executeQuery:@"SELECT * FROM myTable"]; +while ([s next]) { + //retrieve values for each record +} +``` + +You must always invoke `-[FMResultSet next]` before attempting to access the values returned in a query, even if you're only expecting one: + +```objc +FMResultSet *s = [db executeQuery:@"SELECT COUNT(*) FROM myTable"]; +if ([s next]) { + int totalCount = [s intForColumnIndex:0]; +} +``` + +`FMResultSet` has many methods to retrieve data in an appropriate format: + +- `intForColumn:` +- `longForColumn:` +- `longLongIntForColumn:` +- `boolForColumn:` +- `doubleForColumn:` +- `stringForColumn:` +- `dateForColumn:` +- `dataForColumn:` +- `dataNoCopyForColumn:` +- `UTF8StringForColumn:` +- `objectForColumn:` + +Each of these methods also has a `{type}ForColumnIndex:` variant that is used to retrieve the data based on the position of the column in the results, as opposed to the column's name. + +Typically, there's no need to `-close` an `FMResultSet` yourself, since that happens when either the result set is deallocated, or the parent database is closed. + +### Closing + +When you have finished executing queries and updates on the database, you should `-close` the `FMDatabase` connection so that SQLite will relinquish any resources it has acquired during the course of its operation. + +```objc +[db close]; +``` + +### Transactions + +`FMDatabase` can begin and commit a transaction by invoking one of the appropriate methods or executing a begin/end transaction statement. + +### Multiple Statements and Batch Stuff + +You can use `FMDatabase`'s executeStatements:withResultBlock: to do multiple statements in a string: + +```objc +NSString *sql = @"create table bulktest1 (id integer primary key autoincrement, x text);" + "create table bulktest2 (id integer primary key autoincrement, y text);" + "create table bulktest3 (id integer primary key autoincrement, z text);" + "insert into bulktest1 (x) values ('XXX');" + "insert into bulktest2 (y) values ('YYY');" + "insert into bulktest3 (z) values ('ZZZ');"; + +success = [db executeStatements:sql]; + +sql = @"select count(*) as count from bulktest1;" + "select count(*) as count from bulktest2;" + "select count(*) as count from bulktest3;"; + +success = [self.db executeStatements:sql withResultBlock:^int(NSDictionary *dictionary) { + NSInteger count = [dictionary[@"count"] integerValue]; + XCTAssertEqual(count, 1, @"expected one record for dictionary %@", dictionary); + return 0; +}]; +``` + +### Data Sanitization + +When providing a SQL statement to FMDB, you should not attempt to "sanitize" any values before insertion. Instead, you should use the standard SQLite binding syntax: + +```sql +INSERT INTO myTable VALUES (?, ?, ?, ?) +``` + +The `?` character is recognized by SQLite as a placeholder for a value to be inserted. The execution methods all accept a variable number of arguments (or a representation of those arguments, such as an `NSArray`, `NSDictionary`, or a `va_list`), which are properly escaped for you. + +And, to use that SQL with the `?` placeholders from Objective-C: + +```objc +NSInteger identifier = 42; +NSString *name = @"Liam O'Flaherty (\"the famous Irish author\")"; +NSDate *date = [NSDate date]; +NSString *comment = nil; + +BOOL success = [db executeUpdate:@"INSERT INTO authors (identifier, name, date, comment) VALUES (?, ?, ?, ?)", @(identifier), name, date, comment ?: [NSNull null]]; +if (!success) { + NSLog(@"error = %@", [db lastErrorMessage]); +} +``` + +> **Note:** Fundamental data types, like the `NSInteger` variable `identifier`, should be as a `NSNumber` objects, achieved by using the `@` syntax, shown above. Or you can use the `[NSNumber numberWithInt:identifier]` syntax, too. +> +> Likewise, SQL `NULL` values should be inserted as `[NSNull null]`. For example, in the case of `comment` which might be `nil` (and is in this example), you can use the `comment ?: [NSNull null]` syntax, which will insert the string if `comment` is not `nil`, but will insert `[NSNull null]` if it is `nil`. + +In Swift, you would use `executeUpdate(values:)`, which not only is a concise Swift syntax, but also `throws` errors for proper error handling: + +```swift +do { + let identifier = 42 + let name = "Liam O'Flaherty (\"the famous Irish author\")" + let date = Date() + let comment: String? = nil + + try db.executeUpdate("INSERT INTO authors (identifier, name, date, comment) VALUES (?, ?, ?, ?)", values: [identifier, name, date, comment ?? NSNull()]) +} catch { + print("error = \(error)") +} +``` + +> **Note:** In Swift, you don't have to wrap fundamental numeric types like you do in Objective-C. But if you are going to insert an optional string, you would probably use the `comment ?? NSNull()` syntax (i.e., if it is `nil`, use `NSNull`, otherwise use the string). + +Alternatively, you may use named parameters syntax: + +```sql +INSERT INTO authors (identifier, name, date, comment) VALUES (:identifier, :name, :date, :comment) +``` + +The parameters *must* start with a colon. SQLite itself supports other characters, but internally the dictionary keys are prefixed with a colon, do **not** include the colon in your dictionary keys. + +```objc +NSDictionary *arguments = @{@"identifier": @(identifier), @"name": name, @"date": date, @"comment": comment ?: [NSNull null]}; +BOOL success = [db executeUpdate:@"INSERT INTO authors (identifier, name, date, comment) VALUES (:identifier, :name, :date, :comment)" withParameterDictionary:arguments]; +if (!success) { + NSLog(@"error = %@", [db lastErrorMessage]); +} +``` + +The key point is that one should not use `NSString` method `stringWithFormat` to manually insert values into the SQL statement, itself. Nor should one Swift string interpolation to insert values into the SQL. Use `?` placeholders for values to be inserted into the database (or used in `WHERE` clauses in `SELECT` statements). + +

Using FMDatabaseQueue and Thread Safety.

+ +Using a single instance of `FMDatabase` from multiple threads at once is a bad idea. It has always been OK to make a `FMDatabase` object *per thread*. Just don't share a single instance across threads, and definitely not across multiple threads at the same time. Bad things will eventually happen and you'll eventually get something to crash, or maybe get an exception, or maybe meteorites will fall out of the sky and hit your Mac Pro. *This would suck*. + +**So don't instantiate a single `FMDatabase` object and use it across multiple threads.** + +Instead, use `FMDatabaseQueue`. Instantiate a single `FMDatabaseQueue` and use it across multiple threads. The `FMDatabaseQueue` object will synchronize and coordinate access across the multiple threads. Here's how to use it: + +First, make your queue. + +```objc +FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath]; +``` + +Then use it like so: + + +```objc +[queue inDatabase:^(FMDatabase *db) { + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @1]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @2]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @3]; + + FMResultSet *rs = [db executeQuery:@"select * from foo"]; + while ([rs next]) { + … + } +}]; +``` + +An easy way to wrap things up in a transaction can be done like this: + +```objc +[queue inTransaction:^(FMDatabase *db, BOOL *rollback) { + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @1]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @2]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", @3]; + + if (whoopsSomethingWrongHappened) { + *rollback = YES; + return; + } + + // etc ... +}]; +``` + +The Swift equivalent would be: + +```swift +queue.inTransaction { db, rollback in + do { + try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [1]) + try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [2]) + try db.executeUpdate("INSERT INTO myTable VALUES (?)", values: [3]) + + if whoopsSomethingWrongHappened { + rollback.pointee = true + return + } + + // etc ... + } catch { + rollback.pointee = true + print(error) + } +} +``` + +(Note, as of Swift 3, use `pointee`. But in Swift 2.3, use `memory` rather than `pointee`.) + +`FMDatabaseQueue` will run the blocks on a serialized queue (hence the name of the class). So if you call `FMDatabaseQueue`'s methods from multiple threads at the same time, they will be executed in the order they are received. This way queries and updates won't step on each other's toes, and every one is happy. + +**Note:** The calls to `FMDatabaseQueue`'s methods are blocking. So even though you are passing along blocks, they will **not** be run on another thread. + +## Making custom sqlite functions, based on blocks. + +You can do this! For an example, look for `-makeFunctionNamed:` in main.m + +## Swift + +You can use FMDB in Swift projects too. + +To do this, you must: + +1. Copy the relevant `.m` and `.h` files from the FMDB `src` folder into your project. + + You can copy all of them (which is easiest), or only the ones you need. Likely you will need [`FMDatabase`](http://ccgus.github.io/fmdb/html/Classes/FMDatabase.html) and [`FMResultSet`](http://ccgus.github.io/fmdb/html/Classes/FMResultSet.html) at a minimum. [`FMDatabaseAdditions`](http://ccgus.github.io/fmdb/html/Categories/FMDatabase+FMDatabaseAdditions.html) provides some very useful convenience methods, so you will likely want that, too. If you are doing multithreaded access to a database, [`FMDatabaseQueue`](http://ccgus.github.io/fmdb/html/Classes/FMDatabaseQueue.html) is quite useful, too. If you choose to not copy all of the files from the `src` directory, though, you may want to update `FMDB.h` to only reference the files that you included in your project. + + Note, if you're copying all of the files from the `src` folder into to your project (which is recommended), you may want to drag the individual files into your project, not the folder, itself, because if you drag the folder, you won't be prompted to add the bridging header (see next point). + +2. If prompted to create a "bridging header", you should do so. If not prompted and if you don't already have a bridging header, add one. + + For more information on bridging headers, see [Swift and Objective-C in the Same Project](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_76). + +3. In your bridging header, add a line that says: + ```objc + #import "FMDB.h" + ``` + +4. Use the variations of `executeQuery` and `executeUpdate` with the `sql` and `values` parameters with `try` pattern, as shown below. These renditions of `executeQuery` and `executeUpdate` both `throw` errors in true Swift fashion. + +If you do the above, you can then write Swift code that uses `FMDatabase`. For example, as of Swift 3: + +```swift +let fileURL = try! FileManager.default + .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) + .appendingPathComponent("test.sqlite") + +let database = FMDatabase(url: fileURL) + +guard database.open() else { + print("Unable to open database") + return +} + +do { + try database.executeUpdate("create table test(x text, y text, z text)", values: nil) + try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["a", "b", "c"]) + try database.executeUpdate("insert into test (x, y, z) values (?, ?, ?)", values: ["e", "f", "g"]) + + let rs = try database.executeQuery("select x, y, z from test", values: nil) + while rs.next() { + if let x = rs.string(forColumn: "x"), let y = rs.string(forColumn: "y"), let z = rs.string(forColumn: "z") { + print("x = \(x); y = \(y); z = \(z)") + } + } +} catch { + print("failed: \(error.localizedDescription)") +} + +database.close() +``` + +## History + +The history and changes are availbe on its [GitHub page](https://github.com/ccgus/fmdb) and are summarized in the "CHANGES_AND_TODO_LIST.txt" file. + +## Contributors + +The contributors to FMDB are contained in the "Contributors.txt" file. + +## Additional projects using FMDB, which might be interesting to the discerning developer. + + * FMDBMigrationManager, A SQLite schema migration management system for FMDB: https://github.com/layerhq/FMDBMigrationManager + * FCModel, An alternative to Core Data for people who like having direct SQL access: https://github.com/marcoarment/FCModel + +## Quick notes on FMDB's coding style + +Spaces, not tabs. Square brackets, not dot notation. Look at what FMDB already does with curly brackets and such, and stick to that style. + +## Reporting bugs + +Reduce your bug down to the smallest amount of code possible. You want to make it super easy for the developers to see and reproduce your bug. If it helps, pretend that the person who can fix your bug is active on shipping 3 major products, works on a handful of open source projects, has a newborn baby, and is generally very very busy. + +And we've even added a template function to main.m (FMDBReportABugFunction) in the FMDB distribution to help you out: + +* Open up fmdb project in Xcode. +* Open up main.m and modify the FMDBReportABugFunction to reproduce your bug. + * Setup your table(s) in the code. + * Make your query or update(s). + * Add some assertions which demonstrate the bug. + +Then you can bring it up on the FMDB mailing list by showing your nice and compact FMDBReportABugFunction, or you can report the bug via the github FMDB bug reporter. + +**Optional:** + +Figure out where the bug is, fix it, and send a patch in or bring that up on the mailing list. Make sure all the other tests run after your modifications. + +## Support + +The support channels for FMDB are the mailing list (see above), filing a bug here, or maybe on Stack Overflow. So that is to say, support is provided by the community and on a voluntary basis. + +FMDB development is overseen by Gus Mueller of Flying Meat. If FMDB been helpful to you, consider purchasing an app from FM or telling all your friends about it. + +## License + +The license for FMDB is contained in the "License.txt" file. + +If you happen to come across either Gus Mueller or Rob Ryan in a bar, you might consider purchasing a drink of their choosing if FMDB has been useful to you. + +(The drink is for them of course, shame on you for trying to keep it.) diff --git a/Pods/FMDB/src/fmdb/FMDB.h b/Pods/FMDB/src/fmdb/FMDB.h new file mode 100644 index 0000000..1ff5465 --- /dev/null +++ b/Pods/FMDB/src/fmdb/FMDB.h @@ -0,0 +1,10 @@ +#import + +FOUNDATION_EXPORT double FMDBVersionNumber; +FOUNDATION_EXPORT const unsigned char FMDBVersionString[]; + +#import "FMDatabase.h" +#import "FMResultSet.h" +#import "FMDatabaseAdditions.h" +#import "FMDatabaseQueue.h" +#import "FMDatabasePool.h" diff --git a/Pods/FMDB/src/fmdb/FMDatabase.h b/Pods/FMDB/src/fmdb/FMDatabase.h new file mode 100644 index 0000000..b779d54 --- /dev/null +++ b/Pods/FMDB/src/fmdb/FMDatabase.h @@ -0,0 +1,1360 @@ +#import +#import "FMResultSet.h" +#import "FMDatabasePool.h" + +NS_ASSUME_NONNULL_BEGIN + +#if ! __has_feature(objc_arc) + #define FMDBAutorelease(__v) ([__v autorelease]); + #define FMDBReturnAutoreleased FMDBAutorelease + + #define FMDBRetain(__v) ([__v retain]); + #define FMDBReturnRetained FMDBRetain + + #define FMDBRelease(__v) ([__v release]); + + #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v)); +#else + // -fobjc-arc + #define FMDBAutorelease(__v) + #define FMDBReturnAutoreleased(__v) (__v) + + #define FMDBRetain(__v) + #define FMDBReturnRetained(__v) (__v) + + #define FMDBRelease(__v) + +// If OS_OBJECT_USE_OBJC=1, then the dispatch objects will be treated like ObjC objects +// and will participate in ARC. +// See the section on "Dispatch Queues and Automatic Reference Counting" in "Grand Central Dispatch (GCD) Reference" for details. + #if OS_OBJECT_USE_OBJC + #define FMDBDispatchQueueRelease(__v) + #else + #define FMDBDispatchQueueRelease(__v) (dispatch_release(__v)); + #endif +#endif + +#if !__has_feature(objc_instancetype) + #define instancetype id +#endif + + +typedef int(^FMDBExecuteStatementsCallbackBlock)(NSDictionary *resultsDictionary); + + +/** A SQLite ([http://sqlite.org/](http://sqlite.org/)) Objective-C wrapper. + + ### Usage + The three main classes in FMDB are: + + - `FMDatabase` - Represents a single SQLite database. Used for executing SQL statements. + - `` - Represents the results of executing a query on an `FMDatabase`. + - `` - If you want to perform queries and updates on multiple threads, you'll want to use this class. + + ### See also + + - `` - A pool of `FMDatabase` objects. + - `` - A wrapper for `sqlite_stmt`. + + ### External links + + - [FMDB on GitHub](https://github.com/ccgus/fmdb) including introductory documentation + - [SQLite web site](http://sqlite.org/) + - [FMDB mailing list](http://groups.google.com/group/fmdb) + - [SQLite FAQ](http://www.sqlite.org/faq.html) + + @warning Do not instantiate a single `FMDatabase` object and use it across multiple threads. Instead, use ``. + + */ + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wobjc-interface-ivars" + + +@interface FMDatabase : NSObject + +///----------------- +/// @name Properties +///----------------- + +/** Whether should trace execution */ + +@property (atomic, assign) BOOL traceExecution; + +/** Whether checked out or not */ + +@property (atomic, assign) BOOL checkedOut; + +/** Crash on errors */ + +@property (atomic, assign) BOOL crashOnErrors; + +/** Logs errors */ + +@property (atomic, assign) BOOL logsErrors; + +/** Dictionary of cached statements */ + +@property (atomic, retain, nullable) NSMutableDictionary *cachedStatements; + +///--------------------- +/// @name Initialization +///--------------------- + +/** Create a `FMDatabase` object. + + An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: + + 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. + 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed. + 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. + + For example, to create/open a database in your Mac OS X `tmp` folder: + + FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; + + Or, in iOS, you might open a database in the app's `Documents` directory: + + NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; + NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; + FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; + + (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) + + @param inPath Path of database file + + @return `FMDatabase` object if successful; `nil` if failure. + + */ + ++ (instancetype)databaseWithPath:(NSString * _Nullable)inPath; + +/** Create a `FMDatabase` object. + + An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: + + 1. A file system URL. The file does not have to exist on disk. If it does not exist, it is created for you. + 2. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. + + For example, to create/open a database in your Mac OS X `tmp` folder: + + FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; + + Or, in iOS, you might open a database in the app's `Documents` directory: + + NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; + NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; + FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; + + (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) + + @param url The local file URL (not remote URL) of database file + + @return `FMDatabase` object if successful; `nil` if failure. + + */ + ++ (instancetype)databaseWithURL:(NSURL * _Nullable)url; + +/** Initialize a `FMDatabase` object. + + An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three: + + 1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you. + 2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed. + 3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. + + For example, to create/open a database in your Mac OS X `tmp` folder: + + FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; + + Or, in iOS, you might open a database in the app's `Documents` directory: + + NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; + NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; + FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; + + (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) + + @param path Path of database file. + + @return `FMDatabase` object if successful; `nil` if failure. + + */ + +- (instancetype)initWithPath:(NSString * _Nullable)path; + +/** Initialize a `FMDatabase` object. + + An `FMDatabase` is created with a local file URL to a SQLite database file. This path can be one of these three: + + 1. A file system URL. The file does not have to exist on disk. If it does not exist, it is created for you. + 2. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed. + + For example, to create/open a database in your Mac OS X `tmp` folder: + + FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"]; + + Or, in iOS, you might open a database in the app's `Documents` directory: + + NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; + NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"]; + FMDatabase *db = [FMDatabase databaseWithPath:dbPath]; + + (For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html)) + + @param url The file `NSURL` of database file. + + @return `FMDatabase` object if successful; `nil` if failure. + + */ + +- (instancetype)initWithURL:(NSURL * _Nullable)url; + +///----------------------------------- +/// @name Opening and closing database +///----------------------------------- + +/** Opening a new database connection + + The database is opened for reading and writing, and is created if it does not already exist. + + @return `YES` if successful, `NO` on error. + + @see [sqlite3_open()](http://sqlite.org/c3ref/open.html) + @see openWithFlags: + @see close + */ + +- (BOOL)open; + +/** Opening a new database connection with flags and an optional virtual file system (VFS) + + @param flags one of the following three values, optionally combined with the `SQLITE_OPEN_NOMUTEX`, `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, `SQLITE_OPEN_PRIVATECACHE`, and/or `SQLITE_OPEN_URI` flags: + + `SQLITE_OPEN_READONLY` + + The database is opened in read-only mode. If the database does not already exist, an error is returned. + + `SQLITE_OPEN_READWRITE` + + The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned. + + `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE` + + The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for `open` method. + + @return `YES` if successful, `NO` on error. + + @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html) + @see open + @see close + */ + +- (BOOL)openWithFlags:(int)flags; + +/** Opening a new database connection with flags and an optional virtual file system (VFS) + + @param flags one of the following three values, optionally combined with the `SQLITE_OPEN_NOMUTEX`, `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, `SQLITE_OPEN_PRIVATECACHE`, and/or `SQLITE_OPEN_URI` flags: + + `SQLITE_OPEN_READONLY` + + The database is opened in read-only mode. If the database does not already exist, an error is returned. + + `SQLITE_OPEN_READWRITE` + + The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned. + + `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE` + + The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for `open` method. + + @param vfsName If vfs is given the value is passed to the vfs parameter of sqlite3_open_v2. + + @return `YES` if successful, `NO` on error. + + @see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html) + @see open + @see close + */ + +- (BOOL)openWithFlags:(int)flags vfs:(NSString * _Nullable)vfsName; + +/** Closing a database connection + + @return `YES` if success, `NO` on error. + + @see [sqlite3_close()](http://sqlite.org/c3ref/close.html) + @see open + @see openWithFlags: + */ + +- (BOOL)close; + +/** Test to see if we have a good connection to the database. + + This will confirm whether: + + - is database open + - if open, it will try a simple SELECT statement and confirm that it succeeds. + + @return `YES` if everything succeeds, `NO` on failure. + */ + +@property (nonatomic, readonly) BOOL goodConnection; + + +///---------------------- +/// @name Perform updates +///---------------------- + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param outErr A reference to the `NSError` pointer to be updated with an auto released `NSError` object if an error if an error occurs. If `nil`, no `NSError` object will be returned. + + @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) + */ + +- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError * _Nullable *)outErr, ...; + +/** Execute single update statement + + @see executeUpdate:withErrorAndBindings: + + @warning **Deprecated**: Please use `` instead. + */ + +- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError * _Nullable*)outErr, ... __deprecated_msg("Use executeUpdate:withErrorAndBindings: instead");; + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) + + @note This technique supports the use of `?` placeholders in the SQL, automatically binding any supplied value parameters to those placeholders. This approach is more robust than techniques that entail using `stringWithFormat` to manually build SQL statements, which can be problematic if the values happened to include any characters that needed to be quoted. + + @note You cannot use this method from Swift due to incompatibilities between Swift and Objective-C variadic implementations. Consider using `` instead. + */ + +- (BOOL)executeUpdate:(NSString*)sql, ...; + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. Do not use `?` placeholders in the SQL if you use this method. + + @param format The SQL to be performed, with `printf`-style escape sequences. + + @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see executeUpdate: + @see lastError + @see lastErrorCode + @see lastErrorMessage + + @note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command + + [db executeUpdateWithFormat:@"INSERT INTO test (name) VALUES (%@)", @"Gus"]; + + is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `` + + [db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"]; + + There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `VALUES` clause was _not_ `VALUES ('%@')` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `VALUES (%@)`. + */ + +- (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2); + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see executeUpdate:values:error: + @see lastError + @see lastErrorCode + @see lastErrorMessage + */ + +- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments; + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + This is similar to ``, except that this also accepts a pointer to a `NSError` pointer, so that errors can be returned. + + In Swift, this throws errors, as if it were defined as follows: + + `func executeUpdate(sql: String, values: [Any]?) throws -> Bool` + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param values A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @param error A `NSError` object to receive any error object (if any). + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + + */ + +- (BOOL)executeUpdate:(NSString*)sql values:(NSArray * _Nullable)values error:(NSError * _Nullable __autoreleasing *)error; + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage +*/ + +- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments; + + +/** Execute single update statement + + This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. + + The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method. + + @param sql The SQL to be performed, with optional `?` placeholders. + + @param args A `va_list` of arguments. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + */ + +- (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args; + +/** Execute multiple SQL statements + + This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`. + + @param sql The SQL to be performed + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see executeStatements:withResultBlock: + @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html) + + */ + +- (BOOL)executeStatements:(NSString *)sql; + +/** Execute multiple SQL statements with callback handler + + This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`. + + @param sql The SQL to be performed. + @param block A block that will be called for any result sets returned by any SQL statements. + Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use SQLITE_OK), + non-zero value upon failure (which will stop the bulk execution of the SQL). If a statement returns values, the block will be called with the results from the query in NSDictionary *resultsDictionary. + This may be `nil` if you don't care to receive any results. + + @return `YES` upon success; `NO` upon failure. If failed, you can call ``, + ``, or `` for diagnostic information regarding the failure. + + @see executeStatements: + @see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html) + + */ + +- (BOOL)executeStatements:(NSString *)sql withResultBlock:(__attribute__((noescape)) FMDBExecuteStatementsCallbackBlock _Nullable)block; + +/** Last insert rowid + + Each entry in an SQLite table has a unique 64-bit signed integer key called the "rowid". The rowid is always available as an undeclared column named `ROWID`, `OID`, or `_ROWID_` as long as those names are not also used by explicitly declared columns. If the table has a column of type `INTEGER PRIMARY KEY` then that column is another alias for the rowid. + + This routine returns the rowid of the most recent successful `INSERT` into the database from the database connection in the first argument. As of SQLite version 3.7.7, this routines records the last insert rowid of both ordinary tables and virtual tables. If no successful `INSERT`s have ever occurred on that database connection, zero is returned. + + @return The rowid of the last inserted row. + + @see [sqlite3_last_insert_rowid()](http://sqlite.org/c3ref/last_insert_rowid.html) + + */ + +@property (nonatomic, readonly) int64_t lastInsertRowId; + +/** The number of rows changed by prior SQL statement. + + This function returns the number of database rows that were changed or inserted or deleted by the most recently completed SQL statement on the database connection specified by the first parameter. Only changes that are directly specified by the INSERT, UPDATE, or DELETE statement are counted. + + @return The number of rows changed by prior SQL statement. + + @see [sqlite3_changes()](http://sqlite.org/c3ref/changes.html) + + */ + +@property (nonatomic, readonly) int changes; + + +///------------------------- +/// @name Retrieving results +///------------------------- + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. + + This method employs [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) for any optional value parameters. This properly escapes any characters that need escape sequences (e.g. quotation marks), which eliminates simple SQL errors as well as protects against SQL injection attacks. This method natively handles `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects. All other object types will be interpreted as text values using the object's `description` method. + + @param sql The SELECT statement to be performed, with optional `?` placeholders. + + @param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.). + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + @see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) + + @note You cannot use this method from Swift due to incompatibilities between Swift and Objective-C variadic implementations. Consider using `` instead. + */ + +- (FMResultSet * _Nullable)executeQuery:(NSString*)sql, ...; + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. + + @param format The SQL to be performed, with `printf`-style escape sequences. + + @param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement. + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see executeQuery: + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + + @note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command + + [db executeQueryWithFormat:@"SELECT * FROM test WHERE name=%@", @"Gus"]; + + is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `` + + [db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"]; + + There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `WHERE` clause was _not_ `WHERE name='%@'` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `WHERE name=%@`. + + */ + +- (FMResultSet * _Nullable)executeQueryWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2); + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. + + @param sql The SELECT statement to be performed, with optional `?` placeholders. + + @param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see -executeQuery:values:error: + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + */ + +- (FMResultSet * _Nullable)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments; + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. + + This is similar to ``, except that this also accepts a pointer to a `NSError` pointer, so that errors can be returned. + + In Swift, this throws errors, as if it were defined as follows: + + `func executeQuery(sql: String, values: [Any]?) throws -> FMResultSet!` + + @param sql The SELECT statement to be performed, with optional `?` placeholders. + + @param values A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement. + + @param error A `NSError` object to receive any error object (if any). + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + + @note When called from Swift, only use the first two parameters, `sql` and `values`. This but throws the error. + + */ + +- (FMResultSet * _Nullable)executeQuery:(NSString *)sql values:(NSArray * _Nullable)values error:(NSError * _Nullable __autoreleasing *)error; + +/** Execute select statement + + Executing queries returns an `` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `` and `` methods to determine why a query failed. + + In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other. + + @param sql The SELECT statement to be performed, with optional `?` placeholders. + + @param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement. + + @return A `` for the result set upon success; `nil` upon failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see FMResultSet + @see [`FMResultSet next`](<[FMResultSet next]>) + */ + +- (FMResultSet * _Nullable)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary * _Nullable)arguments; + + +// Documentation forthcoming. +- (FMResultSet * _Nullable)executeQuery:(NSString *)sql withVAList:(va_list)args; + +///------------------- +/// @name Transactions +///------------------- + +/** Begin a transaction + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see commit + @see rollback + @see beginDeferredTransaction + @see isInTransaction + */ + +- (BOOL)beginTransaction; + +/** Begin a deferred transaction + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see commit + @see rollback + @see beginTransaction + @see isInTransaction + */ + +- (BOOL)beginDeferredTransaction; + +/** Commit a transaction + + Commit a transaction that was initiated with either `` or with ``. + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see beginTransaction + @see beginDeferredTransaction + @see rollback + @see isInTransaction + */ + +- (BOOL)commit; + +/** Rollback a transaction + + Rollback a transaction that was initiated with either `` or with ``. + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see beginTransaction + @see beginDeferredTransaction + @see commit + @see isInTransaction + */ + +- (BOOL)rollback; + +/** Identify whether currently in a transaction or not + + @see beginTransaction + @see beginDeferredTransaction + @see commit + @see rollback + */ + +@property (nonatomic, readonly) BOOL isInTransaction; + +- (BOOL)inTransaction __deprecated_msg("Use isInTransaction property instead"); + + +///---------------------------------------- +/// @name Cached statements and result sets +///---------------------------------------- + +/** Clear cached statements */ + +- (void)clearCachedStatements; + +/** Close all open result sets */ + +- (void)closeOpenResultSets; + +/** Whether database has any open result sets + + @return `YES` if there are open result sets; `NO` if not. + */ + +@property (nonatomic, readonly) BOOL hasOpenResultSets; + +/** Whether should cache statements or not + */ + +@property (nonatomic) BOOL shouldCacheStatements; + +/** Interupt pending database operation + + This method causes any pending database operation to abort and return at its earliest opportunity + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + */ + +- (BOOL)interrupt; + +///------------------------- +/// @name Encryption methods +///------------------------- + +/** Set encryption key. + + @param key The key to be used. + + @return `YES` if success, `NO` on error. + + @see https://www.zetetic.net/sqlcipher/ + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)setKey:(NSString*)key; + +/** Reset encryption key + + @param key The key to be used. + + @return `YES` if success, `NO` on error. + + @see https://www.zetetic.net/sqlcipher/ + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)rekey:(NSString*)key; + +/** Set encryption key using `keyData`. + + @param keyData The `NSData` to be used. + + @return `YES` if success, `NO` on error. + + @see https://www.zetetic.net/sqlcipher/ + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)setKeyWithData:(NSData *)keyData; + +/** Reset encryption key using `keyData`. + + @param keyData The `NSData` to be used. + + @return `YES` if success, `NO` on error. + + @see https://www.zetetic.net/sqlcipher/ + + @warning You need to have purchased the sqlite encryption extensions for this method to work. + */ + +- (BOOL)rekeyWithData:(NSData *)keyData; + + +///------------------------------ +/// @name General inquiry methods +///------------------------------ + +/** The path of the database file + */ + +@property (nonatomic, readonly, nullable) NSString *databasePath; + +/** The file URL of the database file. + */ + +@property (nonatomic, readonly, nullable) NSURL *databaseURL; + +/** The underlying SQLite handle + + @return The `sqlite3` pointer. + + */ + +@property (nonatomic, readonly) void *sqliteHandle; + + +///----------------------------- +/// @name Retrieving error codes +///----------------------------- + +/** Last error message + + Returns the English-language text that describes the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. + + @return `NSString` of the last error message. + + @see [sqlite3_errmsg()](http://sqlite.org/c3ref/errcode.html) + @see lastErrorCode + @see lastError + + */ + +- (NSString*)lastErrorMessage; + +/** Last error code + + Returns the numeric result code or extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. + + @return Integer value of the last error code. + + @see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html) + @see lastErrorMessage + @see lastError + + */ + +- (int)lastErrorCode; + +/** Last extended error code + + Returns the numeric extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined. + + @return Integer value of the last extended error code. + + @see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html) + @see [2. Primary Result Codes versus Extended Result Codes](http://sqlite.org/rescode.html#primary_result_codes_versus_extended_result_codes) + @see [5. Extended Result Code List](http://sqlite.org/rescode.html#extrc) + @see lastErrorMessage + @see lastError + + */ + +- (int)lastExtendedErrorCode; + +/** Had error + + @return `YES` if there was an error, `NO` if no error. + + @see lastError + @see lastErrorCode + @see lastErrorMessage + + */ + +- (BOOL)hadError; + +/** Last error + + @return `NSError` representing the last error. + + @see lastErrorCode + @see lastErrorMessage + + */ + +- (NSError *)lastError; + + +// description forthcoming +@property (nonatomic) NSTimeInterval maxBusyRetryTimeInterval; + + +///------------------ +/// @name Save points +///------------------ + +/** Start save point + + @param name Name of save point. + + @param outErr A `NSError` object to receive any error object (if any). + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see releaseSavePointWithName:error: + @see rollbackToSavePointWithName:error: + */ + +- (BOOL)startSavePointWithName:(NSString*)name error:(NSError * _Nullable *)outErr; + +/** Release save point + + @param name Name of save point. + + @param outErr A `NSError` object to receive any error object (if any). + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see startSavePointWithName:error: + @see rollbackToSavePointWithName:error: + + */ + +- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError * _Nullable *)outErr; + +/** Roll back to save point + + @param name Name of save point. + @param outErr A `NSError` object to receive any error object (if any). + + @return `YES` on success; `NO` on failure. If failed, you can call ``, ``, or `` for diagnostic information regarding the failure. + + @see startSavePointWithName:error: + @see releaseSavePointWithName:error: + + */ + +- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError * _Nullable *)outErr; + +/** Start save point + + @param block Block of code to perform from within save point. + + @return The NSError corresponding to the error, if any. If no error, returns `nil`. + + @see startSavePointWithName:error: + @see releaseSavePointWithName:error: + @see rollbackToSavePointWithName:error: + + */ + +- (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(BOOL *rollback))block; + +///---------------------------- +/// @name SQLite library status +///---------------------------- + +/** Test to see if the library is threadsafe + + @return `NO` if and only if SQLite was compiled with mutexing code omitted due to the SQLITE_THREADSAFE compile-time option being set to 0. + + @see [sqlite3_threadsafe()](http://sqlite.org/c3ref/threadsafe.html) + */ + ++ (BOOL)isSQLiteThreadSafe; + +/** Run-time library version numbers + + @return The sqlite library version string. + + @see [sqlite3_libversion()](http://sqlite.org/c3ref/libversion.html) + */ + ++ (NSString*)sqliteLibVersion; + + ++ (NSString*)FMDBUserVersion; + ++ (SInt32)FMDBVersion; + + +///------------------------ +/// @name Make SQL function +///------------------------ + +/** Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates. + + For example: + + [db makeFunctionNamed:@"RemoveDiacritics" arguments:1 block:^(void *context, int argc, void **argv) { + SqliteValueType type = [self.db valueType:argv[0]]; + if (type == SqliteValueTypeNull) { + [self.db resultNullInContext:context]; + return; + } + if (type != SqliteValueTypeText) { + [self.db resultError:@"Expected text" context:context]; + return; + } + NSString *string = [self.db valueString:argv[0]]; + NSString *result = [string stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:nil]; + [self.db resultString:result context:context]; + }]; + + FMResultSet *rs = [db executeQuery:@"SELECT * FROM employees WHERE RemoveDiacritics(first_name) LIKE 'jose'"]; + NSAssert(rs, @"Error %@", [db lastErrorMessage]); + + @param name Name of function. + + @param arguments Maximum number of parameters. + + @param block The block of code for the function. + + @see [sqlite3_create_function()](http://sqlite.org/c3ref/create_function.html) + */ + +- (void)makeFunctionNamed:(NSString *)name arguments:(int)arguments block:(void (^)(void *context, int argc, void * _Nonnull * _Nonnull argv))block; + +- (void)makeFunctionNamed:(NSString *)name maximumArguments:(int)count withBlock:(void (^)(void *context, int argc, void * _Nonnull * _Nonnull argv))block __deprecated_msg("Use makeFunctionNamed:arguments:block:"); + +typedef NS_ENUM(int, SqliteValueType) { + SqliteValueTypeInteger = 1, + SqliteValueTypeFloat = 2, + SqliteValueTypeText = 3, + SqliteValueTypeBlob = 4, + SqliteValueTypeNull = 5 +}; + +- (SqliteValueType)valueType:(void *)argv; + +/** + Get integer value of parameter in custom function. + + @param value The argument whose value to return. + @return The integer value. + + @see makeFunctionNamed:arguments:block: + */ +- (int)valueInt:(void *)value; + +/** + Get long value of parameter in custom function. + + @param value The argument whose value to return. + @return The long value. + + @see makeFunctionNamed:arguments:block: + */ +- (long long)valueLong:(void *)value; + +/** + Get double value of parameter in custom function. + + @param value The argument whose value to return. + @return The double value. + + @see makeFunctionNamed:arguments:block: + */ +- (double)valueDouble:(void *)value; + +/** + Get `NSData` value of parameter in custom function. + + @param value The argument whose value to return. + @return The data object. + + @see makeFunctionNamed:arguments:block: + */ +- (NSData * _Nullable)valueData:(void *)value; + +/** + Get string value of parameter in custom function. + + @param value The argument whose value to return. + @return The string value. + + @see makeFunctionNamed:arguments:block: + */ +- (NSString * _Nullable)valueString:(void *)value; + +/** + Return null value from custom function. + + @param context The context to which the null value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultNullInContext:(void *)context NS_SWIFT_NAME(resultNull(context:)); + +/** + Return integer value from custom function. + + @param value The integer value to be returned. + @param context The context to which the value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultInt:(int) value context:(void *)context; + +/** + Return long value from custom function. + + @param value The long value to be returned. + @param context The context to which the value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultLong:(long long)value context:(void *)context; + +/** + Return double value from custom function. + + @param value The double value to be returned. + @param context The context to which the value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultDouble:(double)value context:(void *)context; + +/** + Return `NSData` object from custom function. + + @param data The `NSData` object to be returned. + @param context The context to which the value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultData:(NSData *)data context:(void *)context; + +/** + Return string value from custom function. + + @param value The string value to be returned. + @param context The context to which the value will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultString:(NSString *)value context:(void *)context; + +/** + Return error string from custom function. + + @param error The error string to be returned. + @param context The context to which the error will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultError:(NSString *)error context:(void *)context; + +/** + Return error code from custom function. + + @param errorCode The integer error code to be returned. + @param context The context to which the error will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultErrorCode:(int)errorCode context:(void *)context; + +/** + Report memory error in custom function. + + @param context The context to which the error will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultErrorNoMemoryInContext:(void *)context NS_SWIFT_NAME(resultErrorNoMemory(context:)); + +/** + Report that string or BLOB is too long to represent in custom function. + + @param context The context to which the error will be returned. + + @see makeFunctionNamed:arguments:block: + */ +- (void)resultErrorTooBigInContext:(void *)context NS_SWIFT_NAME(resultErrorTooBig(context:)); + +///--------------------- +/// @name Date formatter +///--------------------- + +/** Generate an `NSDateFormatter` that won't be broken by permutations of timezones or locales. + + Use this method to generate values to set the dateFormat property. + + Example: + + myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"]; + + @param format A valid NSDateFormatter format string. + + @return A `NSDateFormatter` that can be used for converting dates to strings and vice versa. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + + @warning Note that `NSDateFormatter` is not thread-safe, so the formatter generated by this method should be assigned to only one FMDB instance and should not be used for other purposes. + + */ + ++ (NSDateFormatter *)storeableDateFormat:(NSString *)format; + +/** Test whether the database has a date formatter assigned. + + @return `YES` if there is a date formatter; `NO` if not. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + */ + +- (BOOL)hasDateFormatter; + +/** Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps. + + @param format Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using FMDatabase::storeableDateFormat. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + + @warning Note there is no direct getter for the `NSDateFormatter`, and you should not use the formatter you pass to FMDB for other purposes, as `NSDateFormatter` is not thread-safe. + */ + +- (void)setDateFormat:(NSDateFormatter *)format; + +/** Convert the supplied NSString to NSDate, using the current database formatter. + + @param s `NSString` to convert to `NSDate`. + + @return The `NSDate` object; or `nil` if no formatter is set. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + */ + +- (NSDate * _Nullable)dateFromString:(NSString *)s; + +/** Convert the supplied NSDate to NSString, using the current database formatter. + + @param date `NSDate` of date to convert to `NSString`. + + @return The `NSString` representation of the date; `nil` if no formatter is set. + + @see hasDateFormatter + @see setDateFormat: + @see dateFromString: + @see stringFromDate: + @see storeableDateFormat: + */ + +- (NSString *)stringFromDate:(NSDate *)date; + +@end + + +/** Objective-C wrapper for `sqlite3_stmt` + + This is a wrapper for a SQLite `sqlite3_stmt`. Generally when using FMDB you will not need to interact directly with `FMStatement`, but rather with `` and `` only. + + ### See also + + - `` + - `` + - [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html) + */ + +@interface FMStatement : NSObject { + void *_statement; + NSString *_query; + long _useCount; + BOOL _inUse; +} + +///----------------- +/// @name Properties +///----------------- + +/** Usage count */ + +@property (atomic, assign) long useCount; + +/** SQL statement */ + +@property (atomic, retain) NSString *query; + +/** SQLite sqlite3_stmt + + @see [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html) + */ + +@property (atomic, assign) void *statement; + +/** Indication of whether the statement is in use */ + +@property (atomic, assign) BOOL inUse; + +///---------------------------- +/// @name Closing and Resetting +///---------------------------- + +/** Close statement */ + +- (void)close; + +/** Reset statement */ + +- (void)reset; + +@end + +#pragma clang diagnostic pop + +NS_ASSUME_NONNULL_END diff --git a/Pods/FMDB/src/fmdb/FMDatabase.m b/Pods/FMDB/src/fmdb/FMDatabase.m new file mode 100644 index 0000000..493e772 --- /dev/null +++ b/Pods/FMDB/src/fmdb/FMDatabase.m @@ -0,0 +1,1596 @@ +#import "FMDatabase.h" +#import "unistd.h" +#import + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +@interface FMDatabase () { + void* _db; + BOOL _isExecutingStatement; + NSTimeInterval _startBusyRetryTime; + + NSMutableSet *_openResultSets; + NSMutableSet *_openFunctions; + + NSDateFormatter *_dateFormat; +} + +NS_ASSUME_NONNULL_BEGIN + +- (FMResultSet * _Nullable)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args; +- (BOOL)executeUpdate:(NSString *)sql error:(NSError * _Nullable *)outErr withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args; + +NS_ASSUME_NONNULL_END + +@end + +@implementation FMDatabase + +// Because these two properties have all of their accessor methods implemented, +// we have to synthesize them to get the corresponding ivars. The rest of the +// properties have their ivars synthesized automatically for us. + +@synthesize shouldCacheStatements = _shouldCacheStatements; +@synthesize maxBusyRetryTimeInterval = _maxBusyRetryTimeInterval; + +#pragma mark FMDatabase instantiation and deallocation + ++ (instancetype)databaseWithPath:(NSString *)aPath { + return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]); +} + ++ (instancetype)databaseWithURL:(NSURL *)url { + return FMDBReturnAutoreleased([[self alloc] initWithURL:url]); +} + +- (instancetype)init { + return [self initWithPath:nil]; +} + +- (instancetype)initWithURL:(NSURL *)url { + return [self initWithPath:url.path]; +} + +- (instancetype)initWithPath:(NSString *)path { + + assert(sqlite3_threadsafe()); // whoa there big boy- gotta make sure sqlite it happy with what we're going to do. + + self = [super init]; + + if (self) { + _databasePath = [path copy]; + _openResultSets = [[NSMutableSet alloc] init]; + _db = nil; + _logsErrors = YES; + _crashOnErrors = NO; + _maxBusyRetryTimeInterval = 2; + } + + return self; +} + +#if ! __has_feature(objc_arc) +- (void)finalize { + [self close]; + [super finalize]; +} +#endif + +- (void)dealloc { + [self close]; + FMDBRelease(_openResultSets); + FMDBRelease(_cachedStatements); + FMDBRelease(_dateFormat); + FMDBRelease(_databasePath); + FMDBRelease(_openFunctions); + +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (NSURL *)databaseURL { + return _databasePath ? [NSURL fileURLWithPath:_databasePath] : nil; +} + ++ (NSString*)FMDBUserVersion { + return @"2.7.2"; +} + +// returns 0x0240 for version 2.4. This makes it super easy to do things like: +// /* need to make sure to do X with FMDB version 2.4 or later */ +// if ([FMDatabase FMDBVersion] >= 0x0240) { … } + ++ (SInt32)FMDBVersion { + + // we go through these hoops so that we only have to change the version number in a single spot. + static dispatch_once_t once; + static SInt32 FMDBVersionVal = 0; + + dispatch_once(&once, ^{ + NSString *prodVersion = [self FMDBUserVersion]; + + if ([[prodVersion componentsSeparatedByString:@"."] count] < 3) { + prodVersion = [prodVersion stringByAppendingString:@".0"]; + } + + NSString *junk = [prodVersion stringByReplacingOccurrencesOfString:@"." withString:@""]; + + char *e = nil; + FMDBVersionVal = (int) strtoul([junk UTF8String], &e, 16); + + }); + + return FMDBVersionVal; +} + +#pragma mark SQLite information + ++ (NSString*)sqliteLibVersion { + return [NSString stringWithFormat:@"%s", sqlite3_libversion()]; +} + ++ (BOOL)isSQLiteThreadSafe { + // make sure to read the sqlite headers on this guy! + return sqlite3_threadsafe() != 0; +} + +- (void*)sqliteHandle { + return _db; +} + +- (const char*)sqlitePath { + + if (!_databasePath) { + return ":memory:"; + } + + if ([_databasePath length] == 0) { + return ""; // this creates a temporary database (it's an sqlite thing). + } + + return [_databasePath fileSystemRepresentation]; + +} + +#pragma mark Open and close database + +- (BOOL)open { + if (_db) { + return YES; + } + + int err = sqlite3_open([self sqlitePath], (sqlite3**)&_db ); + if(err != SQLITE_OK) { + NSLog(@"error opening!: %d", err); + return NO; + } + + if (_maxBusyRetryTimeInterval > 0.0) { + // set the handler + [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval]; + } + + + return YES; +} + +- (BOOL)openWithFlags:(int)flags { + return [self openWithFlags:flags vfs:nil]; +} +- (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName { +#if SQLITE_VERSION_NUMBER >= 3005000 + if (_db) { + return YES; + } + + int err = sqlite3_open_v2([self sqlitePath], (sqlite3**)&_db, flags, [vfsName UTF8String]); + if(err != SQLITE_OK) { + NSLog(@"error opening!: %d", err); + return NO; + } + + if (_maxBusyRetryTimeInterval > 0.0) { + // set the handler + [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval]; + } + + return YES; +#else + NSLog(@"openWithFlags requires SQLite 3.5"); + return NO; +#endif +} + + +- (BOOL)close { + + [self clearCachedStatements]; + [self closeOpenResultSets]; + + if (!_db) { + return YES; + } + + int rc; + BOOL retry; + BOOL triedFinalizingOpenStatements = NO; + + do { + retry = NO; + rc = sqlite3_close(_db); + if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) { + if (!triedFinalizingOpenStatements) { + triedFinalizingOpenStatements = YES; + sqlite3_stmt *pStmt; + while ((pStmt = sqlite3_next_stmt(_db, nil)) !=0) { + NSLog(@"Closing leaked statement"); + sqlite3_finalize(pStmt); + retry = YES; + } + } + } + else if (SQLITE_OK != rc) { + NSLog(@"error closing!: %d", rc); + } + } + while (retry); + + _db = nil; + return YES; +} + +#pragma mark Busy handler routines + +// NOTE: appledoc seems to choke on this function for some reason; +// so when generating documentation, you might want to ignore the +// .m files so that it only documents the public interfaces outlined +// in the .h files. +// +// This is a known appledoc bug that it has problems with C functions +// within a class implementation, but for some reason, only this +// C function causes problems; the rest don't. Anyway, ignoring the .m +// files with appledoc will prevent this problem from occurring. + +static int FMDBDatabaseBusyHandler(void *f, int count) { + FMDatabase *self = (__bridge FMDatabase*)f; + + if (count == 0) { + self->_startBusyRetryTime = [NSDate timeIntervalSinceReferenceDate]; + return 1; + } + + NSTimeInterval delta = [NSDate timeIntervalSinceReferenceDate] - (self->_startBusyRetryTime); + + if (delta < [self maxBusyRetryTimeInterval]) { + int requestedSleepInMillseconds = (int) arc4random_uniform(50) + 50; + int actualSleepInMilliseconds = sqlite3_sleep(requestedSleepInMillseconds); + if (actualSleepInMilliseconds != requestedSleepInMillseconds) { + NSLog(@"WARNING: Requested sleep of %i milliseconds, but SQLite returned %i. Maybe SQLite wasn't built with HAVE_USLEEP=1?", requestedSleepInMillseconds, actualSleepInMilliseconds); + } + return 1; + } + + return 0; +} + +- (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeout { + + _maxBusyRetryTimeInterval = timeout; + + if (!_db) { + return; + } + + if (timeout > 0) { + sqlite3_busy_handler(_db, &FMDBDatabaseBusyHandler, (__bridge void *)(self)); + } + else { + // turn it off otherwise + sqlite3_busy_handler(_db, nil, nil); + } +} + +- (NSTimeInterval)maxBusyRetryTimeInterval { + return _maxBusyRetryTimeInterval; +} + + +// we no longer make busyRetryTimeout public +// but for folks who don't bother noticing that the interface to FMDatabase changed, +// we'll still implement the method so they don't get suprise crashes +- (int)busyRetryTimeout { + NSLog(@"%s:%d", __FUNCTION__, __LINE__); + NSLog(@"FMDB: busyRetryTimeout no longer works, please use maxBusyRetryTimeInterval"); + return -1; +} + +- (void)setBusyRetryTimeout:(int)i { +#pragma unused(i) + NSLog(@"%s:%d", __FUNCTION__, __LINE__); + NSLog(@"FMDB: setBusyRetryTimeout does nothing, please use setMaxBusyRetryTimeInterval:"); +} + +#pragma mark Result set functions + +- (BOOL)hasOpenResultSets { + return [_openResultSets count] > 0; +} + +- (void)closeOpenResultSets { + + //Copy the set so we don't get mutation errors + NSSet *openSetCopy = FMDBReturnAutoreleased([_openResultSets copy]); + for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) { + FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue]; + + [rs setParentDB:nil]; + [rs close]; + + [_openResultSets removeObject:rsInWrappedInATastyValueMeal]; + } +} + +- (void)resultSetDidClose:(FMResultSet *)resultSet { + NSValue *setValue = [NSValue valueWithNonretainedObject:resultSet]; + + [_openResultSets removeObject:setValue]; +} + +#pragma mark Cached statements + +- (void)clearCachedStatements { + + for (NSMutableSet *statements in [_cachedStatements objectEnumerator]) { + for (FMStatement *statement in [statements allObjects]) { + [statement close]; + } + } + + [_cachedStatements removeAllObjects]; +} + +- (FMStatement*)cachedStatementForQuery:(NSString*)query { + + NSMutableSet* statements = [_cachedStatements objectForKey:query]; + + return [[statements objectsPassingTest:^BOOL(FMStatement* statement, BOOL *stop) { + + *stop = ![statement inUse]; + return *stop; + + }] anyObject]; +} + + +- (void)setCachedStatement:(FMStatement*)statement forQuery:(NSString*)query { + + query = [query copy]; // in case we got handed in a mutable string... + [statement setQuery:query]; + + NSMutableSet* statements = [_cachedStatements objectForKey:query]; + if (!statements) { + statements = [NSMutableSet set]; + } + + [statements addObject:statement]; + + [_cachedStatements setObject:statements forKey:query]; + + FMDBRelease(query); +} + +#pragma mark Key routines + +- (BOOL)rekey:(NSString*)key { + NSData *keyData = [NSData dataWithBytes:(void *)[key UTF8String] length:(NSUInteger)strlen([key UTF8String])]; + + return [self rekeyWithData:keyData]; +} + +- (BOOL)rekeyWithData:(NSData *)keyData { +#ifdef SQLITE_HAS_CODEC + if (!keyData) { + return NO; + } + + int rc = sqlite3_rekey(_db, [keyData bytes], (int)[keyData length]); + + if (rc != SQLITE_OK) { + NSLog(@"error on rekey: %d", rc); + NSLog(@"%@", [self lastErrorMessage]); + } + + return (rc == SQLITE_OK); +#else +#pragma unused(keyData) + return NO; +#endif +} + +- (BOOL)setKey:(NSString*)key { + NSData *keyData = [NSData dataWithBytes:[key UTF8String] length:(NSUInteger)strlen([key UTF8String])]; + + return [self setKeyWithData:keyData]; +} + +- (BOOL)setKeyWithData:(NSData *)keyData { +#ifdef SQLITE_HAS_CODEC + if (!keyData) { + return NO; + } + + int rc = sqlite3_key(_db, [keyData bytes], (int)[keyData length]); + + return (rc == SQLITE_OK); +#else +#pragma unused(keyData) + return NO; +#endif +} + +#pragma mark Date routines + ++ (NSDateFormatter *)storeableDateFormat:(NSString *)format { + + NSDateFormatter *result = FMDBReturnAutoreleased([[NSDateFormatter alloc] init]); + result.dateFormat = format; + result.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; + result.locale = FMDBReturnAutoreleased([[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]); + return result; +} + + +- (BOOL)hasDateFormatter { + return _dateFormat != nil; +} + +- (void)setDateFormat:(NSDateFormatter *)format { + FMDBAutorelease(_dateFormat); + _dateFormat = FMDBReturnRetained(format); +} + +- (NSDate *)dateFromString:(NSString *)s { + return [_dateFormat dateFromString:s]; +} + +- (NSString *)stringFromDate:(NSDate *)date { + return [_dateFormat stringFromDate:date]; +} + +#pragma mark State of database + +- (BOOL)goodConnection { + + if (!_db) { + return NO; + } + + FMResultSet *rs = [self executeQuery:@"select name from sqlite_master where type='table'"]; + + if (rs) { + [rs close]; + return YES; + } + + return NO; +} + +- (void)warnInUse { + NSLog(@"The FMDatabase %@ is currently in use.", self); + +#ifndef NS_BLOCK_ASSERTIONS + if (_crashOnErrors) { + NSAssert(false, @"The FMDatabase %@ is currently in use.", self); + abort(); + } +#endif +} + +- (BOOL)databaseExists { + + if (!_db) { + + NSLog(@"The FMDatabase %@ is not open.", self); + +#ifndef NS_BLOCK_ASSERTIONS + if (_crashOnErrors) { + NSAssert(false, @"The FMDatabase %@ is not open.", self); + abort(); + } +#endif + + return NO; + } + + return YES; +} + +#pragma mark Error routines + +- (NSString *)lastErrorMessage { + return [NSString stringWithUTF8String:sqlite3_errmsg(_db)]; +} + +- (BOOL)hadError { + int lastErrCode = [self lastErrorCode]; + + return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW); +} + +- (int)lastErrorCode { + return sqlite3_errcode(_db); +} + +- (int)lastExtendedErrorCode { + return sqlite3_extended_errcode(_db); +} + +- (NSError*)errorWithMessage:(NSString *)message { + NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:message forKey:NSLocalizedDescriptionKey]; + + return [NSError errorWithDomain:@"FMDatabase" code:sqlite3_errcode(_db) userInfo:errorMessage]; +} + +- (NSError*)lastError { + return [self errorWithMessage:[self lastErrorMessage]]; +} + +#pragma mark Update information routines + +- (sqlite_int64)lastInsertRowId { + + if (_isExecutingStatement) { + [self warnInUse]; + return NO; + } + + _isExecutingStatement = YES; + + sqlite_int64 ret = sqlite3_last_insert_rowid(_db); + + _isExecutingStatement = NO; + + return ret; +} + +- (int)changes { + if (_isExecutingStatement) { + [self warnInUse]; + return 0; + } + + _isExecutingStatement = YES; + + int ret = sqlite3_changes(_db); + + _isExecutingStatement = NO; + + return ret; +} + +#pragma mark SQL manipulation + +- (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt { + + if ((!obj) || ((NSNull *)obj == [NSNull null])) { + sqlite3_bind_null(pStmt, idx); + } + + // FIXME - someday check the return codes on these binds. + else if ([obj isKindOfClass:[NSData class]]) { + const void *bytes = [obj bytes]; + if (!bytes) { + // it's an empty NSData object, aka [NSData data]. + // Don't pass a NULL pointer, or sqlite will bind a SQL null instead of a blob. + bytes = ""; + } + sqlite3_bind_blob(pStmt, idx, bytes, (int)[obj length], SQLITE_STATIC); + } + else if ([obj isKindOfClass:[NSDate class]]) { + if (self.hasDateFormatter) + sqlite3_bind_text(pStmt, idx, [[self stringFromDate:obj] UTF8String], -1, SQLITE_STATIC); + else + sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]); + } + else if ([obj isKindOfClass:[NSNumber class]]) { + + if (strcmp([obj objCType], @encode(char)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj charValue]); + } + else if (strcmp([obj objCType], @encode(unsigned char)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj unsignedCharValue]); + } + else if (strcmp([obj objCType], @encode(short)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj shortValue]); + } + else if (strcmp([obj objCType], @encode(unsigned short)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj unsignedShortValue]); + } + else if (strcmp([obj objCType], @encode(int)) == 0) { + sqlite3_bind_int(pStmt, idx, [obj intValue]); + } + else if (strcmp([obj objCType], @encode(unsigned int)) == 0) { + sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedIntValue]); + } + else if (strcmp([obj objCType], @encode(long)) == 0) { + sqlite3_bind_int64(pStmt, idx, [obj longValue]); + } + else if (strcmp([obj objCType], @encode(unsigned long)) == 0) { + sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongValue]); + } + else if (strcmp([obj objCType], @encode(long long)) == 0) { + sqlite3_bind_int64(pStmt, idx, [obj longLongValue]); + } + else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) { + sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongLongValue]); + } + else if (strcmp([obj objCType], @encode(float)) == 0) { + sqlite3_bind_double(pStmt, idx, [obj floatValue]); + } + else if (strcmp([obj objCType], @encode(double)) == 0) { + sqlite3_bind_double(pStmt, idx, [obj doubleValue]); + } + else if (strcmp([obj objCType], @encode(BOOL)) == 0) { + sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0)); + } + else { + sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC); + } + } + else { + sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC); + } +} + +- (void)extractSQL:(NSString *)sql argumentsList:(va_list)args intoString:(NSMutableString *)cleanedSQL arguments:(NSMutableArray *)arguments { + + NSUInteger length = [sql length]; + unichar last = '\0'; + for (NSUInteger i = 0; i < length; ++i) { + id arg = nil; + unichar current = [sql characterAtIndex:i]; + unichar add = current; + if (last == '%') { + switch (current) { + case '@': + arg = va_arg(args, id); + break; + case 'c': + // warning: second argument to 'va_arg' is of promotable type 'char'; this va_arg has undefined behavior because arguments will be promoted to 'int' + arg = [NSString stringWithFormat:@"%c", va_arg(args, int)]; + break; + case 's': + arg = [NSString stringWithUTF8String:va_arg(args, char*)]; + break; + case 'd': + case 'D': + case 'i': + arg = [NSNumber numberWithInt:va_arg(args, int)]; + break; + case 'u': + case 'U': + arg = [NSNumber numberWithUnsignedInt:va_arg(args, unsigned int)]; + break; + case 'h': + i++; + if (i < length && [sql characterAtIndex:i] == 'i') { + // warning: second argument to 'va_arg' is of promotable type 'short'; this va_arg has undefined behavior because arguments will be promoted to 'int' + arg = [NSNumber numberWithShort:(short)(va_arg(args, int))]; + } + else if (i < length && [sql characterAtIndex:i] == 'u') { + // warning: second argument to 'va_arg' is of promotable type 'unsigned short'; this va_arg has undefined behavior because arguments will be promoted to 'int' + arg = [NSNumber numberWithUnsignedShort:(unsigned short)(va_arg(args, uint))]; + } + else { + i--; + } + break; + case 'q': + i++; + if (i < length && [sql characterAtIndex:i] == 'i') { + arg = [NSNumber numberWithLongLong:va_arg(args, long long)]; + } + else if (i < length && [sql characterAtIndex:i] == 'u') { + arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)]; + } + else { + i--; + } + break; + case 'f': + arg = [NSNumber numberWithDouble:va_arg(args, double)]; + break; + case 'g': + // warning: second argument to 'va_arg' is of promotable type 'float'; this va_arg has undefined behavior because arguments will be promoted to 'double' + arg = [NSNumber numberWithFloat:(float)(va_arg(args, double))]; + break; + case 'l': + i++; + if (i < length) { + unichar next = [sql characterAtIndex:i]; + if (next == 'l') { + i++; + if (i < length && [sql characterAtIndex:i] == 'd') { + //%lld + arg = [NSNumber numberWithLongLong:va_arg(args, long long)]; + } + else if (i < length && [sql characterAtIndex:i] == 'u') { + //%llu + arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)]; + } + else { + i--; + } + } + else if (next == 'd') { + //%ld + arg = [NSNumber numberWithLong:va_arg(args, long)]; + } + else if (next == 'u') { + //%lu + arg = [NSNumber numberWithUnsignedLong:va_arg(args, unsigned long)]; + } + else { + i--; + } + } + else { + i--; + } + break; + default: + // something else that we can't interpret. just pass it on through like normal + break; + } + } + else if (current == '%') { + // percent sign; skip this character + add = '\0'; + } + + if (arg != nil) { + [cleanedSQL appendString:@"?"]; + [arguments addObject:arg]; + } + else if (add == (unichar)'@' && last == (unichar) '%') { + [cleanedSQL appendFormat:@"NULL"]; + } + else if (add != '\0') { + [cleanedSQL appendFormat:@"%C", add]; + } + last = current; + } +} + +#pragma mark Execute queries + +- (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments { + return [self executeQuery:sql withArgumentsInArray:nil orDictionary:arguments orVAList:nil]; +} + +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args { + + if (![self databaseExists]) { + return 0x00; + } + + if (_isExecutingStatement) { + [self warnInUse]; + return 0x00; + } + + _isExecutingStatement = YES; + + int rc = 0x00; + sqlite3_stmt *pStmt = 0x00; + FMStatement *statement = 0x00; + FMResultSet *rs = 0x00; + + if (_traceExecution && sql) { + NSLog(@"%@ executeQuery: %@", self, sql); + } + + if (_shouldCacheStatements) { + statement = [self cachedStatementForQuery:sql]; + pStmt = statement ? [statement statement] : 0x00; + [statement reset]; + } + + if (!pStmt) { + + rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0); + + if (SQLITE_OK != rc) { + if (_logsErrors) { + NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); + NSLog(@"DB Query: %@", sql); + NSLog(@"DB Path: %@", _databasePath); + } + + if (_crashOnErrors) { + NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); + abort(); + } + + sqlite3_finalize(pStmt); + _isExecutingStatement = NO; + return nil; + } + } + + id obj; + int idx = 0; + int queryCount = sqlite3_bind_parameter_count(pStmt); // pointed out by Dominic Yu (thanks!) + + // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support + if (dictionaryArgs) { + + for (NSString *dictionaryKey in [dictionaryArgs allKeys]) { + + // Prefix the key with a colon. + NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey]; + + if (_traceExecution) { + NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]); + } + + // Get the index for the parameter name. + int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]); + + FMDBRelease(parameterName); + + if (namedIdx > 0) { + // Standard binding from here. + [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt]; + // increment the binding count, so our check below works out + idx++; + } + else { + NSLog(@"Could not find index for %@", dictionaryKey); + } + } + } + else { + + while (idx < queryCount) { + + if (arrayArgs && idx < (int)[arrayArgs count]) { + obj = [arrayArgs objectAtIndex:(NSUInteger)idx]; + } + else if (args) { + obj = va_arg(args, id); + } + else { + //We ran out of arguments + break; + } + + if (_traceExecution) { + if ([obj isKindOfClass:[NSData class]]) { + NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]); + } + else { + NSLog(@"obj: %@", obj); + } + } + + idx++; + + [self bindObject:obj toColumn:idx inStatement:pStmt]; + } + } + + if (idx != queryCount) { + NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)"); + sqlite3_finalize(pStmt); + _isExecutingStatement = NO; + return nil; + } + + FMDBRetain(statement); // to balance the release below + + if (!statement) { + statement = [[FMStatement alloc] init]; + [statement setStatement:pStmt]; + + if (_shouldCacheStatements && sql) { + [self setCachedStatement:statement forQuery:sql]; + } + } + + // the statement gets closed in rs's dealloc or [rs close]; + rs = [FMResultSet resultSetWithStatement:statement usingParentDatabase:self]; + [rs setQuery:sql]; + + NSValue *openResultSet = [NSValue valueWithNonretainedObject:rs]; + [_openResultSets addObject:openResultSet]; + + [statement setUseCount:[statement useCount] + 1]; + + FMDBRelease(statement); + + _isExecutingStatement = NO; + + return rs; +} + +- (FMResultSet *)executeQuery:(NSString*)sql, ... { + va_list args; + va_start(args, sql); + + id result = [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args]; + + va_end(args); + return result; +} + +- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... { + va_list args; + va_start(args, format); + + NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]]; + NSMutableArray *arguments = [NSMutableArray array]; + [self extractSQL:format argumentsList:args intoString:sql arguments:arguments]; + + va_end(args); + + return [self executeQuery:sql withArgumentsInArray:arguments]; +} + +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments { + return [self executeQuery:sql withArgumentsInArray:arguments orDictionary:nil orVAList:nil]; +} + +- (FMResultSet *)executeQuery:(NSString *)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error { + FMResultSet *rs = [self executeQuery:sql withArgumentsInArray:values orDictionary:nil orVAList:nil]; + if (!rs && error) { + *error = [self lastError]; + } + return rs; +} + +- (FMResultSet *)executeQuery:(NSString*)sql withVAList:(va_list)args { + return [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args]; +} + +#pragma mark Execute updates + +- (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args { + + if (![self databaseExists]) { + return NO; + } + + if (_isExecutingStatement) { + [self warnInUse]; + return NO; + } + + _isExecutingStatement = YES; + + int rc = 0x00; + sqlite3_stmt *pStmt = 0x00; + FMStatement *cachedStmt = 0x00; + + if (_traceExecution && sql) { + NSLog(@"%@ executeUpdate: %@", self, sql); + } + + if (_shouldCacheStatements) { + cachedStmt = [self cachedStatementForQuery:sql]; + pStmt = cachedStmt ? [cachedStmt statement] : 0x00; + [cachedStmt reset]; + } + + if (!pStmt) { + rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0); + + if (SQLITE_OK != rc) { + if (_logsErrors) { + NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); + NSLog(@"DB Query: %@", sql); + NSLog(@"DB Path: %@", _databasePath); + } + + if (_crashOnErrors) { + NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]); + abort(); + } + + if (outErr) { + *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]]; + } + + sqlite3_finalize(pStmt); + + _isExecutingStatement = NO; + return NO; + } + } + + id obj; + int idx = 0; + int queryCount = sqlite3_bind_parameter_count(pStmt); + + // If dictionaryArgs is passed in, that means we are using sqlite's named parameter support + if (dictionaryArgs) { + + for (NSString *dictionaryKey in [dictionaryArgs allKeys]) { + + // Prefix the key with a colon. + NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey]; + + if (_traceExecution) { + NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]); + } + // Get the index for the parameter name. + int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]); + + FMDBRelease(parameterName); + + if (namedIdx > 0) { + // Standard binding from here. + [self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt]; + + // increment the binding count, so our check below works out + idx++; + } + else { + NSString *message = [NSString stringWithFormat:@"Could not find index for %@", dictionaryKey]; + + if (_logsErrors) { + NSLog(@"%@", message); + } + if (outErr) { + *outErr = [self errorWithMessage:message]; + } + } + } + } + else { + + while (idx < queryCount) { + + if (arrayArgs && idx < (int)[arrayArgs count]) { + obj = [arrayArgs objectAtIndex:(NSUInteger)idx]; + } + else if (args) { + obj = va_arg(args, id); + } + else { + //We ran out of arguments + break; + } + + if (_traceExecution) { + if ([obj isKindOfClass:[NSData class]]) { + NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]); + } + else { + NSLog(@"obj: %@", obj); + } + } + + idx++; + + [self bindObject:obj toColumn:idx inStatement:pStmt]; + } + } + + + if (idx != queryCount) { + NSString *message = [NSString stringWithFormat:@"Error: the bind count (%d) is not correct for the # of variables in the query (%d) (%@) (executeUpdate)", idx, queryCount, sql]; + if (_logsErrors) { + NSLog(@"%@", message); + } + if (outErr) { + *outErr = [self errorWithMessage:message]; + } + + sqlite3_finalize(pStmt); + _isExecutingStatement = NO; + return NO; + } + + /* Call sqlite3_step() to run the virtual machine. Since the SQL being + ** executed is not a SELECT statement, we assume no data will be returned. + */ + + rc = sqlite3_step(pStmt); + + if (SQLITE_DONE == rc) { + // all is well, let's return. + } + else if (SQLITE_INTERRUPT == rc) { + if (_logsErrors) { + NSLog(@"Error calling sqlite3_step. Query was interrupted (%d: %s) SQLITE_INTERRUPT", rc, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + else if (rc == SQLITE_ROW) { + NSString *message = [NSString stringWithFormat:@"A executeUpdate is being called with a query string '%@'", sql]; + if (_logsErrors) { + NSLog(@"%@", message); + NSLog(@"DB Query: %@", sql); + } + if (outErr) { + *outErr = [self errorWithMessage:message]; + } + } + else { + if (outErr) { + *outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]]; + } + + if (SQLITE_ERROR == rc) { + if (_logsErrors) { + NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_ERROR", rc, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + else if (SQLITE_MISUSE == rc) { + // uh oh. + if (_logsErrors) { + NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_MISUSE", rc, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + else { + // wtf? + if (_logsErrors) { + NSLog(@"Unknown error calling sqlite3_step (%d: %s) eu", rc, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + } + + if (_shouldCacheStatements && !cachedStmt) { + cachedStmt = [[FMStatement alloc] init]; + + [cachedStmt setStatement:pStmt]; + + [self setCachedStatement:cachedStmt forQuery:sql]; + + FMDBRelease(cachedStmt); + } + + int closeErrorCode; + + if (cachedStmt) { + [cachedStmt setUseCount:[cachedStmt useCount] + 1]; + closeErrorCode = sqlite3_reset(pStmt); + } + else { + /* Finalize the virtual machine. This releases all memory and other + ** resources allocated by the sqlite3_prepare() call above. + */ + closeErrorCode = sqlite3_finalize(pStmt); + } + + if (closeErrorCode != SQLITE_OK) { + if (_logsErrors) { + NSLog(@"Unknown error finalizing or resetting statement (%d: %s)", closeErrorCode, sqlite3_errmsg(_db)); + NSLog(@"DB Query: %@", sql); + } + } + + _isExecutingStatement = NO; + return (rc == SQLITE_DONE || rc == SQLITE_OK); +} + + +- (BOOL)executeUpdate:(NSString*)sql, ... { + va_list args; + va_start(args, sql); + + BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args]; + + va_end(args); + return result; +} + +- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments { + return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orDictionary:nil orVAList:nil]; +} + +- (BOOL)executeUpdate:(NSString*)sql values:(NSArray *)values error:(NSError * __autoreleasing *)error { + return [self executeUpdate:sql error:error withArgumentsInArray:values orDictionary:nil orVAList:nil]; +} + +- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments { + return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:arguments orVAList:nil]; +} + +- (BOOL)executeUpdate:(NSString*)sql withVAList:(va_list)args { + return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args]; +} + +- (BOOL)executeUpdateWithFormat:(NSString*)format, ... { + va_list args; + va_start(args, format); + + NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]]; + NSMutableArray *arguments = [NSMutableArray array]; + + [self extractSQL:format argumentsList:args intoString:sql arguments:arguments]; + + va_end(args); + + return [self executeUpdate:sql withArgumentsInArray:arguments]; +} + + +int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names); // shhh clang. +int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names) { + + if (!theBlockAsVoid) { + return SQLITE_OK; + } + + int (^execCallbackBlock)(NSDictionary *resultsDictionary) = (__bridge int (^)(NSDictionary *__strong))(theBlockAsVoid); + + NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:(NSUInteger)columns]; + + for (NSInteger i = 0; i < columns; i++) { + NSString *key = [NSString stringWithUTF8String:names[i]]; + id value = values[i] ? [NSString stringWithUTF8String:values[i]] : [NSNull null]; + [dictionary setObject:value forKey:key]; + } + + return execCallbackBlock(dictionary); +} + +- (BOOL)executeStatements:(NSString *)sql { + return [self executeStatements:sql withResultBlock:nil]; +} + +- (BOOL)executeStatements:(NSString *)sql withResultBlock:(FMDBExecuteStatementsCallbackBlock)block { + + int rc; + char *errmsg = nil; + + rc = sqlite3_exec([self sqliteHandle], [sql UTF8String], block ? FMDBExecuteBulkSQLCallback : nil, (__bridge void *)(block), &errmsg); + + if (errmsg && [self logsErrors]) { + NSLog(@"Error inserting batch: %s", errmsg); + sqlite3_free(errmsg); + } + + return (rc == SQLITE_OK); +} + +- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... { + + va_list args; + va_start(args, outErr); + + BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args]; + + va_end(args); + return result; +} + + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-implementations" +- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... { + va_list args; + va_start(args, outErr); + + BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args]; + + va_end(args); + return result; +} + +#pragma clang diagnostic pop + +#pragma mark Transactions + +- (BOOL)rollback { + BOOL b = [self executeUpdate:@"rollback transaction"]; + + if (b) { + _isInTransaction = NO; + } + + return b; +} + +- (BOOL)commit { + BOOL b = [self executeUpdate:@"commit transaction"]; + + if (b) { + _isInTransaction = NO; + } + + return b; +} + +- (BOOL)beginDeferredTransaction { + + BOOL b = [self executeUpdate:@"begin deferred transaction"]; + if (b) { + _isInTransaction = YES; + } + + return b; +} + +- (BOOL)beginTransaction { + + BOOL b = [self executeUpdate:@"begin exclusive transaction"]; + if (b) { + _isInTransaction = YES; + } + + return b; +} + +- (BOOL)inTransaction { + return _isInTransaction; +} + +- (BOOL)interrupt +{ + if (_db) { + sqlite3_interrupt([self sqliteHandle]); + return YES; + } + return NO; +} + +static NSString *FMDBEscapeSavePointName(NSString *savepointName) { + return [savepointName stringByReplacingOccurrencesOfString:@"'" withString:@"''"]; +} + +- (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr { +#if SQLITE_VERSION_NUMBER >= 3007000 + NSParameterAssert(name); + + NSString *sql = [NSString stringWithFormat:@"savepoint '%@';", FMDBEscapeSavePointName(name)]; + + return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return NO; +#endif +} + +- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr { +#if SQLITE_VERSION_NUMBER >= 3007000 + NSParameterAssert(name); + + NSString *sql = [NSString stringWithFormat:@"release savepoint '%@';", FMDBEscapeSavePointName(name)]; + + return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return NO; +#endif +} + +- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr { +#if SQLITE_VERSION_NUMBER >= 3007000 + NSParameterAssert(name); + + NSString *sql = [NSString stringWithFormat:@"rollback transaction to savepoint '%@';", FMDBEscapeSavePointName(name)]; + + return [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:nil]; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return NO; +#endif +} + +- (NSError*)inSavePoint:(void (^)(BOOL *rollback))block { +#if SQLITE_VERSION_NUMBER >= 3007000 + static unsigned long savePointIdx = 0; + + NSString *name = [NSString stringWithFormat:@"dbSavePoint%ld", savePointIdx++]; + + BOOL shouldRollback = NO; + + NSError *err = 0x00; + + if (![self startSavePointWithName:name error:&err]) { + return err; + } + + if (block) { + block(&shouldRollback); + } + + if (shouldRollback) { + // We need to rollback and release this savepoint to remove it + [self rollbackToSavePointWithName:name error:&err]; + } + [self releaseSavePointWithName:name error:&err]; + + return err; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; +#endif +} + + +#pragma mark Cache statements + +- (BOOL)shouldCacheStatements { + return _shouldCacheStatements; +} + +- (void)setShouldCacheStatements:(BOOL)value { + + _shouldCacheStatements = value; + + if (_shouldCacheStatements && !_cachedStatements) { + [self setCachedStatements:[NSMutableDictionary dictionary]]; + } + + if (!_shouldCacheStatements) { + [self setCachedStatements:nil]; + } +} + +#pragma mark Callback function + +void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv); // -Wmissing-prototypes +void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv) { +#if ! __has_feature(objc_arc) + void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (id)sqlite3_user_data(context); +#else + void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (__bridge id)sqlite3_user_data(context); +#endif + if (block) { + @autoreleasepool { + block(context, argc, argv); + } + } +} + +// deprecated because "arguments" parameter is not maximum argument count, but actual argument count. + +- (void)makeFunctionNamed:(NSString *)name maximumArguments:(int)arguments withBlock:(void (^)(void *context, int argc, void **argv))block { + [self makeFunctionNamed:name arguments:arguments block:block]; +} + +- (void)makeFunctionNamed:(NSString *)name arguments:(int)arguments block:(void (^)(void *context, int argc, void **argv))block { + + if (!_openFunctions) { + _openFunctions = [NSMutableSet new]; + } + + id b = FMDBReturnAutoreleased([block copy]); + + [_openFunctions addObject:b]; + + /* I tried adding custom functions to release the block when the connection is destroyed- but they seemed to never be called, so we use _openFunctions to store the values instead. */ +#if ! __has_feature(objc_arc) + sqlite3_create_function([self sqliteHandle], [name UTF8String], arguments, SQLITE_UTF8, (void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00); +#else + sqlite3_create_function([self sqliteHandle], [name UTF8String], arguments, SQLITE_UTF8, (__bridge void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00); +#endif +} + +- (SqliteValueType)valueType:(void *)value { + return sqlite3_value_type(value); +} + +- (int)valueInt:(void *)value { + return sqlite3_value_int(value); +} + +- (long long)valueLong:(void *)value { + return sqlite3_value_int64(value); +} + +- (double)valueDouble:(void *)value { + return sqlite3_value_double(value); +} + +- (NSData *)valueData:(void *)value { + const void *bytes = sqlite3_value_blob(value); + int length = sqlite3_value_bytes(value); + return bytes ? [NSData dataWithBytes:bytes length:length] : nil; +} + +- (NSString *)valueString:(void *)value { + const char *cString = (const char *)sqlite3_value_text(value); + return cString ? [NSString stringWithUTF8String:cString] : nil; +} + +- (void)resultNullInContext:(void *)context { + sqlite3_result_null(context); +} + +- (void)resultInt:(int) value context:(void *)context { + sqlite3_result_int(context, value); +} + +- (void)resultLong:(long long)value context:(void *)context { + sqlite3_result_int64(context, value); +} + +- (void)resultDouble:(double)value context:(void *)context { + sqlite3_result_double(context, value); +} + +- (void)resultData:(NSData *)data context:(void *)context { + sqlite3_result_blob(context, data.bytes, (int)data.length, SQLITE_TRANSIENT); +} + +- (void)resultString:(NSString *)value context:(void *)context { + sqlite3_result_text(context, [value UTF8String], -1, SQLITE_TRANSIENT); +} + +- (void)resultError:(NSString *)error context:(void *)context { + sqlite3_result_error(context, [error UTF8String], -1); +} + +- (void)resultErrorCode:(int)errorCode context:(void *)context { + sqlite3_result_error_code(context, errorCode); +} + +- (void)resultErrorNoMemoryInContext:(void *)context { + sqlite3_result_error_nomem(context); +} + +- (void)resultErrorTooBigInContext:(void *)context { + sqlite3_result_error_toobig(context); +} + +@end + + + +@implementation FMStatement + +#if ! __has_feature(objc_arc) +- (void)finalize { + [self close]; + [super finalize]; +} +#endif + +- (void)dealloc { + [self close]; + FMDBRelease(_query); +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (void)close { + if (_statement) { + sqlite3_finalize(_statement); + _statement = 0x00; + } + + _inUse = NO; +} + +- (void)reset { + if (_statement) { + sqlite3_reset(_statement); + } + + _inUse = NO; +} + +- (NSString*)description { + return [NSString stringWithFormat:@"%@ %ld hit(s) for query %@", [super description], _useCount, _query]; +} + +@end + diff --git a/Pods/FMDB/src/fmdb/FMDatabaseAdditions.h b/Pods/FMDB/src/fmdb/FMDatabaseAdditions.h new file mode 100644 index 0000000..8ee51c7 --- /dev/null +++ b/Pods/FMDB/src/fmdb/FMDatabaseAdditions.h @@ -0,0 +1,250 @@ +// +// FMDatabaseAdditions.h +// fmdb +// +// Created by August Mueller on 10/30/05. +// Copyright 2005 Flying Meat Inc.. All rights reserved. +// + +#import +#import "FMDatabase.h" + +NS_ASSUME_NONNULL_BEGIN + +/** Category of additions for `` class. + + ### See also + + - `` + */ + +@interface FMDatabase (FMDatabaseAdditions) + +///---------------------------------------- +/// @name Return results of SQL to variable +///---------------------------------------- + +/** Return `int` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `int` value. + + @note This is not available from Swift. + */ + +- (int)intForQuery:(NSString*)query, ...; + +/** Return `long` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `long` value. + + @note This is not available from Swift. + */ + +- (long)longForQuery:(NSString*)query, ...; + +/** Return `BOOL` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `BOOL` value. + + @note This is not available from Swift. + */ + +- (BOOL)boolForQuery:(NSString*)query, ...; + +/** Return `double` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `double` value. + + @note This is not available from Swift. + */ + +- (double)doubleForQuery:(NSString*)query, ...; + +/** Return `NSString` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `NSString` value. + + @note This is not available from Swift. + */ + +- (NSString * _Nullable)stringForQuery:(NSString*)query, ...; + +/** Return `NSData` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `NSData` value. + + @note This is not available from Swift. + */ + +- (NSData * _Nullable)dataForQuery:(NSString*)query, ...; + +/** Return `NSDate` value for query + + @param query The SQL query to be performed. + @param ... A list of parameters that will be bound to the `?` placeholders in the SQL query. + + @return `NSDate` value. + + @note This is not available from Swift. + */ + +- (NSDate * _Nullable)dateForQuery:(NSString*)query, ...; + + +// Notice that there's no dataNoCopyForQuery:. +// That would be a bad idea, because we close out the result set, and then what +// happens to the data that we just didn't copy? Who knows, not I. + + +///-------------------------------- +/// @name Schema related operations +///-------------------------------- + +/** Does table exist in database? + + @param tableName The name of the table being looked for. + + @return `YES` if table found; `NO` if not found. + */ + +- (BOOL)tableExists:(NSString*)tableName; + +/** The schema of the database. + + This will be the schema for the entire database. For each entity, each row of the result set will include the following fields: + + - `type` - The type of entity (e.g. table, index, view, or trigger) + - `name` - The name of the object + - `tbl_name` - The name of the table to which the object references + - `rootpage` - The page number of the root b-tree page for tables and indices + - `sql` - The SQL that created the entity + + @return `FMResultSet` of schema; `nil` on error. + + @see [SQLite File Format](http://www.sqlite.org/fileformat.html) + */ + +- (FMResultSet *)getSchema; + +/** The schema of the database. + + This will be the schema for a particular table as report by SQLite `PRAGMA`, for example: + + PRAGMA table_info('employees') + + This will report: + + - `cid` - The column ID number + - `name` - The name of the column + - `type` - The data type specified for the column + - `notnull` - whether the field is defined as NOT NULL (i.e. values required) + - `dflt_value` - The default value for the column + - `pk` - Whether the field is part of the primary key of the table + + @param tableName The name of the table for whom the schema will be returned. + + @return `FMResultSet` of schema; `nil` on error. + + @see [table_info](http://www.sqlite.org/pragma.html#pragma_table_info) + */ + +- (FMResultSet*)getTableSchema:(NSString*)tableName; + +/** Test to see if particular column exists for particular table in database + + @param columnName The name of the column. + + @param tableName The name of the table. + + @return `YES` if column exists in table in question; `NO` otherwise. + */ + +- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName; + +/** Test to see if particular column exists for particular table in database + + @param columnName The name of the column. + + @param tableName The name of the table. + + @return `YES` if column exists in table in question; `NO` otherwise. + + @see columnExists:inTableWithName: + + @warning Deprecated - use `` instead. + */ + +- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __deprecated_msg("Use columnExists:inTableWithName: instead"); + + +/** Validate SQL statement + + This validates SQL statement by performing `sqlite3_prepare_v2`, but not returning the results, but instead immediately calling `sqlite3_finalize`. + + @param sql The SQL statement being validated. + + @param error This is a pointer to a `NSError` object that will receive the autoreleased `NSError` object if there was any error. If this is `nil`, no `NSError` result will be returned. + + @return `YES` if validation succeeded without incident; `NO` otherwise. + + */ + +- (BOOL)validateSQL:(NSString*)sql error:(NSError * _Nullable *)error; + + +///----------------------------------- +/// @name Application identifier tasks +///----------------------------------- + +/** Retrieve application ID + + @return The `uint32_t` numeric value of the application ID. + + @see setApplicationID: + */ + +@property (nonatomic) uint32_t applicationID; + +#if TARGET_OS_MAC && !TARGET_OS_IPHONE + +/** Retrieve application ID string + + @see setApplicationIDString: + */ + +@property (nonatomic, retain) NSString *applicationIDString; + +#endif + +///----------------------------------- +/// @name user version identifier tasks +///----------------------------------- + +/** Retrieve user version + + @see setUserVersion: + */ + +@property (nonatomic) uint32_t userVersion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FMDB/src/fmdb/FMDatabaseAdditions.m b/Pods/FMDB/src/fmdb/FMDatabaseAdditions.m new file mode 100644 index 0000000..208e69e --- /dev/null +++ b/Pods/FMDB/src/fmdb/FMDatabaseAdditions.m @@ -0,0 +1,245 @@ +// +// FMDatabaseAdditions.m +// fmdb +// +// Created by August Mueller on 10/30/05. +// Copyright 2005 Flying Meat Inc.. All rights reserved. +// + +#import "FMDatabase.h" +#import "FMDatabaseAdditions.h" +#import "TargetConditionals.h" + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +@interface FMDatabase (PrivateStuff) +- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray * _Nullable)arrayArgs orDictionary:(NSDictionary * _Nullable)dictionaryArgs orVAList:(va_list)args; +@end + +@implementation FMDatabase (FMDatabaseAdditions) + +#define RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(type, sel) \ +va_list args; \ +va_start(args, query); \ +FMResultSet *resultSet = [self executeQuery:query withArgumentsInArray:0x00 orDictionary:0x00 orVAList:args]; \ +va_end(args); \ +if (![resultSet next]) { return (type)0; } \ +type ret = [resultSet sel:0]; \ +[resultSet close]; \ +[resultSet setParentDB:nil]; \ +return ret; + + +- (NSString *)stringForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSString *, stringForColumnIndex); +} + +- (int)intForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(int, intForColumnIndex); +} + +- (long)longForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(long, longForColumnIndex); +} + +- (BOOL)boolForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(BOOL, boolForColumnIndex); +} + +- (double)doubleForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(double, doubleForColumnIndex); +} + +- (NSData*)dataForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSData *, dataForColumnIndex); +} + +- (NSDate*)dateForQuery:(NSString*)query, ... { + RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSDate *, dateForColumnIndex); +} + + +- (BOOL)tableExists:(NSString*)tableName { + + tableName = [tableName lowercaseString]; + + FMResultSet *rs = [self executeQuery:@"select [sql] from sqlite_master where [type] = 'table' and lower(name) = ?", tableName]; + + //if at least one next exists, table exists + BOOL returnBool = [rs next]; + + //close and free object + [rs close]; + + return returnBool; +} + +/* + get table with list of tables: result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] + check if table exist in database (patch from OZLB) +*/ +- (FMResultSet*)getSchema { + + //result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING] + FMResultSet *rs = [self executeQuery:@"SELECT type, name, tbl_name, rootpage, sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type != 'meta' AND name NOT LIKE 'sqlite_%' ORDER BY tbl_name, type DESC, name"]; + + return rs; +} + +/* + get table schema: result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] +*/ +- (FMResultSet*)getTableSchema:(NSString*)tableName { + + //result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER] + FMResultSet *rs = [self executeQuery:[NSString stringWithFormat: @"pragma table_info('%@')", tableName]]; + + return rs; +} + +- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName { + + BOOL returnBool = NO; + + tableName = [tableName lowercaseString]; + columnName = [columnName lowercaseString]; + + FMResultSet *rs = [self getTableSchema:tableName]; + + //check if column is present in table schema + while ([rs next]) { + if ([[[rs stringForColumn:@"name"] lowercaseString] isEqualToString:columnName]) { + returnBool = YES; + break; + } + } + + //If this is not done FMDatabase instance stays out of pool + [rs close]; + + return returnBool; +} + + + +- (uint32_t)applicationID { +#if SQLITE_VERSION_NUMBER >= 3007017 + uint32_t r = 0; + + FMResultSet *rs = [self executeQuery:@"pragma application_id"]; + + if ([rs next]) { + r = (uint32_t)[rs longLongIntForColumnIndex:0]; + } + + [rs close]; + + return r; +#else + NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return 0; +#endif +} + +- (void)setApplicationID:(uint32_t)appID { +#if SQLITE_VERSION_NUMBER >= 3007017 + NSString *query = [NSString stringWithFormat:@"pragma application_id=%d", appID]; + FMResultSet *rs = [self executeQuery:query]; + [rs next]; + [rs close]; +#else + NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); +#endif +} + + +#if TARGET_OS_MAC && !TARGET_OS_IPHONE + +- (NSString*)applicationIDString { +#if SQLITE_VERSION_NUMBER >= 3007017 + NSString *s = NSFileTypeForHFSTypeCode([self applicationID]); + + assert([s length] == 6); + + s = [s substringWithRange:NSMakeRange(1, 4)]; + + + return s; +#else + NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return nil; +#endif +} + +- (void)setApplicationIDString:(NSString*)s { +#if SQLITE_VERSION_NUMBER >= 3007017 + if ([s length] != 4) { + NSLog(@"setApplicationIDString: string passed is not exactly 4 chars long. (was %ld)", [s length]); + } + + [self setApplicationID:NSHFSTypeCodeFromFileType([NSString stringWithFormat:@"'%@'", s])]; +#else + NSString *errorMessage = NSLocalizedString(@"Application ID functions require SQLite 3.7.17", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); +#endif +} + +#endif + +- (uint32_t)userVersion { + uint32_t r = 0; + + FMResultSet *rs = [self executeQuery:@"pragma user_version"]; + + if ([rs next]) { + r = (uint32_t)[rs longLongIntForColumnIndex:0]; + } + + [rs close]; + return r; +} + +- (void)setUserVersion:(uint32_t)version { + NSString *query = [NSString stringWithFormat:@"pragma user_version = %d", version]; + FMResultSet *rs = [self executeQuery:query]; + [rs next]; + [rs close]; +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-implementations" + +- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)) { + return [self columnExists:columnName inTableWithName:tableName]; +} + +#pragma clang diagnostic pop + +- (BOOL)validateSQL:(NSString*)sql error:(NSError**)error { + sqlite3_stmt *pStmt = NULL; + BOOL validationSucceeded = YES; + + int rc = sqlite3_prepare_v2([self sqliteHandle], [sql UTF8String], -1, &pStmt, 0); + if (rc != SQLITE_OK) { + validationSucceeded = NO; + if (error) { + *error = [NSError errorWithDomain:NSCocoaErrorDomain + code:[self lastErrorCode] + userInfo:[NSDictionary dictionaryWithObject:[self lastErrorMessage] + forKey:NSLocalizedDescriptionKey]]; + } + } + + sqlite3_finalize(pStmt); + + return validationSucceeded; +} + +@end diff --git a/Pods/FMDB/src/fmdb/FMDatabasePool.h b/Pods/FMDB/src/fmdb/FMDatabasePool.h new file mode 100755 index 0000000..3642f59 --- /dev/null +++ b/Pods/FMDB/src/fmdb/FMDatabasePool.h @@ -0,0 +1,258 @@ +// +// FMDatabasePool.h +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class FMDatabase; + +/** Pool of `` objects. + + ### See also + + - `` + - `` + + @warning Before using `FMDatabasePool`, please consider using `` instead. + + If you really really really know what you're doing and `FMDatabasePool` is what + you really really need (ie, you're using a read only database), OK you can use + it. But just be careful not to deadlock! + + For an example on deadlocking, search for: + `ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD` + in the main.m file. + */ + +@interface FMDatabasePool : NSObject + +/** Database path */ + +@property (atomic, copy, nullable) NSString *path; + +/** Delegate object */ + +@property (atomic, assign, nullable) id delegate; + +/** Maximum number of databases to create */ + +@property (atomic, assign) NSUInteger maximumNumberOfDatabasesToCreate; + +/** Open flags */ + +@property (atomic, readonly) int openFlags; + +/** Custom virtual file system name */ + +@property (atomic, copy, nullable) NSString *vfsName; + + +///--------------------- +/// @name Initialization +///--------------------- + +/** Create pool using path. + + @param aPath The file path of the database. + + @return The `FMDatabasePool` object. `nil` on error. + */ + ++ (instancetype)databasePoolWithPath:(NSString * _Nullable)aPath; + +/** Create pool using file URL. + + @param url The file `NSURL` of the database. + + @return The `FMDatabasePool` object. `nil` on error. + */ + ++ (instancetype)databasePoolWithURL:(NSURL * _Nullable)url; + +/** Create pool using path and specified flags + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database. + + @return The `FMDatabasePool` object. `nil` on error. + */ + ++ (instancetype)databasePoolWithPath:(NSString * _Nullable)aPath flags:(int)openFlags; + +/** Create pool using file URL and specified flags + + @param url The file `NSURL` of the database. + @param openFlags Flags passed to the openWithFlags method of the database. + + @return The `FMDatabasePool` object. `nil` on error. + */ + ++ (instancetype)databasePoolWithURL:(NSURL * _Nullable)url flags:(int)openFlags; + +/** Create pool using path. + + @param aPath The file path of the database. + + @return The `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString * _Nullable)aPath; + +/** Create pool using file URL. + + @param url The file `NSURL of the database. + + @return The `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithURL:(NSURL * _Nullable)url; + +/** Create pool using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database + + @return The `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags; + +/** Create pool using file URL and specified flags. + + @param url The file `NSURL` of the database. + @param openFlags Flags passed to the openWithFlags method of the database + + @return The `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags; + +/** Create pool using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database + @param vfsName The name of a custom virtual file system + + @return The `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags vfs:(NSString * _Nullable)vfsName; + +/** Create pool using file URL and specified flags. + + @param url The file `NSURL` of the database. + @param openFlags Flags passed to the openWithFlags method of the database + @param vfsName The name of a custom virtual file system + + @return The `FMDatabasePool` object. `nil` on error. + */ + +- (instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags vfs:(NSString * _Nullable)vfsName; + +/** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object. + + Subclasses can override this method to return specified Class of 'FMDatabase' subclass. + + @return The Class of 'FMDatabase' subclass, that will be used to instantiate database object. + */ + ++ (Class)databaseClass; + +///------------------------------------------------ +/// @name Keeping track of checked in/out databases +///------------------------------------------------ + +/** Number of checked-in databases in pool + */ + +@property (nonatomic, readonly) NSUInteger countOfCheckedInDatabases; + +/** Number of checked-out databases in pool + */ + +@property (nonatomic, readonly) NSUInteger countOfCheckedOutDatabases; + +/** Total number of databases in pool + */ + +@property (nonatomic, readonly) NSUInteger countOfOpenDatabases; + +/** Release all databases in pool */ + +- (void)releaseAllDatabases; + +///------------------------------------------ +/// @name Perform database operations in pool +///------------------------------------------ + +/** Synchronously perform database operations in pool. + + @param block The code to be run on the `FMDatabasePool` pool. + */ + +- (void)inDatabase:(__attribute__((noescape)) void (^)(FMDatabase *db))block; + +/** Synchronously perform database operations in pool using transaction. + + @param block The code to be run on the `FMDatabasePool` pool. + */ + +- (void)inTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; + +/** Synchronously perform database operations in pool using deferred transaction. + + @param block The code to be run on the `FMDatabasePool` pool. + */ + +- (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; + +/** Synchronously perform database operations in pool using save point. + + @param block The code to be run on the `FMDatabasePool` pool. + + @return `NSError` object if error; `nil` if successful. + + @warning You can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. If you need to nest, use `<[FMDatabase startSavePointWithName:error:]>` instead. +*/ + +- (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; + +@end + + +/** FMDatabasePool delegate category + + This is a category that defines the protocol for the FMDatabasePool delegate + */ + +@interface NSObject (FMDatabasePoolDelegate) + +/** Asks the delegate whether database should be added to the pool. + + @param pool The `FMDatabasePool` object. + @param database The `FMDatabase` object. + + @return `YES` if it should add database to pool; `NO` if not. + + */ + +- (BOOL)databasePool:(FMDatabasePool*)pool shouldAddDatabaseToPool:(FMDatabase*)database; + +/** Tells the delegate that database was added to the pool. + + @param pool The `FMDatabasePool` object. + @param database The `FMDatabase` object. + + */ + +- (void)databasePool:(FMDatabasePool*)pool didAddDatabase:(FMDatabase*)database; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FMDB/src/fmdb/FMDatabasePool.m b/Pods/FMDB/src/fmdb/FMDatabasePool.m new file mode 100755 index 0000000..41a5985 --- /dev/null +++ b/Pods/FMDB/src/fmdb/FMDatabasePool.m @@ -0,0 +1,316 @@ +// +// FMDatabasePool.m +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +#import "FMDatabasePool.h" +#import "FMDatabase.h" + +@interface FMDatabasePool () { + dispatch_queue_t _lockQueue; + + NSMutableArray *_databaseInPool; + NSMutableArray *_databaseOutPool; +} + +- (void)pushDatabaseBackInPool:(FMDatabase*)db; +- (FMDatabase*)db; + +@end + + +@implementation FMDatabasePool +@synthesize path=_path; +@synthesize delegate=_delegate; +@synthesize maximumNumberOfDatabasesToCreate=_maximumNumberOfDatabasesToCreate; +@synthesize openFlags=_openFlags; + + ++ (instancetype)databasePoolWithPath:(NSString *)aPath { + return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]); +} + ++ (instancetype)databasePoolWithURL:(NSURL *)url { + return FMDBReturnAutoreleased([[self alloc] initWithPath:url.path]); +} + ++ (instancetype)databasePoolWithPath:(NSString *)aPath flags:(int)openFlags { + return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath flags:openFlags]); +} + ++ (instancetype)databasePoolWithURL:(NSURL *)url flags:(int)openFlags { + return FMDBReturnAutoreleased([[self alloc] initWithPath:url.path flags:openFlags]); +} + +- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags vfs:(NSString *)vfsName { + return [self initWithPath:url.path flags:openFlags vfs:vfsName]; +} + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName { + + self = [super init]; + + if (self != nil) { + _path = [aPath copy]; + _lockQueue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); + _databaseInPool = FMDBReturnRetained([NSMutableArray array]); + _databaseOutPool = FMDBReturnRetained([NSMutableArray array]); + _openFlags = openFlags; + _vfsName = [vfsName copy]; + } + + return self; +} + +- (instancetype)initWithPath:(NSString *)aPath flags:(int)openFlags { + return [self initWithPath:aPath flags:openFlags vfs:nil]; +} + +- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags { + return [self initWithPath:url.path flags:openFlags vfs:nil]; +} + +- (instancetype)initWithPath:(NSString*)aPath { + // default flags for sqlite3_open + return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE]; +} + +- (instancetype)initWithURL:(NSURL *)url { + return [self initWithPath:url.path]; +} + +- (instancetype)init { + return [self initWithPath:nil]; +} + ++ (Class)databaseClass { + return [FMDatabase class]; +} + +- (void)dealloc { + + _delegate = 0x00; + FMDBRelease(_path); + FMDBRelease(_databaseInPool); + FMDBRelease(_databaseOutPool); + FMDBRelease(_vfsName); + + if (_lockQueue) { + FMDBDispatchQueueRelease(_lockQueue); + _lockQueue = 0x00; + } +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + + +- (void)executeLocked:(void (^)(void))aBlock { + dispatch_sync(_lockQueue, aBlock); +} + +- (void)pushDatabaseBackInPool:(FMDatabase*)db { + + if (!db) { // db can be null if we set an upper bound on the # of databases to create. + return; + } + + [self executeLocked:^() { + + if ([self->_databaseInPool containsObject:db]) { + [[NSException exceptionWithName:@"Database already in pool" reason:@"The FMDatabase being put back into the pool is already present in the pool" userInfo:nil] raise]; + } + + [self->_databaseInPool addObject:db]; + [self->_databaseOutPool removeObject:db]; + + }]; +} + +- (FMDatabase*)db { + + __block FMDatabase *db; + + + [self executeLocked:^() { + db = [self->_databaseInPool lastObject]; + + BOOL shouldNotifyDelegate = NO; + + if (db) { + [self->_databaseOutPool addObject:db]; + [self->_databaseInPool removeLastObject]; + } + else { + + if (self->_maximumNumberOfDatabasesToCreate) { + NSUInteger currentCount = [self->_databaseOutPool count] + [self->_databaseInPool count]; + + if (currentCount >= self->_maximumNumberOfDatabasesToCreate) { + NSLog(@"Maximum number of databases (%ld) has already been reached!", (long)currentCount); + return; + } + } + + db = [[[self class] databaseClass] databaseWithPath:self->_path]; + shouldNotifyDelegate = YES; + } + + //This ensures that the db is opened before returning +#if SQLITE_VERSION_NUMBER >= 3005000 + BOOL success = [db openWithFlags:self->_openFlags vfs:self->_vfsName]; +#else + BOOL success = [db open]; +#endif + if (success) { + if ([self->_delegate respondsToSelector:@selector(databasePool:shouldAddDatabaseToPool:)] && ![self->_delegate databasePool:self shouldAddDatabaseToPool:db]) { + [db close]; + db = 0x00; + } + else { + //It should not get added in the pool twice if lastObject was found + if (![self->_databaseOutPool containsObject:db]) { + [self->_databaseOutPool addObject:db]; + + if (shouldNotifyDelegate && [self->_delegate respondsToSelector:@selector(databasePool:didAddDatabase:)]) { + [self->_delegate databasePool:self didAddDatabase:db]; + } + } + } + } + else { + NSLog(@"Could not open up the database at path %@", self->_path); + db = 0x00; + } + }]; + + return db; +} + +- (NSUInteger)countOfCheckedInDatabases { + + __block NSUInteger count; + + [self executeLocked:^() { + count = [self->_databaseInPool count]; + }]; + + return count; +} + +- (NSUInteger)countOfCheckedOutDatabases { + + __block NSUInteger count; + + [self executeLocked:^() { + count = [self->_databaseOutPool count]; + }]; + + return count; +} + +- (NSUInteger)countOfOpenDatabases { + __block NSUInteger count; + + [self executeLocked:^() { + count = [self->_databaseOutPool count] + [self->_databaseInPool count]; + }]; + + return count; +} + +- (void)releaseAllDatabases { + [self executeLocked:^() { + [self->_databaseOutPool removeAllObjects]; + [self->_databaseInPool removeAllObjects]; + }]; +} + +- (void)inDatabase:(void (^)(FMDatabase *db))block { + + FMDatabase *db = [self db]; + + block(db); + + [self pushDatabaseBackInPool:db]; +} + +- (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { + + BOOL shouldRollback = NO; + + FMDatabase *db = [self db]; + + if (useDeferred) { + [db beginDeferredTransaction]; + } + else { + [db beginTransaction]; + } + + + block(db, &shouldRollback); + + if (shouldRollback) { + [db rollback]; + } + else { + [db commit]; + } + + [self pushDatabaseBackInPool:db]; +} + +- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { + [self beginTransaction:YES withBlock:block]; +} + +- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { + [self beginTransaction:NO withBlock:block]; +} + +- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { +#if SQLITE_VERSION_NUMBER >= 3007000 + static unsigned long savePointIdx = 0; + + NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; + + BOOL shouldRollback = NO; + + FMDatabase *db = [self db]; + + NSError *err = 0x00; + + if (![db startSavePointWithName:name error:&err]) { + [self pushDatabaseBackInPool:db]; + return err; + } + + block(db, &shouldRollback); + + if (shouldRollback) { + // We need to rollback and release this savepoint to remove it + [db rollbackToSavePointWithName:name error:&err]; + } + [db releaseSavePointWithName:name error:&err]; + + [self pushDatabaseBackInPool:db]; + + return err; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; +#endif +} + +@end diff --git a/Pods/FMDB/src/fmdb/FMDatabaseQueue.h b/Pods/FMDB/src/fmdb/FMDatabaseQueue.h new file mode 100755 index 0000000..0a8b938 --- /dev/null +++ b/Pods/FMDB/src/fmdb/FMDatabaseQueue.h @@ -0,0 +1,235 @@ +// +// FMDatabaseQueue.h +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class FMDatabase; + +/** To perform queries and updates on multiple threads, you'll want to use `FMDatabaseQueue`. + + Using a single instance of `` from multiple threads at once is a bad idea. It has always been OK to make a `` object *per thread*. Just don't share a single instance across threads, and definitely not across multiple threads at the same time. + + Instead, use `FMDatabaseQueue`. Here's how to use it: + + First, make your queue. + + FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath]; + + Then use it like so: + + [queue inDatabase:^(FMDatabase *db) { + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; + + FMResultSet *rs = [db executeQuery:@"select * from foo"]; + while ([rs next]) { + //… + } + }]; + + An easy way to wrap things up in a transaction can be done like this: + + [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]]; + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]]; + + if (whoopsSomethingWrongHappened) { + *rollback = YES; + return; + } + // etc… + [db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]]; + }]; + + `FMDatabaseQueue` will run the blocks on a serialized queue (hence the name of the class). So if you call `FMDatabaseQueue`'s methods from multiple threads at the same time, they will be executed in the order they are received. This way queries and updates won't step on each other's toes, and every one is happy. + + ### See also + + - `` + + @warning Do not instantiate a single `` object and use it across multiple threads. Use `FMDatabaseQueue` instead. + + @warning The calls to `FMDatabaseQueue`'s methods are blocking. So even though you are passing along blocks, they will **not** be run on another thread. + + */ + +@interface FMDatabaseQueue : NSObject +/** Path of database */ + +@property (atomic, retain, nullable) NSString *path; + +/** Open flags */ + +@property (atomic, readonly) int openFlags; + +/** Custom virtual file system name */ + +@property (atomic, copy, nullable) NSString *vfsName; + +///---------------------------------------------------- +/// @name Initialization, opening, and closing of queue +///---------------------------------------------------- + +/** Create queue using path. + + @param aPath The file path of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + ++ (instancetype)databaseQueueWithPath:(NSString * _Nullable)aPath; + +/** Create queue using file URL. + + @param url The file `NSURL` of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + ++ (instancetype)databaseQueueWithURL:(NSURL * _Nullable)url; + +/** Create queue using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ ++ (instancetype)databaseQueueWithPath:(NSString * _Nullable)aPath flags:(int)openFlags; + +/** Create queue using file URL and specified flags. + + @param url The file `NSURL` of the database. + @param openFlags Flags passed to the openWithFlags method of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ ++ (instancetype)databaseQueueWithURL:(NSURL * _Nullable)url flags:(int)openFlags; + +/** Create queue using path. + + @param aPath The file path of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString * _Nullable)aPath; + +/** Create queue using file URL. + + @param url The file `NSURL of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithURL:(NSURL * _Nullable)url; + +/** Create queue using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags; + +/** Create queue using file URL and specified flags. + + @param url The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database. + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags; + +/** Create queue using path and specified flags. + + @param aPath The file path of the database. + @param openFlags Flags passed to the openWithFlags method of the database + @param vfsName The name of a custom virtual file system + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithPath:(NSString * _Nullable)aPath flags:(int)openFlags vfs:(NSString * _Nullable)vfsName; + +/** Create queue using file URL and specified flags. + + @param url The file `NSURL of the database. + @param openFlags Flags passed to the openWithFlags method of the database + @param vfsName The name of a custom virtual file system + + @return The `FMDatabaseQueue` object. `nil` on error. + */ + +- (instancetype)initWithURL:(NSURL * _Nullable)url flags:(int)openFlags vfs:(NSString * _Nullable)vfsName; + +/** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object. + + Subclasses can override this method to return specified Class of 'FMDatabase' subclass. + + @return The Class of 'FMDatabase' subclass, that will be used to instantiate database object. + */ + ++ (Class)databaseClass; + +/** Close database used by queue. */ + +- (void)close; + +/** Interupt pending database operation. */ + +- (void)interrupt; + +///----------------------------------------------- +/// @name Dispatching database operations to queue +///----------------------------------------------- + +/** Synchronously perform database operations on queue. + + @param block The code to be run on the queue of `FMDatabaseQueue` + */ + +- (void)inDatabase:(__attribute__((noescape)) void (^)(FMDatabase *db))block; + +/** Synchronously perform database operations on queue, using transactions. + + @param block The code to be run on the queue of `FMDatabaseQueue` + */ + +- (void)inTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; + +/** Synchronously perform database operations on queue, using deferred transactions. + + @param block The code to be run on the queue of `FMDatabaseQueue` + */ + +- (void)inDeferredTransaction:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; + +///----------------------------------------------- +/// @name Dispatching database operations to queue +///----------------------------------------------- + +/** Synchronously perform database operations using save point. + + @param block The code to be run on the queue of `FMDatabaseQueue` + */ + +// NOTE: you can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. +// If you need to nest, use FMDatabase's startSavePointWithName:error: instead. +- (NSError * _Nullable)inSavePoint:(__attribute__((noescape)) void (^)(FMDatabase *db, BOOL *rollback))block; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FMDB/src/fmdb/FMDatabaseQueue.m b/Pods/FMDB/src/fmdb/FMDatabaseQueue.m new file mode 100755 index 0000000..f3f30cf --- /dev/null +++ b/Pods/FMDB/src/fmdb/FMDatabaseQueue.m @@ -0,0 +1,270 @@ +// +// FMDatabaseQueue.m +// fmdb +// +// Created by August Mueller on 6/22/11. +// Copyright 2011 Flying Meat Inc. All rights reserved. +// + +#import "FMDatabaseQueue.h" +#import "FMDatabase.h" + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +/* + + Note: we call [self retain]; before using dispatch_sync, just incase + FMDatabaseQueue is released on another thread and we're in the middle of doing + something in dispatch_sync + + */ + +/* + * A key used to associate the FMDatabaseQueue object with the dispatch_queue_t it uses. + * This in turn is used for deadlock detection by seeing if inDatabase: is called on + * the queue's dispatch queue, which should not happen and causes a deadlock. + */ +static const void * const kDispatchQueueSpecificKey = &kDispatchQueueSpecificKey; + +@interface FMDatabaseQueue () { + dispatch_queue_t _queue; + FMDatabase *_db; +} +@end + +@implementation FMDatabaseQueue + ++ (instancetype)databaseQueueWithPath:(NSString *)aPath { + FMDatabaseQueue *q = [[self alloc] initWithPath:aPath]; + + FMDBAutorelease(q); + + return q; +} + ++ (instancetype)databaseQueueWithURL:(NSURL *)url { + return [self databaseQueueWithPath:url.path]; +} + ++ (instancetype)databaseQueueWithPath:(NSString *)aPath flags:(int)openFlags { + FMDatabaseQueue *q = [[self alloc] initWithPath:aPath flags:openFlags]; + + FMDBAutorelease(q); + + return q; +} + ++ (instancetype)databaseQueueWithURL:(NSURL *)url flags:(int)openFlags { + return [self databaseQueueWithPath:url.path flags:openFlags]; +} + ++ (Class)databaseClass { + return [FMDatabase class]; +} + +- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags vfs:(NSString *)vfsName { + return [self initWithPath:url.path flags:openFlags vfs:vfsName]; +} + +- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags vfs:(NSString *)vfsName { + self = [super init]; + + if (self != nil) { + + _db = [[[self class] databaseClass] databaseWithPath:aPath]; + FMDBRetain(_db); + +#if SQLITE_VERSION_NUMBER >= 3005000 + BOOL success = [_db openWithFlags:openFlags vfs:vfsName]; +#else + BOOL success = [_db open]; +#endif + if (!success) { + NSLog(@"Could not create database queue for path %@", aPath); + FMDBRelease(self); + return 0x00; + } + + _path = FMDBReturnRetained(aPath); + + _queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL); + dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL); + _openFlags = openFlags; + _vfsName = [vfsName copy]; + } + + return self; +} + +- (instancetype)initWithPath:(NSString *)aPath flags:(int)openFlags { + return [self initWithPath:aPath flags:openFlags vfs:nil]; +} + +- (instancetype)initWithURL:(NSURL *)url flags:(int)openFlags { + return [self initWithPath:url.path flags:openFlags vfs:nil]; +} + +- (instancetype)initWithURL:(NSURL *)url { + return [self initWithPath:url.path]; +} + +- (instancetype)initWithPath:(NSString *)aPath { + // default flags for sqlite3_open + return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE vfs:nil]; +} + +- (instancetype)init { + return [self initWithPath:nil]; +} + + +- (void)dealloc { + FMDBRelease(_db); + FMDBRelease(_path); + FMDBRelease(_vfsName); + + if (_queue) { + FMDBDispatchQueueRelease(_queue); + _queue = 0x00; + } +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (void)close { + FMDBRetain(self); + dispatch_sync(_queue, ^() { + [self->_db close]; + FMDBRelease(_db); + self->_db = 0x00; + }); + FMDBRelease(self); +} + +- (void)interrupt { + [[self database] interrupt]; +} + +- (FMDatabase*)database { + if (!_db) { + _db = FMDBReturnRetained([[[self class] databaseClass] databaseWithPath:_path]); + +#if SQLITE_VERSION_NUMBER >= 3005000 + BOOL success = [_db openWithFlags:_openFlags vfs:_vfsName]; +#else + BOOL success = [_db open]; +#endif + if (!success) { + NSLog(@"FMDatabaseQueue could not reopen database for path %@", _path); + FMDBRelease(_db); + _db = 0x00; + return 0x00; + } + } + + return _db; +} + +- (void)inDatabase:(void (^)(FMDatabase *db))block { +#ifndef NDEBUG + /* Get the currently executing queue (which should probably be nil, but in theory could be another DB queue + * and then check it against self to make sure we're not about to deadlock. */ + FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey); + assert(currentSyncQueue != self && "inDatabase: was called reentrantly on the same queue, which would lead to a deadlock"); +#endif + + FMDBRetain(self); + + dispatch_sync(_queue, ^() { + + FMDatabase *db = [self database]; + block(db); + + if ([db hasOpenResultSets]) { + NSLog(@"Warning: there is at least one open result set around after performing [FMDatabaseQueue inDatabase:]"); + +#if defined(DEBUG) && DEBUG + NSSet *openSetCopy = FMDBReturnAutoreleased([[db valueForKey:@"_openResultSets"] copy]); + for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) { + FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue]; + NSLog(@"query: '%@'", [rs query]); + } +#endif + } + }); + + FMDBRelease(self); +} + +- (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block { + FMDBRetain(self); + dispatch_sync(_queue, ^() { + + BOOL shouldRollback = NO; + + if (useDeferred) { + [[self database] beginDeferredTransaction]; + } + else { + [[self database] beginTransaction]; + } + + block([self database], &shouldRollback); + + if (shouldRollback) { + [[self database] rollback]; + } + else { + [[self database] commit]; + } + }); + + FMDBRelease(self); +} + +- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { + [self beginTransaction:YES withBlock:block]; +} + +- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block { + [self beginTransaction:NO withBlock:block]; +} + +- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block { +#if SQLITE_VERSION_NUMBER >= 3007000 + static unsigned long savePointIdx = 0; + __block NSError *err = 0x00; + FMDBRetain(self); + dispatch_sync(_queue, ^() { + + NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++]; + + BOOL shouldRollback = NO; + + if ([[self database] startSavePointWithName:name error:&err]) { + + block([self database], &shouldRollback); + + if (shouldRollback) { + // We need to rollback and release this savepoint to remove it + [[self database] rollbackToSavePointWithName:name error:&err]; + } + [[self database] releaseSavePointWithName:name error:&err]; + + } + }); + FMDBRelease(self); + return err; +#else + NSString *errorMessage = NSLocalizedString(@"Save point functions require SQLite 3.7", nil); + if (self.logsErrors) NSLog(@"%@", errorMessage); + return [NSError errorWithDomain:@"FMDatabase" code:0 userInfo:@{NSLocalizedDescriptionKey : errorMessage}]; +#endif +} + +@end diff --git a/Pods/FMDB/src/fmdb/FMResultSet.h b/Pods/FMDB/src/fmdb/FMResultSet.h new file mode 100644 index 0000000..8057291 --- /dev/null +++ b/Pods/FMDB/src/fmdb/FMResultSet.h @@ -0,0 +1,467 @@ +#import + +NS_ASSUME_NONNULL_BEGIN + +#ifndef __has_feature // Optional. +#define __has_feature(x) 0 // Compatibility with non-clang compilers. +#endif + +#ifndef NS_RETURNS_NOT_RETAINED +#if __has_feature(attribute_ns_returns_not_retained) +#define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained)) +#else +#define NS_RETURNS_NOT_RETAINED +#endif +#endif + +@class FMDatabase; +@class FMStatement; + +/** Represents the results of executing a query on an ``. + + ### See also + + - `` + */ + +@interface FMResultSet : NSObject + +@property (nonatomic, retain, nullable) FMDatabase *parentDB; + +///----------------- +/// @name Properties +///----------------- + +/** Executed query */ + +@property (atomic, retain, nullable) NSString *query; + +/** `NSMutableDictionary` mapping column names to numeric index */ + +@property (readonly) NSMutableDictionary *columnNameToIndexMap; + +/** `FMStatement` used by result set. */ + +@property (atomic, retain, nullable) FMStatement *statement; + +///------------------------------------ +/// @name Creating and closing database +///------------------------------------ + +/** Create result set from `` + + @param statement A `` to be performed + + @param aDB A `` to be used + + @return A `FMResultSet` on success; `nil` on failure + */ + ++ (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB; + +/** Close result set */ + +- (void)close; + +///--------------------------------------- +/// @name Iterating through the result set +///--------------------------------------- + +/** Retrieve next row for result set. + + You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one. + + @return `YES` if row successfully retrieved; `NO` if end of result set reached + + @see hasAnotherRow + */ + +- (BOOL)next; + +/** Retrieve next row for result set. + + You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one. + + @param outErr A 'NSError' object to receive any error object (if any). + + @return 'YES' if row successfully retrieved; 'NO' if end of result set reached + + @see hasAnotherRow + */ + +- (BOOL)nextWithError:(NSError * _Nullable *)outErr; + +/** Did the last call to `` succeed in retrieving another row? + + @return `YES` if the last call to `` succeeded in retrieving another record; `NO` if not. + + @see next + + @warning The `hasAnotherRow` method must follow a call to ``. If the previous database interaction was something other than a call to `next`, then this method may return `NO`, whether there is another row of data or not. + */ + +- (BOOL)hasAnotherRow; + +///--------------------------------------------- +/// @name Retrieving information from result set +///--------------------------------------------- + +/** How many columns in result set + + @return Integer value of the number of columns. + */ + +@property (nonatomic, readonly) int columnCount; + +/** Column index for column name + + @param columnName `NSString` value of the name of the column. + + @return Zero-based index for column. + */ + +- (int)columnIndexForName:(NSString*)columnName; + +/** Column name for column index + + @param columnIdx Zero-based index for column. + + @return columnName `NSString` value of the name of the column. + */ + +- (NSString * _Nullable)columnNameForIndex:(int)columnIdx; + +/** Result set integer value for column. + + @param columnName `NSString` value of the name of the column. + + @return `int` value of the result set's column. + */ + +- (int)intForColumn:(NSString*)columnName; + +/** Result set integer value for column. + + @param columnIdx Zero-based index for column. + + @return `int` value of the result set's column. + */ + +- (int)intForColumnIndex:(int)columnIdx; + +/** Result set `long` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `long` value of the result set's column. + */ + +- (long)longForColumn:(NSString*)columnName; + +/** Result set long value for column. + + @param columnIdx Zero-based index for column. + + @return `long` value of the result set's column. + */ + +- (long)longForColumnIndex:(int)columnIdx; + +/** Result set `long long int` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `long long int` value of the result set's column. + */ + +- (long long int)longLongIntForColumn:(NSString*)columnName; + +/** Result set `long long int` value for column. + + @param columnIdx Zero-based index for column. + + @return `long long int` value of the result set's column. + */ + +- (long long int)longLongIntForColumnIndex:(int)columnIdx; + +/** Result set `unsigned long long int` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `unsigned long long int` value of the result set's column. + */ + +- (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName; + +/** Result set `unsigned long long int` value for column. + + @param columnIdx Zero-based index for column. + + @return `unsigned long long int` value of the result set's column. + */ + +- (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx; + +/** Result set `BOOL` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `BOOL` value of the result set's column. + */ + +- (BOOL)boolForColumn:(NSString*)columnName; + +/** Result set `BOOL` value for column. + + @param columnIdx Zero-based index for column. + + @return `BOOL` value of the result set's column. + */ + +- (BOOL)boolForColumnIndex:(int)columnIdx; + +/** Result set `double` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `double` value of the result set's column. + + */ + +- (double)doubleForColumn:(NSString*)columnName; + +/** Result set `double` value for column. + + @param columnIdx Zero-based index for column. + + @return `double` value of the result set's column. + + */ + +- (double)doubleForColumnIndex:(int)columnIdx; + +/** Result set `NSString` value for column. + + @param columnName `NSString` value of the name of the column. + + @return String value of the result set's column. + + */ + +- (NSString * _Nullable)stringForColumn:(NSString*)columnName; + +/** Result set `NSString` value for column. + + @param columnIdx Zero-based index for column. + + @return String value of the result set's column. + */ + +- (NSString * _Nullable)stringForColumnIndex:(int)columnIdx; + +/** Result set `NSDate` value for column. + + @param columnName `NSString` value of the name of the column. + + @return Date value of the result set's column. + */ + +- (NSDate * _Nullable)dateForColumn:(NSString*)columnName; + +/** Result set `NSDate` value for column. + + @param columnIdx Zero-based index for column. + + @return Date value of the result set's column. + + */ + +- (NSDate * _Nullable)dateForColumnIndex:(int)columnIdx; + +/** Result set `NSData` value for column. + + This is useful when storing binary data in table (such as image or the like). + + @param columnName `NSString` value of the name of the column. + + @return Data value of the result set's column. + + */ + +- (NSData * _Nullable)dataForColumn:(NSString*)columnName; + +/** Result set `NSData` value for column. + + @param columnIdx Zero-based index for column. + + @return Data value of the result set's column. + */ + +- (NSData * _Nullable)dataForColumnIndex:(int)columnIdx; + +/** Result set `(const unsigned char *)` value for column. + + @param columnName `NSString` value of the name of the column. + + @return `(const unsigned char *)` value of the result set's column. + */ + +- (const unsigned char * _Nullable)UTF8StringForColumn:(NSString*)columnName; + +- (const unsigned char * _Nullable)UTF8StringForColumnName:(NSString*)columnName __deprecated_msg("Use UTF8StringForColumn instead"); + +/** Result set `(const unsigned char *)` value for column. + + @param columnIdx Zero-based index for column. + + @return `(const unsigned char *)` value of the result set's column. + */ + +- (const unsigned char * _Nullable)UTF8StringForColumnIndex:(int)columnIdx; + +/** Result set object for column. + + @param columnName Name of the column. + + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. + + @see objectForKeyedSubscript: + */ + +- (id _Nullable)objectForColumn:(NSString*)columnName; + +- (id _Nullable)objectForColumnName:(NSString*)columnName __deprecated_msg("Use objectForColumn instead"); + +/** Result set object for column. + + @param columnIdx Zero-based index for column. + + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. + + @see objectAtIndexedSubscript: + */ + +- (id _Nullable)objectForColumnIndex:(int)columnIdx; + +/** Result set object for column. + + This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported: + + id result = rs[@"employee_name"]; + + This simplified syntax is equivalent to calling: + + id result = [rs objectForKeyedSubscript:@"employee_name"]; + + which is, it turns out, equivalent to calling: + + id result = [rs objectForColumnName:@"employee_name"]; + + @param columnName `NSString` value of the name of the column. + + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. + */ + +- (id _Nullable)objectForKeyedSubscript:(NSString *)columnName; + +/** Result set object for column. + + This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported: + + id result = rs[0]; + + This simplified syntax is equivalent to calling: + + id result = [rs objectForKeyedSubscript:0]; + + which is, it turns out, equivalent to calling: + + id result = [rs objectForColumnName:0]; + + @param columnIdx Zero-based index for column. + + @return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object. + */ + +- (id _Nullable)objectAtIndexedSubscript:(int)columnIdx; + +/** Result set `NSData` value for column. + + @param columnName `NSString` value of the name of the column. + + @return Data value of the result set's column. + + @warning If you are going to use this data after you iterate over the next row, or after you close the +result set, make sure to make a copy of the data first (or just use ``/``) +If you don't, you're going to be in a world of hurt when you try and use the data. + + */ + +- (NSData * _Nullable)dataNoCopyForColumn:(NSString *)columnName NS_RETURNS_NOT_RETAINED; + +/** Result set `NSData` value for column. + + @param columnIdx Zero-based index for column. + + @return Data value of the result set's column. + + @warning If you are going to use this data after you iterate over the next row, or after you close the + result set, make sure to make a copy of the data first (or just use ``/``) + If you don't, you're going to be in a world of hurt when you try and use the data. + + */ + +- (NSData * _Nullable)dataNoCopyForColumnIndex:(int)columnIdx NS_RETURNS_NOT_RETAINED; + +/** Is the column `NULL`? + + @param columnIdx Zero-based index for column. + + @return `YES` if column is `NULL`; `NO` if not `NULL`. + */ + +- (BOOL)columnIndexIsNull:(int)columnIdx; + +/** Is the column `NULL`? + + @param columnName `NSString` value of the name of the column. + + @return `YES` if column is `NULL`; `NO` if not `NULL`. + */ + +- (BOOL)columnIsNull:(NSString*)columnName; + + +/** Returns a dictionary of the row results mapped to case sensitive keys of the column names. + + @warning The keys to the dictionary are case sensitive of the column names. + */ + +@property (nonatomic, readonly, nullable) NSDictionary *resultDictionary; + +/** Returns a dictionary of the row results + + @see resultDictionary + + @warning **Deprecated**: Please use `` instead. Also, beware that `` is case sensitive! + */ + +- (NSDictionary * _Nullable)resultDict __deprecated_msg("Use resultDictionary instead"); + +///----------------------------- +/// @name Key value coding magic +///----------------------------- + +/** Performs `setValue` to yield support for key value observing. + + @param object The object for which the values will be set. This is the key-value-coding compliant object that you might, for example, observe. + + */ + +- (void)kvcMagic:(id)object; + + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/FMDB/src/fmdb/FMResultSet.m b/Pods/FMDB/src/fmdb/FMResultSet.m new file mode 100644 index 0000000..2231e47 --- /dev/null +++ b/Pods/FMDB/src/fmdb/FMResultSet.m @@ -0,0 +1,432 @@ +#import "FMResultSet.h" +#import "FMDatabase.h" +#import "unistd.h" + +#if FMDB_SQLITE_STANDALONE +#import +#else +#import +#endif + +@interface FMDatabase () +- (void)resultSetDidClose:(FMResultSet *)resultSet; +@end + +@interface FMResultSet () { + NSMutableDictionary *_columnNameToIndexMap; +} +@end + +@implementation FMResultSet + ++ (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB { + + FMResultSet *rs = [[FMResultSet alloc] init]; + + [rs setStatement:statement]; + [rs setParentDB:aDB]; + + NSParameterAssert(![statement inUse]); + [statement setInUse:YES]; // weak reference + + return FMDBReturnAutoreleased(rs); +} + +#if ! __has_feature(objc_arc) +- (void)finalize { + [self close]; + [super finalize]; +} +#endif + +- (void)dealloc { + [self close]; + + FMDBRelease(_query); + _query = nil; + + FMDBRelease(_columnNameToIndexMap); + _columnNameToIndexMap = nil; + +#if ! __has_feature(objc_arc) + [super dealloc]; +#endif +} + +- (void)close { + [_statement reset]; + FMDBRelease(_statement); + _statement = nil; + + // we don't need this anymore... (i think) + //[_parentDB setInUse:NO]; + [_parentDB resultSetDidClose:self]; + _parentDB = nil; +} + +- (int)columnCount { + return sqlite3_column_count([_statement statement]); +} + +- (NSMutableDictionary *)columnNameToIndexMap { + if (!_columnNameToIndexMap) { + int columnCount = sqlite3_column_count([_statement statement]); + _columnNameToIndexMap = [[NSMutableDictionary alloc] initWithCapacity:(NSUInteger)columnCount]; + int columnIdx = 0; + for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { + [_columnNameToIndexMap setObject:[NSNumber numberWithInt:columnIdx] + forKey:[[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)] lowercaseString]]; + } + } + return _columnNameToIndexMap; +} + +- (void)kvcMagic:(id)object { + + int columnCount = sqlite3_column_count([_statement statement]); + + int columnIdx = 0; + for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { + + const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); + + // check for a null row + if (c) { + NSString *s = [NSString stringWithUTF8String:c]; + + [object setValue:s forKey:[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]]; + } + } +} + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-implementations" + +- (NSDictionary *)resultDict { + + NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); + + if (num_cols > 0) { + NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; + + NSEnumerator *columnNames = [[self columnNameToIndexMap] keyEnumerator]; + NSString *columnName = nil; + while ((columnName = [columnNames nextObject])) { + id objectValue = [self objectForColumnName:columnName]; + [dict setObject:objectValue forKey:columnName]; + } + + return FMDBReturnAutoreleased([dict copy]); + } + else { + NSLog(@"Warning: There seem to be no columns in this set."); + } + + return nil; +} + +#pragma clang diagnostic pop + +- (NSDictionary*)resultDictionary { + + NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]); + + if (num_cols > 0) { + NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols]; + + int columnCount = sqlite3_column_count([_statement statement]); + + int columnIdx = 0; + for (columnIdx = 0; columnIdx < columnCount; columnIdx++) { + + NSString *columnName = [NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]; + id objectValue = [self objectForColumnIndex:columnIdx]; + [dict setObject:objectValue forKey:columnName]; + } + + return dict; + } + else { + NSLog(@"Warning: There seem to be no columns in this set."); + } + + return nil; +} + + + + +- (BOOL)next { + return [self nextWithError:nil]; +} + +- (BOOL)nextWithError:(NSError **)outErr { + + int rc = sqlite3_step([_statement statement]); + + if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) { + NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [_parentDB databasePath]); + NSLog(@"Database busy"); + if (outErr) { + *outErr = [_parentDB lastError]; + } + } + else if (SQLITE_DONE == rc || SQLITE_ROW == rc) { + // all is well, let's return. + } + else if (SQLITE_ERROR == rc) { + NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); + if (outErr) { + *outErr = [_parentDB lastError]; + } + } + else if (SQLITE_MISUSE == rc) { + // uh oh. + NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); + if (outErr) { + if (_parentDB) { + *outErr = [_parentDB lastError]; + } + else { + // If 'next' or 'nextWithError' is called after the result set is closed, + // we need to return the appropriate error. + NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:@"parentDB does not exist" forKey:NSLocalizedDescriptionKey]; + *outErr = [NSError errorWithDomain:@"FMDatabase" code:SQLITE_MISUSE userInfo:errorMessage]; + } + + } + } + else { + // wtf? + NSLog(@"Unknown error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle])); + if (outErr) { + *outErr = [_parentDB lastError]; + } + } + + + if (rc != SQLITE_ROW) { + [self close]; + } + + return (rc == SQLITE_ROW); +} + +- (BOOL)hasAnotherRow { + return sqlite3_errcode([_parentDB sqliteHandle]) == SQLITE_ROW; +} + +- (int)columnIndexForName:(NSString*)columnName { + columnName = [columnName lowercaseString]; + + NSNumber *n = [[self columnNameToIndexMap] objectForKey:columnName]; + + if (n != nil) { + return [n intValue]; + } + + NSLog(@"Warning: I could not find the column named '%@'.", columnName); + + return -1; +} + +- (int)intForColumn:(NSString*)columnName { + return [self intForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (int)intForColumnIndex:(int)columnIdx { + return sqlite3_column_int([_statement statement], columnIdx); +} + +- (long)longForColumn:(NSString*)columnName { + return [self longForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (long)longForColumnIndex:(int)columnIdx { + return (long)sqlite3_column_int64([_statement statement], columnIdx); +} + +- (long long int)longLongIntForColumn:(NSString*)columnName { + return [self longLongIntForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (long long int)longLongIntForColumnIndex:(int)columnIdx { + return sqlite3_column_int64([_statement statement], columnIdx); +} + +- (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName { + return [self unsignedLongLongIntForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx { + return (unsigned long long int)[self longLongIntForColumnIndex:columnIdx]; +} + +- (BOOL)boolForColumn:(NSString*)columnName { + return [self boolForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (BOOL)boolForColumnIndex:(int)columnIdx { + return ([self intForColumnIndex:columnIdx] != 0); +} + +- (double)doubleForColumn:(NSString*)columnName { + return [self doubleForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (double)doubleForColumnIndex:(int)columnIdx { + return sqlite3_column_double([_statement statement], columnIdx); +} + +- (NSString *)stringForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx); + + if (!c) { + // null row. + return nil; + } + + return [NSString stringWithUTF8String:c]; +} + +- (NSString*)stringForColumn:(NSString*)columnName { + return [self stringForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (NSDate*)dateForColumn:(NSString*)columnName { + return [self dateForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (NSDate*)dateForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + return [_parentDB hasDateFormatter] ? [_parentDB dateFromString:[self stringForColumnIndex:columnIdx]] : [NSDate dateWithTimeIntervalSince1970:[self doubleForColumnIndex:columnIdx]]; +} + + +- (NSData*)dataForColumn:(NSString*)columnName { + return [self dataForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (NSData*)dataForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx); + int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); + + if (dataBuffer == NULL) { + return nil; + } + + return [NSData dataWithBytes:(const void *)dataBuffer length:(NSUInteger)dataSize]; +} + + +- (NSData*)dataNoCopyForColumn:(NSString*)columnName { + return [self dataNoCopyForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (NSData*)dataNoCopyForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx); + int dataSize = sqlite3_column_bytes([_statement statement], columnIdx); + + NSData *data = [NSData dataWithBytesNoCopy:(void *)dataBuffer length:(NSUInteger)dataSize freeWhenDone:NO]; + + return data; +} + + +- (BOOL)columnIndexIsNull:(int)columnIdx { + return sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL; +} + +- (BOOL)columnIsNull:(NSString*)columnName { + return [self columnIndexIsNull:[self columnIndexForName:columnName]]; +} + +- (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx { + + if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0) || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + return sqlite3_column_text([_statement statement], columnIdx); +} + +- (const unsigned char *)UTF8StringForColumn:(NSString*)columnName { + return [self UTF8StringForColumnIndex:[self columnIndexForName:columnName]]; +} + +- (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName { + return [self UTF8StringForColumn:columnName]; +} + +- (id)objectForColumnIndex:(int)columnIdx { + if (columnIdx < 0 || columnIdx >= sqlite3_column_count([_statement statement])) { + return nil; + } + + int columnType = sqlite3_column_type([_statement statement], columnIdx); + + id returnValue = nil; + + if (columnType == SQLITE_INTEGER) { + returnValue = [NSNumber numberWithLongLong:[self longLongIntForColumnIndex:columnIdx]]; + } + else if (columnType == SQLITE_FLOAT) { + returnValue = [NSNumber numberWithDouble:[self doubleForColumnIndex:columnIdx]]; + } + else if (columnType == SQLITE_BLOB) { + returnValue = [self dataForColumnIndex:columnIdx]; + } + else { + //default to a string for everything else + returnValue = [self stringForColumnIndex:columnIdx]; + } + + if (returnValue == nil) { + returnValue = [NSNull null]; + } + + return returnValue; +} + +- (id)objectForColumnName:(NSString*)columnName { + return [self objectForColumn:columnName]; +} + +- (id)objectForColumn:(NSString*)columnName { + return [self objectForColumnIndex:[self columnIndexForName:columnName]]; +} + +// returns autoreleased NSString containing the name of the column in the result set +- (NSString*)columnNameForIndex:(int)columnIdx { + return [NSString stringWithUTF8String: sqlite3_column_name([_statement statement], columnIdx)]; +} + +- (id)objectAtIndexedSubscript:(int)columnIdx { + return [self objectForColumnIndex:columnIdx]; +} + +- (id)objectForKeyedSubscript:(NSString *)columnName { + return [self objectForColumn:columnName]; +} + + +@end diff --git a/Pods/Headers/Private/JPush/JPUSHService.h b/Pods/Headers/Private/JPush/JPUSHService.h new file mode 120000 index 0000000..48feb70 --- /dev/null +++ b/Pods/Headers/Private/JPush/JPUSHService.h @@ -0,0 +1 @@ +../../../JPush/JPUSHService.h \ No newline at end of file diff --git a/Pods/Headers/Private/WechatOpenSDK/WXApi.h b/Pods/Headers/Private/WechatOpenSDK/WXApi.h new file mode 120000 index 0000000..b7a3bfe --- /dev/null +++ b/Pods/Headers/Private/WechatOpenSDK/WXApi.h @@ -0,0 +1 @@ +../../../WechatOpenSDK/WechatSDK1.8.2/WXApi.h \ No newline at end of file diff --git a/Pods/Headers/Private/WechatOpenSDK/WXApiObject.h b/Pods/Headers/Private/WechatOpenSDK/WXApiObject.h new file mode 120000 index 0000000..84ab6c1 --- /dev/null +++ b/Pods/Headers/Private/WechatOpenSDK/WXApiObject.h @@ -0,0 +1 @@ +../../../WechatOpenSDK/WechatSDK1.8.2/WXApiObject.h \ No newline at end of file diff --git a/Pods/Headers/Private/WechatOpenSDK/WechatAuthSDK.h b/Pods/Headers/Private/WechatOpenSDK/WechatAuthSDK.h new file mode 120000 index 0000000..7d307cc --- /dev/null +++ b/Pods/Headers/Private/WechatOpenSDK/WechatAuthSDK.h @@ -0,0 +1 @@ +../../../WechatOpenSDK/WechatSDK1.8.2/WechatAuthSDK.h \ No newline at end of file diff --git a/Pods/Headers/Public/JPush/JPUSHService.h b/Pods/Headers/Public/JPush/JPUSHService.h new file mode 120000 index 0000000..48feb70 --- /dev/null +++ b/Pods/Headers/Public/JPush/JPUSHService.h @@ -0,0 +1 @@ +../../../JPush/JPUSHService.h \ No newline at end of file diff --git a/Pods/Headers/Public/WechatOpenSDK/WXApi.h b/Pods/Headers/Public/WechatOpenSDK/WXApi.h new file mode 120000 index 0000000..b7a3bfe --- /dev/null +++ b/Pods/Headers/Public/WechatOpenSDK/WXApi.h @@ -0,0 +1 @@ +../../../WechatOpenSDK/WechatSDK1.8.2/WXApi.h \ No newline at end of file diff --git a/Pods/Headers/Public/WechatOpenSDK/WXApiObject.h b/Pods/Headers/Public/WechatOpenSDK/WXApiObject.h new file mode 120000 index 0000000..84ab6c1 --- /dev/null +++ b/Pods/Headers/Public/WechatOpenSDK/WXApiObject.h @@ -0,0 +1 @@ +../../../WechatOpenSDK/WechatSDK1.8.2/WXApiObject.h \ No newline at end of file diff --git a/Pods/Headers/Public/WechatOpenSDK/WechatAuthSDK.h b/Pods/Headers/Public/WechatOpenSDK/WechatAuthSDK.h new file mode 120000 index 0000000..7d307cc --- /dev/null +++ b/Pods/Headers/Public/WechatOpenSDK/WechatAuthSDK.h @@ -0,0 +1 @@ +../../../WechatOpenSDK/WechatSDK1.8.2/WechatAuthSDK.h \ No newline at end of file diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQNSArray+Sort.h b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQNSArray+Sort.h new file mode 100644 index 0000000..4d7c374 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQNSArray+Sort.h @@ -0,0 +1,47 @@ +// +// IQNSArray+Sort.h +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 + +@class UIView; + +/** + UIView.subviews sorting category. + */ +@interface NSArray (IQ_NSArray_Sort) + +///-------------- +/// @name Sorting +///-------------- + +/** + Returns the array by sorting the UIView's by their tag property. + */ +@property (nonatomic, readonly, copy) NSArray<__kindof UIView*> * _Nonnull sortedArrayByTag; + +/** + Returns the array by sorting the UIView's by their tag property. + */ +@property (nonatomic, readonly, copy) NSArray<__kindof UIView*> * _Nonnull sortedArrayByPosition; + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQNSArray+Sort.m b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQNSArray+Sort.m new file mode 100644 index 0000000..7ca0cdd --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQNSArray+Sort.m @@ -0,0 +1,71 @@ +// +// IQNSArray+Sort.m +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQNSArray+Sort.h" +#import "IQUIView+Hierarchy.h" + +#import + +@implementation NSArray (IQ_NSArray_Sort) + +- (NSArray*)sortedArrayByTag +{ + return [self sortedArrayUsingComparator:^NSComparisonResult(UIView *view1, UIView *view2) { + + if ([view1 respondsToSelector:@selector(tag)] && [view2 respondsToSelector:@selector(tag)]) + { + if ([view1 tag] < [view2 tag]) return NSOrderedAscending; + + else if ([view1 tag] > [view2 tag]) return NSOrderedDescending; + + else return NSOrderedSame; + } + else + return NSOrderedSame; + }]; +} + +- (NSArray*)sortedArrayByPosition +{ + return [self sortedArrayUsingComparator:^NSComparisonResult(UIView *view1, UIView *view2) { + + CGFloat x1 = CGRectGetMinX(view1.frame); + CGFloat y1 = CGRectGetMinY(view1.frame); + CGFloat x2 = CGRectGetMinX(view2.frame); + CGFloat y2 = CGRectGetMinY(view2.frame); + + if (y1 < y2) return NSOrderedAscending; + + else if (y1 > y2) return NSOrderedDescending; + + //Else both y are same so checking for x positions + else if (x1 < x2) return NSOrderedAscending; + + else if (x1 > x2) return NSOrderedDescending; + + else return NSOrderedSame; + }]; +} + + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIScrollView+Additions.h b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIScrollView+Additions.h new file mode 100644 index 0000000..4e3c028 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIScrollView+Additions.h @@ -0,0 +1,40 @@ +// +// IQUIScrollView+Additions.h +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 + + +@interface UIScrollView (Additions) + +/** + If YES, then scrollview will ignore scrolling (simply not scroll it) for adjusting textfield position. Default is NO. + */ +@property(nonatomic, assign) BOOL shouldIgnoreScrollingAdjustment; + +/** + Restore scrollViewContentOffset when resigning from scrollView. Default is NO. + */ +@property(nonatomic, assign) BOOL shouldRestoreScrollViewContentOffset; + + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIScrollView+Additions.m b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIScrollView+Additions.m new file mode 100644 index 0000000..bfe1fab --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIScrollView+Additions.m @@ -0,0 +1,53 @@ +// +// IQUIScrollView+Additions.m +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQUIScrollView+Additions.h" +#import + +@implementation UIScrollView (Additions) + +-(void)setShouldIgnoreScrollingAdjustment:(BOOL)shouldIgnoreScrollingAdjustment +{ + objc_setAssociatedObject(self, @selector(shouldIgnoreScrollingAdjustment), @(shouldIgnoreScrollingAdjustment), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +-(BOOL)shouldIgnoreScrollingAdjustment +{ + NSNumber *shouldIgnoreScrollingAdjustment = objc_getAssociatedObject(self, @selector(shouldIgnoreScrollingAdjustment)); + + return [shouldIgnoreScrollingAdjustment boolValue]; +} + +-(void)setShouldRestoreScrollViewContentOffset:(BOOL)shouldRestoreScrollViewContentOffset +{ + objc_setAssociatedObject(self, @selector(shouldRestoreScrollViewContentOffset), @(shouldRestoreScrollViewContentOffset), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +-(BOOL)shouldRestoreScrollViewContentOffset +{ + NSNumber *shouldRestoreScrollViewContentOffset = objc_getAssociatedObject(self, @selector(shouldRestoreScrollViewContentOffset)); + + return [shouldRestoreScrollViewContentOffset boolValue]; +} + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUITextFieldView+Additions.h b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUITextFieldView+Additions.h new file mode 100644 index 0000000..8da65e3 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUITextFieldView+Additions.h @@ -0,0 +1,62 @@ +// +// IQUITextFieldView+Additions.h +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 +#import "IQKeyboardManagerConstants.h" + +/** + UIView category for managing UITextField/UITextView + */ + +@interface UIView (Additions) + +/** + To set customized distance from keyboard for textField/textView. Can't be less than zero + */ +@property(nonatomic, assign) CGFloat keyboardDistanceFromTextField; + +/** + If shouldIgnoreSwitchingByNextPrevious is YES then library will ignore this textField/textView while moving to other textField/textView using keyboard toolbar next previous buttons. Default is NO + */ +@property(nonatomic, assign) BOOL ignoreSwitchingByNextPrevious; + +///** +// Override Enable/disable managing distance between keyboard and textField behaviour for this particular textField. +// */ +//@property(nonatomic, assign) IQEnableMode enableMode; + +/** + Override resigns Keyboard on touching outside of UITextField/View behaviour for this particular textField. + */ +@property(nonatomic, assign) IQEnableMode shouldResignOnTouchOutsideMode; + +@end + +///------------------------------------------- +/// @name Custom KeyboardDistanceFromTextField +///------------------------------------------- + +/** + Uses default keyboard distance for textField. + */ +extern CGFloat const kIQUseDefaultKeyboardDistance; diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUITextFieldView+Additions.m b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUITextFieldView+Additions.m new file mode 100644 index 0000000..d17bfaf --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUITextFieldView+Additions.m @@ -0,0 +1,90 @@ +// +// IQUITextFieldView+Additions.m +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQUITextFieldView+Additions.h" +#import + +@implementation UIView (Additions) + +-(void)setKeyboardDistanceFromTextField:(CGFloat)keyboardDistanceFromTextField +{ + //Can't be less than zero. Minimum is zero. + keyboardDistanceFromTextField = MAX(keyboardDistanceFromTextField, 0); + + objc_setAssociatedObject(self, @selector(keyboardDistanceFromTextField), @(keyboardDistanceFromTextField), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +-(CGFloat)keyboardDistanceFromTextField +{ + NSNumber *keyboardDistanceFromTextField = objc_getAssociatedObject(self, @selector(keyboardDistanceFromTextField)); + + return (keyboardDistanceFromTextField)?[keyboardDistanceFromTextField floatValue]:kIQUseDefaultKeyboardDistance; +} + +-(void)setIgnoreSwitchingByNextPrevious:(BOOL)ignoreSwitchingByNextPrevious +{ + objc_setAssociatedObject(self, @selector(ignoreSwitchingByNextPrevious), @(ignoreSwitchingByNextPrevious), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +-(BOOL)ignoreSwitchingByNextPrevious +{ + NSNumber *ignoreSwitchingByNextPrevious = objc_getAssociatedObject(self, @selector(ignoreSwitchingByNextPrevious)); + + return [ignoreSwitchingByNextPrevious boolValue]; +} + +//-(void)setEnableMode:(IQEnableMode)enableMode +//{ +// objc_setAssociatedObject(self, @selector(enableMode), @(enableMode), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +//} +// +//-(IQEnableMode)enableMode +//{ +// NSNumber *enableMode = objc_getAssociatedObject(self, @selector(enableMode)); +// +// return [enableMode unsignedIntegerValue]; +//} + +-(void)setShouldResignOnTouchOutsideMode:(IQEnableMode)shouldResignOnTouchOutsideMode +{ + objc_setAssociatedObject(self, @selector(shouldResignOnTouchOutsideMode), @(shouldResignOnTouchOutsideMode), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +-(IQEnableMode)shouldResignOnTouchOutsideMode +{ + NSNumber *shouldResignOnTouchOutsideMode = objc_getAssociatedObject(self, @selector(shouldResignOnTouchOutsideMode)); + + return [shouldResignOnTouchOutsideMode unsignedIntegerValue]; +} + +@end + +///------------------------------------ +/// @name keyboardDistanceFromTextField +///------------------------------------ + +/** + Uses default keyboard distance for textField. + */ +CGFloat const kIQUseDefaultKeyboardDistance = CGFLOAT_MAX; + diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIView+Hierarchy.h b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIView+Hierarchy.h new file mode 100644 index 0000000..9598fc6 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIView+Hierarchy.h @@ -0,0 +1,134 @@ +// +// IQUIView+Hierarchy.h +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 +#import +#import "IQKeyboardManagerConstants.h" + +@class UICollectionView, UIScrollView, UITableView, UISearchBar, NSArray; + +/** + UIView hierarchy category. + */ +@interface UIView (IQ_UIView_Hierarchy) + +///---------------------- +/// @name viewControllers +///---------------------- + +/** + Returns the UIViewController object that manages the receiver. + */ +@property (nullable, nonatomic, readonly, strong) UIViewController *viewContainingController; + +/** + Returns the topMost UIViewController object in hierarchy. + */ +@property (nullable, nonatomic, readonly, strong) UIViewController *topMostController; + +/** + Returns the UIViewController object that is actually the parent of this object. Most of the time it's the viewController object which actually contains it, but result may be different if it's viewController is added as childViewController of another viewController. + */ +@property (nullable, nonatomic, readonly, strong) UIViewController *parentContainerViewController; + +///----------------------------------- +/// @name Superviews/Subviews/Siglings +///----------------------------------- + +/** + Returns the superView of provided class type. + */ +-(nullable UIView*)superviewOfClassType:(nonnull Class)classType; + +/** + Returns all siblings of the receiver which canBecomeFirstResponder. + */ +@property (nonnull, nonatomic, readonly, copy) NSArray<__kindof UIView*> *responderSiblings; + +/** + Returns all deep subViews of the receiver which canBecomeFirstResponder. + */ +@property (nonnull, nonatomic, readonly, copy) NSArray<__kindof UIView*> *deepResponderViews; + +///------------------------- +/// @name Special TextFields +///------------------------- + +/** + Returns searchBar if receiver object is UISearchBarTextField, otherwise return nil. + */ +@property (nullable, nonatomic, readonly) UISearchBar *searchBar; + +/** + Returns YES if the receiver object is UIAlertSheetTextField, otherwise return NO. + */ +@property (nonatomic, getter=isAlertViewTextField, readonly) BOOL alertViewTextField; + +///---------------- +/// @name Transform +///---------------- + +/** + Returns current view transform with respect to the 'toView'. + */ +-(CGAffineTransform)convertTransformToView:(nullable UIView*)toView; + +///----------------- +/// @name Hierarchy +///----------------- + +/** + Returns a string that represent the information about it's subview's hierarchy. You can use this method to debug the subview's positions. + */ +@property (nonnull, nonatomic, readonly, copy) NSString *subHierarchy; + +/** + Returns an string that represent the information about it's upper hierarchy. You can use this method to debug the superview's positions. + */ +@property (nonnull, nonatomic, readonly, copy) NSString *superHierarchy; + +/** + Returns an string that represent the information about it's frame positions. You can use this method to debug self positions. + */ +@property (nonnull, nonatomic, readonly, copy) NSString *debugHierarchy; + +@end + + +@interface UIViewController (IQ_UIView_Hierarchy) + +-(nullable UIViewController*)parentIQContainerViewController; + +@end + +/** + NSObject category to used for logging purposes + */ +@interface NSObject (IQ_Logging) + +/** + Short description for logging purpose. + */ +@property (nonnull, nonatomic, readonly, copy) NSString *_IQDescription; + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIView+Hierarchy.m b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIView+Hierarchy.m new file mode 100644 index 0000000..54a5433 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIView+Hierarchy.m @@ -0,0 +1,437 @@ +// +// IQUIView+Hierarchy.m +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQUIView+Hierarchy.h" +#import "IQUITextFieldView+Additions.h" + +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import + +#import + +#import "IQNSArray+Sort.h" + +@implementation UIView (IQ_UIView_Hierarchy) + +-(UIViewController*)viewContainingController +{ + UIResponder *nextResponder = self; + + do + { + nextResponder = [nextResponder nextResponder]; + + if ([nextResponder isKindOfClass:[UIViewController class]]) + return (UIViewController*)nextResponder; + + } while (nextResponder); + + return nil; +} + +-(UIViewController *)topMostController +{ + NSMutableArray *controllersHierarchy = [[NSMutableArray alloc] init]; + + UIViewController *topController = self.window.rootViewController; + + if (topController) + { + [controllersHierarchy addObject:topController]; + } + + while ([topController presentedViewController]) { + + topController = [topController presentedViewController]; + [controllersHierarchy addObject:topController]; + } + + UIViewController *matchController = [self viewContainingController]; + + while (matchController && [controllersHierarchy containsObject:matchController] == NO) + { + do + { + matchController = (UIViewController*)[matchController nextResponder]; + + } while (matchController && [matchController isKindOfClass:[UIViewController class]] == NO); + } + + return matchController; +} + +-(UIViewController *)parentContainerViewController +{ + UIViewController *matchController = [self viewContainingController]; + + UIViewController *parentContainerViewController = nil; + + if (matchController.navigationController) + { + UINavigationController *navController = matchController.navigationController; + + while (navController.navigationController) { + navController = navController.navigationController; + } + + UIViewController *parentController = navController; + + UIViewController *parentParentController = parentController.parentViewController; + + while (parentParentController && + ([parentParentController isKindOfClass:[UINavigationController class]] == NO && + [parentParentController isKindOfClass:[UITabBarController class]] == NO && + [parentParentController isKindOfClass:[UISplitViewController class]] == NO)) + { + parentController = parentParentController; + parentParentController = parentController.parentViewController; + } + + if (navController == parentController) + { + parentContainerViewController = navController.topViewController; + } + else + { + parentContainerViewController = parentController; + } + } + else if (matchController.tabBarController) + { + if ([matchController.tabBarController.selectedViewController isKindOfClass:[UINavigationController class]]) + { + parentContainerViewController = [(UINavigationController*)matchController.tabBarController.selectedViewController topViewController]; + } + else + { + parentContainerViewController = matchController.tabBarController.selectedViewController; + } + } + else + { + UIViewController *matchParentController = matchController.parentViewController; + + while (matchParentController && + ([matchParentController isKindOfClass:[UINavigationController class]] == NO && + [matchParentController isKindOfClass:[UITabBarController class]] == NO && + [matchParentController isKindOfClass:[UISplitViewController class]] == NO)) + { + matchController = matchParentController; + matchParentController = matchController.parentViewController; + } + + parentContainerViewController = matchController; + } + + UIViewController *finalController = [parentContainerViewController parentIQContainerViewController] ?: parentContainerViewController; + + return finalController; +} + +-(UIView*)superviewOfClassType:(Class)classType +{ + UIView *superview = self.superview; + + while (superview) + { + if ([superview isKindOfClass:classType]) + { + //If it's UIScrollView, then validating for special cases + if ([superview isKindOfClass:[UIScrollView class]]) + { + NSString *classNameString = NSStringFromClass([superview class]); + + // If it's not UITableViewWrapperView class, this is internal class which is actually manage in UITableview. The speciality of this class is that it's superview is UITableView. + // If it's not UITableViewCellScrollView class, this is internal class which is actually manage in UITableviewCell. The speciality of this class is that it's superview is UITableViewCell. + //If it's not _UIQueuingScrollView class, actually we validate for _ prefix which usually used by Apple internal classes + if ([superview.superview isKindOfClass:[UITableView class]] == NO && + [superview.superview isKindOfClass:[UITableViewCell class]] == NO && + [classNameString hasPrefix:@"_"] == NO) + { + return superview; + } + } + else + { + return superview; + } + } + + superview = superview.superview; + } + + return nil; +} + +-(BOOL)_IQcanBecomeFirstResponder +{ + BOOL _IQcanBecomeFirstResponder = NO; + + if ([self isKindOfClass:[UITextField class]]) + { + _IQcanBecomeFirstResponder = [(UITextField*)self isEnabled]; + } + else if ([self isKindOfClass:[UITextView class]]) + { + _IQcanBecomeFirstResponder = [(UITextView*)self isEditable]; + } + + if (_IQcanBecomeFirstResponder == YES) + { + _IQcanBecomeFirstResponder = ([self isUserInteractionEnabled] && ![self isHidden] && [self alpha]!=0.0 && ![self isAlertViewTextField] && !self.searchBar); + } + + return _IQcanBecomeFirstResponder; +} + +- (NSArray*)responderSiblings +{ + // Getting all siblings + NSArray *siblings = self.superview.subviews; + + //Array of (UITextField/UITextView's). + NSMutableArray *tempTextFields = [[NSMutableArray alloc] init]; + + for (UIView *textField in siblings) + if ((textField == self || textField.ignoreSwitchingByNextPrevious == NO) && [textField _IQcanBecomeFirstResponder]) + [tempTextFields addObject:textField]; + + return tempTextFields; +} + +- (NSArray*)deepResponderViews +{ + NSMutableArray *textFields = [[NSMutableArray alloc] init]; + + for (UIView *textField in self.subviews) + { + if ((textField == self || textField.ignoreSwitchingByNextPrevious == NO) && [textField _IQcanBecomeFirstResponder]) + { + [textFields addObject:textField]; + } + + //Sometimes there are hidden or disabled views and textField inside them still recorded, so we added some more validations here (Bug ID: #458) + //Uncommented else (Bug ID: #625) + if (textField.subviews.count && [textField isUserInteractionEnabled] && ![textField isHidden] && [textField alpha]!=0.0) + { + [textFields addObjectsFromArray:[textField deepResponderViews]]; + } + } + + //subviews are returning in incorrect order. Sorting according the frames 'y'. + return [textFields sortedArrayUsingComparator:^NSComparisonResult(UIView *view1, UIView *view2) { + + CGRect frame1 = [view1 convertRect:view1.bounds toView:self]; + CGRect frame2 = [view2 convertRect:view2.bounds toView:self]; + + CGFloat x1 = CGRectGetMinX(frame1); + CGFloat y1 = CGRectGetMinY(frame1); + CGFloat x2 = CGRectGetMinX(frame2); + CGFloat y2 = CGRectGetMinY(frame2); + + if (y1 < y2) return NSOrderedAscending; + + else if (y1 > y2) return NSOrderedDescending; + + //Else both y are same so checking for x positions + else if (x1 < x2) return NSOrderedAscending; + + else if (x1 > x2) return NSOrderedDescending; + + else return NSOrderedSame; + }]; + + return textFields; +} + +-(CGAffineTransform)convertTransformToView:(UIView*)toView +{ + if (toView == nil) + { + toView = self.window; + } + + CGAffineTransform myTransform = CGAffineTransformIdentity; + + //My Transform + { + UIView *superView = [self superview]; + + if (superView) myTransform = CGAffineTransformConcat(self.transform, [superView convertTransformToView:nil]); + else myTransform = self.transform; + } + + CGAffineTransform viewTransform = CGAffineTransformIdentity; + + //view Transform + { + UIView *superView = [toView superview]; + + if (superView) viewTransform = CGAffineTransformConcat(toView.transform, [superView convertTransformToView:nil]); + else if (toView) viewTransform = toView.transform; + } + + return CGAffineTransformConcat(myTransform, CGAffineTransformInvert(viewTransform)); +} + + +- (NSInteger)depth +{ + NSInteger depth = 0; + + if ([self superview]) + { + depth = [[self superview] depth] + 1; + } + + return depth; +} + +- (NSString *)subHierarchy +{ + NSMutableString *debugInfo = [[NSMutableString alloc] initWithString:@"\n"]; + NSInteger depth = [self depth]; + + for (int counter = 0; counter < depth; counter ++) [debugInfo appendString:@"| "]; + + [debugInfo appendString:[self debugHierarchy]]; + + for (UIView *subview in self.subviews) + { + [debugInfo appendString:[subview subHierarchy]]; + } + + return debugInfo; +} + +- (NSString *)superHierarchy +{ + NSMutableString *debugInfo = [[NSMutableString alloc] init]; + + if (self.superview) + { + [debugInfo appendString:[self.superview superHierarchy]]; + } + else + { + [debugInfo appendString:@"\n"]; + } + + NSInteger depth = [self depth]; + + for (int counter = 0; counter < depth; counter ++) [debugInfo appendString:@"| "]; + + [debugInfo appendString:[self debugHierarchy]]; + + [debugInfo appendString:@"\n"]; + + return debugInfo; +} + +-(NSString *)debugHierarchy +{ + NSMutableString *debugInfo = [[NSMutableString alloc] init]; + + [debugInfo appendFormat:@"%@: ( %.0f, %.0f, %.0f, %.0f )",NSStringFromClass([self class]), CGRectGetMinX(self.frame), CGRectGetMinY(self.frame), CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)]; + + if ([self isKindOfClass:[UIScrollView class]]) + { + UIScrollView *scrollView = (UIScrollView*)self; + [debugInfo appendFormat:@"%@: ( %.0f, %.0f )",NSStringFromSelector(@selector(contentSize)),scrollView.contentSize.width,scrollView.contentSize.height]; + } + + if (CGAffineTransformEqualToTransform(self.transform, CGAffineTransformIdentity) == false) + { + [debugInfo appendFormat:@"%@: %@",NSStringFromSelector(@selector(transform)),NSStringFromCGAffineTransform(self.transform)]; + } + + return debugInfo; +} + +-(UISearchBar *)searchBar +{ + UIResponder *searchBar = [self nextResponder]; + + while (searchBar) + { + if ([searchBar isKindOfClass:[UISearchBar class]]) + { + return (UISearchBar*)searchBar; + } + else if ([searchBar isKindOfClass:[UIViewController class]]) //If found viewcontroller but still not found UISearchBar then it's not the search bar textfield + { + break; + } + + searchBar = [searchBar nextResponder]; + } + + return nil; +} + +-(BOOL)isAlertViewTextField +{ + UIResponder *alertViewController = [self viewContainingController]; + + BOOL isAlertViewTextField = NO; + while (alertViewController && isAlertViewTextField == NO) + { + if ([alertViewController isKindOfClass:[UIAlertController class]]) + { + isAlertViewTextField = YES; + break; + } + + alertViewController = [alertViewController nextResponder]; + } + + return isAlertViewTextField; +} + +@end + +@implementation UIViewController (IQ_UIView_Hierarchy) + +-(nullable UIViewController*)parentIQContainerViewController +{ + return self; +} + +@end + +@implementation NSObject (IQ_Logging) + +-(NSString *)_IQDescription +{ + return [NSString stringWithFormat:@"<%@ %p>",NSStringFromClass([self class]),self]; +} + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIViewController+Additions.h b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIViewController+Additions.h new file mode 100644 index 0000000..f7e9893 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIViewController+Additions.h @@ -0,0 +1,39 @@ +// +// IQUIViewController+Additions.h +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 + +@class NSLayoutConstraint; + +@interface UIViewController (Additions) + +/** + Top/Bottom Layout constraint which help library to manage keyboardTextField distance + + @message Library is internally handle Safe Area in iOS11 if `canAdjustAdditionalSafeAreaInsets = YES` and there is no need to do any tweak if you already migrated to use Safe Area + + @deprecated Due to change in core-logic of handling distance between textField and keyboard distance, this layout contraint tweak is no longer needed and things will just work out of the box regardless of constraint pinned with safeArea/layoutGuide/superview. +*/ +@property(nullable, nonatomic, strong) IBOutlet NSLayoutConstraint *IQLayoutGuideConstraint __attribute__((deprecated("Due to change in core-logic of handling distance between textField and keyboard distance, this layout contraint tweak is no longer needed and things will just work out of the box regardless of constraint pinned with safeArea/layoutGuide/superview."))); + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIViewController+Additions.m b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIViewController+Additions.m new file mode 100644 index 0000000..767d10a --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/Categories/IQUIViewController+Additions.m @@ -0,0 +1,40 @@ +// +// IQUIViewController+Additions.m +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQUIViewController+Additions.h" +#import +#import + +@implementation UIViewController (Additions) + +-(void)setIQLayoutGuideConstraint:(NSLayoutConstraint *)IQLayoutGuideConstraint +{ + objc_setAssociatedObject(self, @selector(IQLayoutGuideConstraint), IQLayoutGuideConstraint, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +-(NSLayoutConstraint *)IQLayoutGuideConstraint +{ + return objc_getAssociatedObject(self, @selector(IQLayoutGuideConstraint)); +} + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Constants/IQKeyboardManagerConstants.h b/Pods/IQKeyboardManager/IQKeyboardManager/Constants/IQKeyboardManagerConstants.h new file mode 100644 index 0000000..548f16f --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/Constants/IQKeyboardManagerConstants.h @@ -0,0 +1,156 @@ +// +// IQKeyboardManagerConstants.h +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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. + +#ifndef IQKeyboardManagerConstants_h +#define IQKeyboardManagerConstants_h + +#import + +///----------------------------------- +/// @name IQAutoToolbarManageBehaviour +///----------------------------------- + +/** + `IQAutoToolbarBySubviews` + Creates Toolbar according to subview's hirarchy of Textfield's in view. + + `IQAutoToolbarByTag` + Creates Toolbar according to tag property of TextField's. + + `IQAutoToolbarByPosition` + Creates Toolbar according to the y,x position of textField in it's superview coordinate. + */ +typedef NS_ENUM(NSInteger, IQAutoToolbarManageBehaviour) { + IQAutoToolbarBySubviews, + IQAutoToolbarByTag, + IQAutoToolbarByPosition, +}; + +/** + `IQPreviousNextDisplayModeDefault` + Show NextPrevious when there are more than 1 textField otherwise hide. + + `IQPreviousNextDisplayModeAlwaysHide` + Do not show NextPrevious buttons in any case. + + `IQPreviousNextDisplayModeAlwaysShow` + Always show nextPrevious buttons, if there are more than 1 textField then both buttons will be visible but will be shown as disabled. + */ +typedef NS_ENUM(NSUInteger, IQPreviousNextDisplayMode) { + IQPreviousNextDisplayModeDefault, + IQPreviousNextDisplayModeAlwaysHide, + IQPreviousNextDisplayModeAlwaysShow, +}; + +/** + `IQEnableModeDefault` + Pick default settings. + + `IQEnableModeEnabled` + setting is enabled. + + `IQEnableModeDisabled` + setting is disabled. + */ +typedef NS_ENUM(NSUInteger, IQEnableMode) { + IQEnableModeDefault, + IQEnableModeEnabled, + IQEnableModeDisabled, +}; + +#endif + +/* + + /---------------------------------------------------------------------------------------------------\ + \---------------------------------------------------------------------------------------------------/ + | iOS NSNotification Mechanism | + /---------------------------------------------------------------------------------------------------\ + \---------------------------------------------------------------------------------------------------/ + + + ------------------------------------------------------------ + When UITextField become first responder + ------------------------------------------------------------ + - UITextFieldTextDidBeginEditingNotification (UITextField) + - UIKeyboardWillShowNotification + - UIKeyboardDidShowNotification + + ------------------------------------------------------------ + When UITextView become first responder + ------------------------------------------------------------ + - UIKeyboardWillShowNotification + - UITextViewTextDidBeginEditingNotification (UITextView) + - UIKeyboardDidShowNotification + + ------------------------------------------------------------ + When switching focus from UITextField to another UITextField + ------------------------------------------------------------ + - UITextFieldTextDidEndEditingNotification (UITextField1) + - UITextFieldTextDidBeginEditingNotification (UITextField2) + - UIKeyboardWillShowNotification + - UIKeyboardDidShowNotification + + ------------------------------------------------------------ + When switching focus from UITextView to another UITextView + ------------------------------------------------------------ + - UITextViewTextDidEndEditingNotification : (UITextView1) + - UIKeyboardWillShowNotification + - UITextViewTextDidBeginEditingNotification : (UITextView2) + - UIKeyboardDidShowNotification + + ------------------------------------------------------------ + When switching focus from UITextField to UITextView + ------------------------------------------------------------ + - UITextFieldTextDidEndEditingNotification (UITextField) + - UIKeyboardWillShowNotification + - UITextViewTextDidBeginEditingNotification (UITextView) + - UIKeyboardDidShowNotification + + ------------------------------------------------------------ + When switching focus from UITextView to UITextField + ------------------------------------------------------------ + - UITextViewTextDidEndEditingNotification (UITextView) + - UITextFieldTextDidBeginEditingNotification (UITextField) + - UIKeyboardWillShowNotification + - UIKeyboardDidShowNotification + + ------------------------------------------------------------ + When opening/closing UIKeyboard Predictive bar + ------------------------------------------------------------ + - UIKeyboardWillShowNotification + - UIKeyboardDidShowNotification + + ------------------------------------------------------------ + On orientation change + ------------------------------------------------------------ + - UIApplicationWillChangeStatusBarOrientationNotification + - UIKeyboardWillHideNotification + - UIKeyboardDidHideNotification + - UIApplicationDidChangeStatusBarOrientationNotification + - UIKeyboardWillShowNotification + - UIKeyboardDidShowNotification + - UIKeyboardWillShowNotification + - UIKeyboardDidShowNotification + + */ diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Constants/IQKeyboardManagerConstantsInternal.h b/Pods/IQKeyboardManager/IQKeyboardManager/Constants/IQKeyboardManagerConstantsInternal.h new file mode 100644 index 0000000..2225174 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/Constants/IQKeyboardManagerConstantsInternal.h @@ -0,0 +1,30 @@ +// +// IQKeyboardManagerConstantsInternal.h +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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. + +#ifndef IQKeyboardManagerConstantsInternal_h +#define IQKeyboardManagerConstantsInternal_h + + +#define IQ_IS_IOS10_OR_GREATER ([[NSProcessInfo processInfo] operatingSystemVersion].majorVersion >= 10) + +#endif diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/IQKeyboardManager.h b/Pods/IQKeyboardManager/IQKeyboardManager/IQKeyboardManager.h new file mode 100755 index 0000000..c6714e0 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/IQKeyboardManager.h @@ -0,0 +1,368 @@ +// +// IQKeyboardManager.h +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQKeyboardManagerConstants.h" +#import "IQUIView+IQKeyboardToolbar.h" +#import "IQPreviousNextView.h" +#import "IQUIViewController+Additions.h" +#import "IQKeyboardReturnKeyHandler.h" +#import "IQTextView.h" +#import "IQToolbar.h" +#import "IQUIScrollView+Additions.h" +#import "IQUITextFieldView+Additions.h" +#import "IQBarButtonItem.h" +#import "IQTitleBarButtonItem.h" +#import "IQUIView+Hierarchy.h" + +#import + +#import +#import +#import + +#import + +@class UIFont, UIColor, UITapGestureRecognizer, UIView, UIImage; + +@class NSString; + +///--------------------- +/// @name IQToolbar tags +///--------------------- + +/** + Default tag for toolbar with Done button -1002. + */ +extern NSInteger const kIQDoneButtonToolbarTag; + +/** + Default tag for toolbar with Previous/Next buttons -1005. + */ +extern NSInteger const kIQPreviousNextButtonToolbarTag; + + + +/** + Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more. A generic version of KeyboardManagement. https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html + */ +@interface IQKeyboardManager : NSObject + +///-------------------------- +/// @name UIKeyboard handling +///-------------------------- + +/** + Returns the default singleton instance. You are not allowed to create your own instances of this class. + */ ++ (nonnull instancetype)sharedManager; + +/** + Enable/disable managing distance between keyboard and textField. Default is YES(Enabled when class loads in `+(void)load` method). + */ +@property(nonatomic, assign, getter = isEnabled) BOOL enable; + +/** + To set keyboard distance from textField. can't be less than zero. Default is 10.0. + */ +@property(nonatomic, assign) CGFloat keyboardDistanceFromTextField; + +/** + Prevent keyboard manager to slide up the rootView to more than keyboard height. Default is YES. + + Due to change in core-logic of handling distance between textField and keyboard distance, this tweak is no longer needed and things will just work out of the box for most of the cases. + */ +@property(nonatomic, assign) BOOL preventShowingBottomBlankSpace __attribute__((deprecated("Due to change in core-logic of handling distance between textField and keyboard distance, this tweak is no longer needed and things will just work out of the box for most of the cases. This property will be removed in future release."))); + +/** + Refreshes textField/textView position if any external changes is explicitly made by user. + */ +- (void)reloadLayoutIfNeeded; + +/** + Boolean to know if keyboard is showing. + */ +@property(nonatomic, assign, readonly, getter = isKeyboardShowing) BOOL keyboardShowing; + +/** + moved distance to the top used to maintain distance between keyboard and textField. Most of the time this will be a positive value. + */ +@property(nonatomic, assign, readonly) CGFloat movedDistance; + + +///------------------------- +/// @name IQToolbar handling +///------------------------- + +/** + Automatic add IQToolbar functionality. Default is YES. + */ +@property(nonatomic, assign, getter = isEnableAutoToolbar) BOOL enableAutoToolbar; + +/** + IQAutoToolbarBySubviews: Creates Toolbar according to subview's hirarchy of Textfield's in view. + IQAutoToolbarByTag: Creates Toolbar according to tag property of TextField's. + IQAutoToolbarByPosition: Creates Toolbar according to the y,x position of textField in it's superview coordinate. + + Default is IQAutoToolbarBySubviews. +*/ +@property(nonatomic, assign) IQAutoToolbarManageBehaviour toolbarManageBehaviour; + +/** + If YES, then uses textField's tintColor property for IQToolbar, otherwise tint color is black. Default is NO. + */ +@property(nonatomic, assign) BOOL shouldToolbarUsesTextFieldTintColor; + +/** + This is used for toolbar.tintColor when textfield.keyboardAppearance is UIKeyboardAppearanceDefault. If shouldToolbarUsesTextFieldTintColor is YES then this property is ignored. Default is nil and uses black color. + */ +@property(nullable, nonatomic, strong) UIColor *toolbarTintColor; + +/** + This is used for toolbar.barTintColor. Default is nil and uses white color. + */ +@property(nullable, nonatomic, strong) UIColor *toolbarBarTintColor; + +/** + IQPreviousNextDisplayModeDefault: Show NextPrevious when there are more than 1 textField otherwise hide. + IQPreviousNextDisplayModeAlwaysHide: Do not show NextPrevious buttons in any case. + IQPreviousNextDisplayModeAlwaysShow: Always show nextPrevious buttons, if there are more than 1 textField then both buttons will be visible but will be shown as disabled. + */ +@property(nonatomic, assign) IQPreviousNextDisplayMode previousNextDisplayMode; + +/** + Toolbar previous/next/done button icon, If nothing is provided then check toolbarDoneBarButtonItemText to draw done button. + */ +@property(nullable, nonatomic, strong) UIImage *toolbarPreviousBarButtonItemImage; +@property(nullable, nonatomic, strong) UIImage *toolbarNextBarButtonItemImage; +@property(nullable, nonatomic, strong) UIImage *toolbarDoneBarButtonItemImage; + +/** + Toolbar previous/next/done button text, If nothing is provided then system default 'UIBarButtonSystemItemDone' will be used. + */ +@property(nullable, nonatomic, strong) NSString *toolbarPreviousBarButtonItemText; +@property(nullable, nonatomic, strong) NSString *toolbarNextBarButtonItemText; +@property(nullable, nonatomic, strong) NSString *toolbarDoneBarButtonItemText; + +/** + If YES, then it add the textField's placeholder text on IQToolbar. Default is YES. + */ +@property(nonatomic, assign) BOOL shouldShowTextFieldPlaceholder __attribute__((deprecated("This is renamed to `shouldShowToolbarPlaceholder` for more clear naming."))); +@property(nonatomic, assign) BOOL shouldShowToolbarPlaceholder; + +/** + Placeholder Font. Default is nil. + */ +@property(nullable, nonatomic, strong) UIFont *placeholderFont; + +/** + Placeholder Color. Default is nil. Which means lightGray + */ +@property(nullable, nonatomic, strong) UIColor *placeholderColor; + +/** + Placeholder Button Color when it's treated as button. Default is nil. Which means iOS Blue for light toolbar and Yellow for dark toolbar + */ +@property(nullable, nonatomic, strong) UIColor *placeholderButtonColor; + +/** + Reload all toolbar buttons on the fly. + */ +- (void)reloadInputViews; + +///--------------------------------------- +/// @name UIKeyboard appearance overriding +///--------------------------------------- + +/** + Override the keyboardAppearance for all textField/textView. Default is NO. + */ +@property(nonatomic, assign) BOOL overrideKeyboardAppearance; + +/** + If overrideKeyboardAppearance is YES, then all the textField keyboardAppearance is set using this property. + */ +@property(nonatomic, assign) UIKeyboardAppearance keyboardAppearance; + +///----------------------------------------------------------- +/// @name UITextField/UITextView Next/Previous/Resign handling +///----------------------------------------------------------- + +/** + Resigns Keyboard on touching outside of UITextField/View. Default is NO. + */ +@property(nonatomic, assign) BOOL shouldResignOnTouchOutside; + +/** TapGesture to resign keyboard on view's touch. It's a readonly property and exposed only for adding/removing dependencies if your added gesture does have collision with this one */ +@property(nonnull, nonatomic, strong, readonly) UITapGestureRecognizer *resignFirstResponderGesture; + +/** + Resigns currently first responder field. + */ +- (BOOL)resignFirstResponder; + +/** + Returns YES if can navigate to previous responder textField/textView, otherwise NO. + */ +@property (nonatomic, readonly) BOOL canGoPrevious; + +/** + Returns YES if can navigate to next responder textField/textView, otherwise NO. + */ +@property (nonatomic, readonly) BOOL canGoNext; + +/** + Navigate to previous responder textField/textView. + */ +- (BOOL)goPrevious; + +/** + Navigate to next responder textField/textView. + */ +- (BOOL)goNext; + +///----------------------- +/// @name UISound handling +///----------------------- + +/** + If YES, then it plays inputClick sound on next/previous/done click. Default is YES. + */ +@property(nonatomic, assign) BOOL shouldPlayInputClicks; + +///--------------------------- +/// @name UIAnimation handling +///--------------------------- + +/** + If YES, then calls 'setNeedsLayout' and 'layoutIfNeeded' on any frame update of to viewController's view. + */ +@property(nonatomic, assign) BOOL layoutIfNeededOnUpdate; + +///----------------------------------------------- +/// @name InteractivePopGestureRecognizer handling +///----------------------------------------------- + +/** + If YES, then always consider UINavigationController.view begin point as {0,0}, this is a workaround to fix a bug #464 because there are no notification mechanism exist when UINavigationController.view.frame gets changed internally. + */ +@property(nonatomic, assign) BOOL shouldFixInteractivePopGestureRecognizer __attribute__((deprecated("Due to change in core-logic of handling distance between textField and keyboard distance, this tweak is no longer needed and things will just work out of the box for most of the cases. This property will be removed in future release."))); + +#ifdef __IPHONE_11_0 +///--------------------------- +/// @name Safe Area +///--------------------------- + +/** + If YES, then library will try to adjust viewController.additionalSafeAreaInsets to automatically handle layout guide. Default is NO. + */ +@property(nonatomic, assign) BOOL canAdjustAdditionalSafeAreaInsets __attribute__((deprecated("Due to change in core-logic of handling distance between textField and keyboard distance, this safe area tweak is no longer needed and things will just work out of the box regardless of constraint pinned with safeArea/layoutGuide/superview. This property will be removed in future release."))); +#endif + +///--------------------------------------------- +/// @name Class Level enabling/disabling methods +///--------------------------------------------- + +/** + Disable distance handling within the scope of disabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController. Default is [UITableViewController, UIAlertController, _UIAlertControllerTextFieldViewController]. + */ +@property(nonatomic, strong, nonnull, readonly) NSMutableSet *disabledDistanceHandlingClasses; + +/** + Enable distance handling within the scope of enabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController. Default is []. + */ +@property(nonatomic, strong, nonnull, readonly) NSMutableSet *enabledDistanceHandlingClasses; + +/** + Disable automatic toolbar creation within the scope of disabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController. Default is [UIAlertController, _UIAlertControllerTextFieldViewController]. + */ +@property(nonatomic, strong, nonnull, readonly) NSMutableSet *disabledToolbarClasses; + +/** + Enable automatic toolbar creation within the scope of enabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController. Default is []. + */ +@property(nonatomic, strong, nonnull, readonly) NSMutableSet *enabledToolbarClasses; + +/** + Allowed subclasses of UIView to add all inner textField, this will allow to navigate between textField contains in different superview. Class should be kind of UIView. Default is [UITableView, UICollectionView, IQPreviousNextView]. + */ +@property(nonatomic, strong, nonnull, readonly) NSMutableSet *toolbarPreviousNextAllowedClasses; + +/** + Disabled classes to ignore 'shouldResignOnTouchOutside' property, Class should be kind of UIViewController. Default is [UIAlertController, UIAlertControllerTextFieldViewController] + */ +@property(nonatomic, strong, nonnull, readonly) NSMutableSet *disabledTouchResignedClasses; + +/** + Enabled classes to forcefully enable 'shouldResignOnTouchOutsite' property. Class should be kind of UIViewController. Default is []. + */ +@property(nonatomic, strong, nonnull, readonly) NSMutableSet *enabledTouchResignedClasses; + +/** + if shouldResignOnTouchOutside is enabled then you can customise the behaviour to not recognise gesture touches on some specific view subclasses. Class should be kind of UIView. Default is [UIControl, UINavigationBar] + */ +@property(nonatomic, strong, nonnull, readonly) NSMutableSet *touchResignedGestureIgnoreClasses; + +///------------------------------------------- +/// @name Third Party Library support +/// Add TextField/TextView Notifications customised NSNotifications. For example while using YYTextView https://github.com/ibireme/YYText +///------------------------------------------- + +/** + Add/Remove customised Notification for third party customised TextField/TextView. Please be aware that the NSNotification object must be idential to UITextField/UITextView NSNotification objects and customised TextField/TextView support must be idential to UITextField/UITextView. + @param didBeginEditingNotificationName This should be identical to UITextViewTextDidBeginEditingNotification + @param didEndEditingNotificationName This should be identical to UITextViewTextDidEndEditingNotification + */ +-(void)registerTextFieldViewClass:(nonnull Class)aClass + didBeginEditingNotificationName:(nonnull NSString *)didBeginEditingNotificationName + didEndEditingNotificationName:(nonnull NSString *)didEndEditingNotificationName; +-(void)unregisterTextFieldViewClass:(nonnull Class)aClass + didBeginEditingNotificationName:(nonnull NSString *)didBeginEditingNotificationName + didEndEditingNotificationName:(nonnull NSString *)didEndEditingNotificationName; + +///---------------------------------------- +/// @name Debugging & Developer options +///---------------------------------------- + +@property(nonatomic, assign) BOOL enableDebugging; + +/** + @warning Use these methods to completely enable/disable notifications registered by library internally. Please keep in mind that library is totally dependent on NSNotification of UITextField, UITextField, Keyboard etc. If you do unregisterAllNotifications then library will not work at all. You should only use below methods if you want to completedly disable all library functions. You should use below methods at your own risk. + */ +-(void)registerAllNotifications; +-(void)unregisterAllNotifications; + +///---------------------------------------- +/// @name Must not be used for subclassing. +///---------------------------------------- + +/** + Unavailable. Please use sharedManager method + */ +-(nonnull instancetype)init NS_UNAVAILABLE; + +/** + Unavailable. Please use sharedManager method + */ ++ (nonnull instancetype)new NS_UNAVAILABLE; + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/IQKeyboardManager.m b/Pods/IQKeyboardManager/IQKeyboardManager/IQKeyboardManager.m new file mode 100644 index 0000000..13d5b58 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/IQKeyboardManager.m @@ -0,0 +1,2105 @@ +// +// IQKeyboardManager.m +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQKeyboardManager.h" +#import "IQUIView+Hierarchy.h" +#import "IQUIView+IQKeyboardToolbar.h" +#import "IQNSArray+Sort.h" +#import "IQKeyboardManagerConstantsInternal.h" +#import "IQUIScrollView+Additions.h" +#import "IQUITextFieldView+Additions.h" +#import "IQUIViewController+Additions.h" +#import "IQPreviousNextView.h" + +#import + +#import + +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import + + +NSInteger const kIQDoneButtonToolbarTag = -1002; +NSInteger const kIQPreviousNextButtonToolbarTag = -1005; + +#define kIQCGPointInvalid CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX) + +@interface IQKeyboardManager() + +/*******************************************/ + +/** used to adjust contentInset of UITextView. */ +@property(nonatomic, assign) UIEdgeInsets startingTextViewContentInsets; + +/** used to adjust scrollIndicatorInsets of UITextView. */ +@property(nonatomic, assign) UIEdgeInsets startingTextViewScrollIndicatorInsets; + +/** used with textView to detect a textFieldView contentInset is changed or not. (Bug ID: #92)*/ +@property(nonatomic, assign) BOOL isTextViewContentInsetChanged; + +/*******************************************/ + +/** To save UITextField/UITextView object voa textField/textView notifications. */ +@property(nonatomic, weak) UIView *textFieldView; + +/** To save rootViewController.view.frame.origin. */ +@property(nonatomic, assign) CGPoint topViewBeginOrigin; + +/** To save rootViewController */ +@property(nonatomic, weak) UIViewController *rootViewController; + +/** To overcome with popGestureRecognizer issue Bug ID: #1361 */ +@property(nonatomic, weak) UIViewController *rootViewControllerWhilePopGestureRecognizerActive; +@property(nonatomic, assign) CGPoint topViewBeginOriginWhilePopGestureRecognizerActive; + +/** To know if we have any pending request to adjust view position. */ +@property(nonatomic, assign) BOOL hasPendingAdjustRequest; + +/*******************************************/ + +/** Variable to save lastScrollView that was scrolled. */ +@property(nonatomic, weak) UIScrollView *lastScrollView; + +/** LastScrollView's initial contentInsets. */ +@property(nonatomic, assign) UIEdgeInsets startingContentInsets; + +/** LastScrollView's initial scrollIndicatorInsets. */ +@property(nonatomic, assign) UIEdgeInsets startingScrollIndicatorInsets; + +/** LastScrollView's initial contentOffset. */ +@property(nonatomic, assign) CGPoint startingContentOffset; + +/*******************************************/ + +/** To save keyboard animation duration. */ +@property(nonatomic, assign) CGFloat animationDuration; + +/** To mimic the keyboard animation */ +@property(nonatomic, assign) NSInteger animationCurve; + +/*******************************************/ + +/** TapGesture to resign keyboard on view's touch. It's a readonly property and exposed only for adding/removing dependencies if your added gesture does have collision with this one */ +@property(nonnull, nonatomic, strong, readwrite) UITapGestureRecognizer *resignFirstResponderGesture; + +/** + moved distance to the top used to maintain distance between keyboard and textField. Most of the time this will be a positive value. + */ +@property(nonatomic, assign, readwrite) CGFloat movedDistance; + +/*******************************************/ + +@property(nonatomic, strong, nonnull, readwrite) NSMutableSet *registeredClasses; + +@property(nonatomic, strong, nonnull, readwrite) NSMutableSet *disabledDistanceHandlingClasses; +@property(nonatomic, strong, nonnull, readwrite) NSMutableSet *enabledDistanceHandlingClasses; + +@property(nonatomic, strong, nonnull, readwrite) NSMutableSet *disabledToolbarClasses; +@property(nonatomic, strong, nonnull, readwrite) NSMutableSet *enabledToolbarClasses; + +@property(nonatomic, strong, nonnull, readwrite) NSMutableSet *toolbarPreviousNextAllowedClasses; + +@property(nonatomic, strong, nonnull, readwrite) NSMutableSet *disabledTouchResignedClasses; +@property(nonatomic, strong, nonnull, readwrite) NSMutableSet *enabledTouchResignedClasses; +@property(nonatomic, strong, nonnull, readwrite) NSMutableSet *touchResignedGestureIgnoreClasses; + +/*******************************************/ + +@end + +@implementation IQKeyboardManager +{ + @package + + /*******************************************/ + + /** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */ + NSNotification *_kbShowNotification; + + /** To save keyboard size. */ + CGSize _kbSize; + + /*******************************************/ +} + +//UIKeyboard handling +@synthesize enable = _enable; +@synthesize keyboardDistanceFromTextField = _keyboardDistanceFromTextField; + +//Keyboard Appearance handling +@synthesize overrideKeyboardAppearance = _overrideKeyboardAppearance; +@synthesize keyboardAppearance = _keyboardAppearance; + +//IQToolbar handling +@synthesize enableAutoToolbar = _enableAutoToolbar; +@synthesize toolbarManageBehaviour = _toolbarManageBehaviour; + +@synthesize shouldToolbarUsesTextFieldTintColor = _shouldToolbarUsesTextFieldTintColor; +@synthesize toolbarTintColor = _toolbarTintColor; +@synthesize toolbarBarTintColor = _toolbarBarTintColor; +@dynamic shouldShowTextFieldPlaceholder; +@synthesize shouldShowToolbarPlaceholder = _shouldShowToolbarPlaceholder; +@synthesize placeholderFont = _placeholderFont; +@synthesize placeholderColor = _placeholderColor; +@synthesize placeholderButtonColor = _placeholderButtonColor; + +//Resign handling +@synthesize shouldResignOnTouchOutside = _shouldResignOnTouchOutside; +@synthesize resignFirstResponderGesture = _resignFirstResponderGesture; + +//Sound handling +@synthesize shouldPlayInputClicks = _shouldPlayInputClicks; + +//Animation handling +@synthesize layoutIfNeededOnUpdate = _layoutIfNeededOnUpdate; + +#pragma mark - Initializing functions + +/** Override +load method to enable KeyboardManager when class loader load IQKeyboardManager. Enabling when app starts (No need to write any code) */ ++(void)load +{ + //Enabling IQKeyboardManager. Loading asynchronous on main thread + [self performSelectorOnMainThread:@selector(sharedManager) withObject:nil waitUntilDone:NO]; +} + +/* Singleton Object Initialization. */ +-(instancetype)init +{ + if (self = [super init]) + { + __weak typeof(self) weakSelf = self; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + + __strong typeof(self) strongSelf = weakSelf; + + strongSelf.registeredClasses = [[NSMutableSet alloc] init]; + + [strongSelf registerAllNotifications]; + + //Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14) + strongSelf.resignFirstResponderGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapRecognized:)]; + strongSelf.resignFirstResponderGesture.cancelsTouchesInView = NO; + [strongSelf.resignFirstResponderGesture setDelegate:self]; + strongSelf.resignFirstResponderGesture.enabled = strongSelf.shouldResignOnTouchOutside; + strongSelf.topViewBeginOrigin = kIQCGPointInvalid; + strongSelf.topViewBeginOriginWhilePopGestureRecognizerActive = kIQCGPointInvalid; + + //Setting it's initial values + strongSelf.animationDuration = 0.25; + strongSelf.animationCurve = UIViewAnimationCurveEaseInOut; + [self setEnable:YES]; + [self setKeyboardDistanceFromTextField:10.0]; + [self setShouldPlayInputClicks:YES]; + [self setShouldResignOnTouchOutside:NO]; + [self setOverrideKeyboardAppearance:NO]; + [self setKeyboardAppearance:UIKeyboardAppearanceDefault]; + [self setEnableAutoToolbar:YES]; + [self setShouldShowToolbarPlaceholder:YES]; + [self setToolbarManageBehaviour:IQAutoToolbarBySubviews]; + [self setLayoutIfNeededOnUpdate:NO]; + + //Loading IQToolbar, IQTitleBarButtonItem, IQBarButtonItem to fix first time keyboard appearance delay (Bug ID: #550) + { + //If you experience exception breakpoint issue at below line then try these solutions https://stackoverflow.com/questions/27375640/all-exception-break-point-is-stopping-for-no-reason-on-simulator + UITextField *view = [[UITextField alloc] init]; + [view addDoneOnKeyboardWithTarget:nil action:nil]; + [view addPreviousNextDoneOnKeyboardWithTarget:nil previousAction:nil nextAction:nil doneAction:nil]; + } + + //Initializing disabled classes Set. + strongSelf.disabledDistanceHandlingClasses = [[NSMutableSet alloc] initWithObjects:[UITableViewController class],[UIAlertController class], nil]; + strongSelf.enabledDistanceHandlingClasses = [[NSMutableSet alloc] init]; + + strongSelf.disabledToolbarClasses = [[NSMutableSet alloc] initWithObjects:[UIAlertController class], nil]; + strongSelf.enabledToolbarClasses = [[NSMutableSet alloc] init]; + + strongSelf.toolbarPreviousNextAllowedClasses = [[NSMutableSet alloc] initWithObjects:[UITableView class],[UICollectionView class],[IQPreviousNextView class], nil]; + + strongSelf.disabledTouchResignedClasses = [[NSMutableSet alloc] initWithObjects:[UIAlertController class], nil]; + strongSelf.enabledTouchResignedClasses = [[NSMutableSet alloc] init]; + strongSelf.touchResignedGestureIgnoreClasses = [[NSMutableSet alloc] initWithObjects:[UIControl class],[UINavigationBar class], nil]; + + [self setShouldToolbarUsesTextFieldTintColor:NO]; + }); + } + return self; +} + +/* Automatically called from the `+(void)load` method. */ ++ (IQKeyboardManager*)sharedManager +{ + //Singleton instance + static IQKeyboardManager *kbManager; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + + kbManager = [[self alloc] init]; + }); + + return kbManager; +} + +#pragma mark - Dealloc +-(void)dealloc +{ + // Disable the keyboard manager. + [self setEnable:NO]; + + //Removing notification observers on dealloc. + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +#pragma mark - Property functions +-(void)setEnable:(BOOL)enable +{ + // If not enabled, enable it. + if (enable == YES && + _enable == NO) + { + //Setting NO to _enable. + _enable = enable; + + //If keyboard is currently showing. Sending a fake notification for keyboardWillShow to adjust view according to keyboard. + if (_kbShowNotification) [self keyboardWillShow:_kbShowNotification]; + + [self showLog:@"Enabled"]; + } + //If not disable, desable it. + else if (enable == NO && + _enable == YES) + { + //Sending a fake notification for keyboardWillHide to retain view's original position. + [self keyboardWillHide:nil]; + + //Setting NO to _enable. + _enable = enable; + + [self showLog:@"Disabled"]; + } + //If already disabled. + else if (enable == NO && + _enable == NO) + { + [self showLog:@"Already Disabled"]; + } + //If already enabled. + else if (enable == YES && + _enable == YES) + { + [self showLog:@"Already Enabled"]; + } +} + +-(BOOL)privateIsEnabled +{ + BOOL enable = _enable; + +// IQEnableMode enableMode = _textFieldView.enableMode; +// +// if (enableMode == IQEnableModeEnabled) +// { +// enable = YES; +// } +// else if (enableMode == IQEnableModeDisabled) +// { +// enable = NO; +// } +// else + { + UIViewController *textFieldViewController = [_textFieldView viewContainingController]; + + if (textFieldViewController) + { + if (enable == NO) + { + //If viewController is kind of enable viewController class, then assuming it's enabled. + for (Class enabledClass in _enabledDistanceHandlingClasses) + { + if ([textFieldViewController isKindOfClass:enabledClass]) + { + enable = YES; + break; + } + } + } + + if (enable) + { + //If viewController is kind of disable viewController class, then assuming it's disable. + for (Class disabledClass in _disabledDistanceHandlingClasses) + { + if ([textFieldViewController isKindOfClass:disabledClass]) + { + enable = NO; + break; + } + } + + //Special Controllers + if (enable == YES) + { + NSString *classNameString = NSStringFromClass([textFieldViewController class]); + + //_UIAlertControllerTextFieldViewController + if ([classNameString containsString:@"UIAlertController"] && [classNameString hasSuffix:@"TextFieldViewController"]) + { + enable = NO; + } + } + } + } + } + + return enable; +} + +-(BOOL)shouldShowTextFieldPlaceholder +{ + return _shouldShowToolbarPlaceholder; +} + +-(void)setShouldShowTextFieldPlaceholder:(BOOL)shouldShowTextFieldPlaceholder +{ + _shouldShowToolbarPlaceholder = shouldShowTextFieldPlaceholder; +} + +// Setting keyboard distance from text field. +-(void)setKeyboardDistanceFromTextField:(CGFloat)keyboardDistanceFromTextField +{ + //Can't be less than zero. Minimum is zero. + _keyboardDistanceFromTextField = MAX(keyboardDistanceFromTextField, 0); + + [self showLog:[NSString stringWithFormat:@"keyboardDistanceFromTextField: %.2f",_keyboardDistanceFromTextField]]; +} + +/** Enabling/disable gesture on touching. */ +-(void)setShouldResignOnTouchOutside:(BOOL)shouldResignOnTouchOutside +{ + [self showLog:[NSString stringWithFormat:@"shouldResignOnTouchOutside: %@",shouldResignOnTouchOutside?@"Yes":@"No"]]; + + _shouldResignOnTouchOutside = shouldResignOnTouchOutside; + + //Enable/Disable gesture recognizer (Enhancement ID: #14) + [_resignFirstResponderGesture setEnabled:[self privateShouldResignOnTouchOutside]]; +} + +-(BOOL)privateShouldResignOnTouchOutside +{ + BOOL shouldResignOnTouchOutside = _shouldResignOnTouchOutside; + + UIView *textFieldView = _textFieldView; + IQEnableMode enableMode = textFieldView.shouldResignOnTouchOutsideMode; + + if (enableMode == IQEnableModeEnabled) + { + shouldResignOnTouchOutside = YES; + } + else if (enableMode == IQEnableModeDisabled) + { + shouldResignOnTouchOutside = NO; + } + else + { + UIViewController *textFieldViewController = [textFieldView viewContainingController]; + + if (textFieldViewController) + { + if (shouldResignOnTouchOutside == NO) + { + //If viewController is kind of enable viewController class, then assuming shouldResignOnTouchOutside is enabled. + for (Class enabledClass in _enabledTouchResignedClasses) + { + if ([textFieldViewController isKindOfClass:enabledClass]) + { + shouldResignOnTouchOutside = YES; + break; + } + } + } + + if (shouldResignOnTouchOutside) + { + //If viewController is kind of disable viewController class, then assuming shouldResignOnTouchOutside is disable. + for (Class disabledClass in _disabledTouchResignedClasses) + { + if ([textFieldViewController isKindOfClass:disabledClass]) + { + shouldResignOnTouchOutside = NO; + break; + } + } + + //Special Controllers + if (shouldResignOnTouchOutside == YES) + { + NSString *classNameString = NSStringFromClass([textFieldViewController class]); + + //_UIAlertControllerTextFieldViewController + if ([classNameString containsString:@"UIAlertController"] && [classNameString hasSuffix:@"TextFieldViewController"]) + { + shouldResignOnTouchOutside = NO; + } + } + } + } + } + + return shouldResignOnTouchOutside; +} + +/** Enable/disable autotoolbar. Adding and removing toolbar if required. */ +-(void)setEnableAutoToolbar:(BOOL)enableAutoToolbar +{ + _enableAutoToolbar = enableAutoToolbar; + + [self showLog:[NSString stringWithFormat:@"enableAutoToolbar: %@",enableAutoToolbar?@"Yes":@"No"]]; + + //If enabled then adding toolbar. + if ([self privateIsEnableAutoToolbar] == YES) + { + [self addToolbarIfRequired]; + } + //Else removing toolbar. + else + { + [self removeToolbarIfRequired]; + } +} + +-(BOOL)privateIsEnableAutoToolbar +{ + BOOL enableAutoToolbar = _enableAutoToolbar; + + UIViewController *textFieldViewController = [_textFieldView viewContainingController]; + + if (textFieldViewController) + { + if (enableAutoToolbar == NO) + { + //If found any toolbar enabled classes then return. + for (Class enabledToolbarClass in _enabledToolbarClasses) + { + if ([textFieldViewController isKindOfClass:enabledToolbarClass]) + { + enableAutoToolbar = YES; + break; + } + } + } + + if (enableAutoToolbar) + { + //If found any toolbar disabled classes then return. + for (Class disabledToolbarClass in _disabledToolbarClasses) + { + if ([textFieldViewController isKindOfClass:disabledToolbarClass]) + { + enableAutoToolbar = NO; + break; + } + } + + + //Special Controllers + if (enableAutoToolbar == YES) + { + NSString *classNameString = NSStringFromClass([textFieldViewController class]); + + //_UIAlertControllerTextFieldViewController + if ([classNameString containsString:@"UIAlertController"] && [classNameString hasSuffix:@"TextFieldViewController"]) + { + enableAutoToolbar = NO; + } + } + } + } + + return enableAutoToolbar; +} + +#pragma mark - Private Methods + +/** Getting keyWindow. */ +-(UIWindow *)keyWindow +{ + UIView *textFieldView = _textFieldView; + + if (textFieldView.window) + { + return textFieldView.window; + } + else + { + static __weak UIWindow *_keyWindow = nil; + + /* (Bug ID: #23, #25, #73) */ + UIWindow *originalKeyWindow = [[UIApplication sharedApplication] keyWindow]; + + //If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow. + if (originalKeyWindow && + _keyWindow != originalKeyWindow) + { + _keyWindow = originalKeyWindow; + } + + return _keyWindow; + } +} + +-(void)optimizedAdjustPosition +{ + if (_hasPendingAdjustRequest == NO) + { + _hasPendingAdjustRequest = YES; + + __weak typeof(self) weakSelf = self; + + [[NSOperationQueue mainQueue] addOperationWithBlock:^{ + [self adjustPosition]; + weakSelf.hasPendingAdjustRequest = NO; + }]; + } +} + +/* Adjusting RootViewController's frame according to interface orientation. */ +-(void)adjustPosition +{ + UIView *textFieldView = _textFieldView; + + // Getting RootViewController. (Bug ID: #1, #4) + UIViewController *rootController = _rootViewController; + + // Getting KeyWindow object. + UIWindow *keyWindow = [self keyWindow]; + + // We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11) + if (_hasPendingAdjustRequest == NO || + textFieldView == nil || + rootController == nil || + keyWindow == nil) + return; + + CFTimeInterval startTime = CACurrentMediaTime(); + [self showLog:[NSString stringWithFormat:@"****** %@ started ******",NSStringFromSelector(_cmd)]]; + + // Converting Rectangle according to window bounds. + CGRect textFieldViewRectInWindow = [[textFieldView superview] convertRect:textFieldView.frame toView:keyWindow]; + CGRect textFieldViewRectInRootSuperview = [[textFieldView superview] convertRect:textFieldView.frame toView:rootController.view.superview]; + // Getting RootView origin. + CGPoint rootViewOrigin = rootController.view.frame.origin; + + //Maintain keyboardDistanceFromTextField + CGFloat specialKeyboardDistanceFromTextField = textFieldView.keyboardDistanceFromTextField; + + { + UISearchBar *searchBar = textFieldView.searchBar; + + if (searchBar) + { + specialKeyboardDistanceFromTextField = searchBar.keyboardDistanceFromTextField; + } + } + + CGFloat keyboardDistanceFromTextField = (specialKeyboardDistanceFromTextField == kIQUseDefaultKeyboardDistance)?_keyboardDistanceFromTextField:specialKeyboardDistanceFromTextField; + CGSize kbSize = _kbSize; + kbSize.height += keyboardDistanceFromTextField; + + CGFloat navigationBarAreaHeight = [[UIApplication sharedApplication] statusBarFrame].size.height + rootController.navigationController.navigationBar.frame.size.height; + CGFloat layoutAreaHeight = rootController.view.layoutMargins.top; + + CGFloat topLayoutGuide = MAX(navigationBarAreaHeight, layoutAreaHeight) + 5; + CGFloat bottomLayoutGuide = [textFieldView isKindOfClass:[UITextView class]] ? 0 : rootController.view.layoutMargins.bottom; //Validation of textView for case where there is a tab bar at the bottom or running on iPhone X and textView is at the bottom. + + // +Move positive = textField is hidden. + // -Move negative = textField is showing. + // Calculating move position. Common for both normal and special cases. + CGFloat move = MIN(CGRectGetMinY(textFieldViewRectInRootSuperview)-topLayoutGuide, CGRectGetMaxY(textFieldViewRectInWindow)-(CGRectGetHeight(keyWindow.frame)-kbSize.height)+bottomLayoutGuide); + + [self showLog:[NSString stringWithFormat:@"Need to move: %.2f",move]]; + + UIScrollView *superScrollView = nil; + UIScrollView *superView = (UIScrollView*)[textFieldView superviewOfClassType:[UIScrollView class]]; + + //Getting UIScrollView whose scrolling is enabled. // (Bug ID: #285) + while (superView) + { + if (superView.isScrollEnabled && superView.shouldIgnoreScrollingAdjustment == NO) + { + superScrollView = superView; + break; + } + else + { + // Getting it's superScrollView. // (Enhancement ID: #21, #24) + superView = (UIScrollView*)[superView superviewOfClassType:[UIScrollView class]]; + } + } + + //If there was a lastScrollView. // (Bug ID: #34) + if (_lastScrollView) + { + //If we can't find current superScrollView, then setting lastScrollView to it's original form. + if (superScrollView == nil) + { + [self showLog:[NSString stringWithFormat:@"Restoring %@ contentInset to : %@ and contentOffset to : %@",[_lastScrollView _IQDescription],NSStringFromUIEdgeInsets(_startingContentInsets),NSStringFromCGPoint(_startingContentOffset)]]; + + __weak typeof(self) weakSelf = self; + + [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{ + + __strong typeof(self) strongSelf = weakSelf; + UIScrollView *strongLastScrollView = strongSelf.lastScrollView; + + [strongLastScrollView setContentInset:strongSelf.startingContentInsets]; + strongLastScrollView.scrollIndicatorInsets = strongSelf.startingScrollIndicatorInsets; + } completion:NULL]; + + if (_lastScrollView.shouldRestoreScrollViewContentOffset) + { + [_lastScrollView setContentOffset:_startingContentOffset animated:UIView.areAnimationsEnabled]; + } + + _startingContentInsets = UIEdgeInsetsZero; + _startingScrollIndicatorInsets = UIEdgeInsetsZero; + _startingContentOffset = CGPointZero; + _lastScrollView = nil; + } + //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView. + else if (superScrollView != _lastScrollView) + { + [self showLog:[NSString stringWithFormat:@"Restoring %@ contentInset to : %@ and contentOffset to : %@",[_lastScrollView _IQDescription],NSStringFromUIEdgeInsets(_startingContentInsets),NSStringFromCGPoint(_startingContentOffset)]]; + + __weak typeof(self) weakSelf = self; + + [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{ + + __strong typeof(self) strongSelf = weakSelf; + UIScrollView *strongLastScrollView = strongSelf.lastScrollView; + + [strongLastScrollView setContentInset:strongSelf.startingContentInsets]; + strongLastScrollView.scrollIndicatorInsets = strongSelf.startingScrollIndicatorInsets; + } completion:NULL]; + + if (_lastScrollView.shouldRestoreScrollViewContentOffset) + { + [_lastScrollView setContentOffset:_startingContentOffset animated:UIView.areAnimationsEnabled]; + } + + _lastScrollView = superScrollView; + _startingContentInsets = superScrollView.contentInset; + _startingScrollIndicatorInsets = superScrollView.scrollIndicatorInsets; + _startingContentOffset = superScrollView.contentOffset; + + [self showLog:[NSString stringWithFormat:@"Saving New %@ contentInset: %@ and contentOffset : %@",[_lastScrollView _IQDescription],NSStringFromUIEdgeInsets(_startingContentInsets),NSStringFromCGPoint(_startingContentOffset)]]; + } + //Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing + } + //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView. + else if(superScrollView) + { + _lastScrollView = superScrollView; + _startingContentInsets = superScrollView.contentInset; + _startingContentOffset = superScrollView.contentOffset; + _startingScrollIndicatorInsets = superScrollView.scrollIndicatorInsets; + + [self showLog:[NSString stringWithFormat:@"Saving %@ contentInset: %@ and contentOffset : %@",[_lastScrollView _IQDescription],NSStringFromUIEdgeInsets(_startingContentInsets),NSStringFromCGPoint(_startingContentOffset)]]; + } + + // Special case for ScrollView. + { + // If we found lastScrollView then setting it's contentOffset to show textField. + if (_lastScrollView) + { + //Saving + UIView *lastView = textFieldView; + superScrollView = _lastScrollView; + + //Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object. + while (superScrollView && + (move>0?(move > (-superScrollView.contentOffset.y-superScrollView.contentInset.top)):superScrollView.contentOffset.y>0) ) + { + UIScrollView *nextScrollView = nil; + UIScrollView *tempScrollView = (UIScrollView*)[superScrollView superviewOfClassType:[UIScrollView class]]; + + //Getting UIScrollView whose scrolling is enabled. // (Bug ID: #285) + while (tempScrollView) + { + if (tempScrollView.isScrollEnabled && tempScrollView.shouldIgnoreScrollingAdjustment == NO) + { + nextScrollView = tempScrollView; + break; + } + else + { + // Getting it's superScrollView. // (Enhancement ID: #21, #24) + tempScrollView = (UIScrollView*)[tempScrollView superviewOfClassType:[UIScrollView class]]; + } + } + + //Getting lastViewRect. + CGRect lastViewRect = [[lastView superview] convertRect:lastView.frame toView:superScrollView]; + + //Calculating the expected Y offset from move and scrollView's contentOffset. + CGFloat shouldOffsetY = superScrollView.contentOffset.y - MIN(superScrollView.contentOffset.y,-move); + + //Rearranging the expected Y offset according to the view. + shouldOffsetY = MIN(shouldOffsetY, lastViewRect.origin.y); + + //[textFieldView isKindOfClass:[UITextView class]] If is a UITextView type + //[superScrollView superviewOfClassType:[UIScrollView class]] == nil If processing scrollView is last scrollView in upper hierarchy (there is no other scrollView upper hierarchy.) + //shouldOffsetY >= 0 shouldOffsetY must be greater than in order to keep distance from navigationBar (Bug ID: #92) + if ([textFieldView isKindOfClass:[UITextView class]] && + nextScrollView == nil && + (shouldOffsetY >= 0)) + { + // Converting Rectangle according to window bounds. + CGRect currentTextFieldViewRect = [[textFieldView superview] convertRect:textFieldView.frame toView:keyWindow]; + + //Calculating expected fix distance which needs to be managed from navigation bar + CGFloat expectedFixDistance = CGRectGetMinY(currentTextFieldViewRect) - topLayoutGuide; + + //Now if expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) is lower than current shouldOffsetY, which means we're in a position where navigationBar up and hide, then reducing shouldOffsetY with expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) + shouldOffsetY = MIN(shouldOffsetY, superScrollView.contentOffset.y + expectedFixDistance); + + //Setting move to 0 because now we don't want to move any view anymore (All will be managed by our contentInset logic. + move = 0; + } + else + { + //Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY. + move -= (shouldOffsetY-superScrollView.contentOffset.y); + } + + + //Getting problem while using `setContentOffset:animated:`, So I used animation API. + [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{ + + [self showLog:[NSString stringWithFormat:@"Adjusting %.2f to %@ ContentOffset",(superScrollView.contentOffset.y-shouldOffsetY),[superScrollView _IQDescription]]]; + [self showLog:[NSString stringWithFormat:@"Remaining Move: %.2f",move]]; + + superScrollView.contentOffset = CGPointMake(superScrollView.contentOffset.x, shouldOffsetY); + + } completion:NULL]; + + // Getting next lastView & superScrollView. + lastView = superScrollView; + superScrollView = nextScrollView; + } + + //Updating contentInset + { + CGRect lastScrollViewRect = [[_lastScrollView superview] convertRect:_lastScrollView.frame toView:keyWindow]; + + CGFloat bottom = (kbSize.height-keyboardDistanceFromTextField)-(CGRectGetHeight(keyWindow.frame)-CGRectGetMaxY(lastScrollViewRect)); + + // Update the insets so that the scroll vew doesn't shift incorrectly when the offset is near the bottom of the scroll view. + UIEdgeInsets movedInsets = _lastScrollView.contentInset; + + movedInsets.bottom = MAX(_startingContentInsets.bottom, bottom); + + [self showLog:[NSString stringWithFormat:@"%@ old ContentInset : %@",[_lastScrollView _IQDescription], NSStringFromUIEdgeInsets(_lastScrollView.contentInset)]]; + + __weak typeof(self) weakSelf = self; + + [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{ + + __strong typeof(self) strongSelf = weakSelf; + UIScrollView *strongLastScrollView = strongSelf.lastScrollView; + + strongLastScrollView.contentInset = movedInsets; + + UIEdgeInsets newInset = strongLastScrollView.scrollIndicatorInsets; + newInset.bottom = movedInsets.bottom; + strongLastScrollView.scrollIndicatorInsets = newInset; + + } completion:NULL]; + + [self showLog:[NSString stringWithFormat:@"%@ new ContentInset : %@",[_lastScrollView _IQDescription], NSStringFromUIEdgeInsets(_lastScrollView.contentInset)]]; + } + } + //Going ahead. No else if. + } + + { + //Special case for UITextView(Readjusting textView.contentInset when textView hight is too big to fit on screen) + //_lastScrollView If not having inside any scrollView, (now contentInset manages the full screen textView. + //[textFieldView isKindOfClass:[UITextView class]] If is a UITextView type + if ([textFieldView isKindOfClass:[UITextView class]]) + { + UITextView *textView = (UITextView*)textFieldView; + + CGFloat keyboardYPosition = CGRectGetHeight(keyWindow.frame)-(kbSize.height-keyboardDistanceFromTextField); + + CGRect rootSuperViewFrameInWindow = [rootController.view.superview convertRect:rootController.view.superview.bounds toView:keyWindow]; + + CGFloat keyboardOverlapping = CGRectGetMaxY(rootSuperViewFrameInWindow) - keyboardYPosition; + + CGFloat textViewHeight = MIN(CGRectGetHeight(textFieldView.frame), (CGRectGetHeight(rootSuperViewFrameInWindow)-topLayoutGuide-keyboardOverlapping)); + + if (textFieldView.frame.size.height-textView.contentInset.bottom>textViewHeight) + { + __weak typeof(self) weakSelf = self; + + [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{ + + __strong typeof(self) strongSelf = weakSelf; + UIView *strongTextFieldView = strongSelf.textFieldView; + + [self showLog:[NSString stringWithFormat:@"%@ Old UITextView.contentInset : %@",[strongTextFieldView _IQDescription], NSStringFromUIEdgeInsets(textView.contentInset)]]; + + //_isTextViewContentInsetChanged, If frame is not change by library in past, then saving user textView properties (Bug ID: #92) + if (strongSelf.isTextViewContentInsetChanged == NO) + { + strongSelf.startingTextViewContentInsets = textView.contentInset; + strongSelf.startingTextViewScrollIndicatorInsets = textView.scrollIndicatorInsets; + } + + UIEdgeInsets newContentInset = textView.contentInset; + newContentInset.bottom = strongTextFieldView.frame.size.height-textViewHeight; + textView.contentInset = newContentInset; + textView.scrollIndicatorInsets = newContentInset; + strongSelf.isTextViewContentInsetChanged = YES; + + [self showLog:[NSString stringWithFormat:@"%@ New UITextView.contentInset : %@",[strongTextFieldView _IQDescription], NSStringFromUIEdgeInsets(textView.contentInset)]]; + + } completion:NULL]; + } + } + + { + __weak typeof(self) weakSelf = self; + + // +Positive or zero. + if (move>=0) + { + rootViewOrigin.y -= move; + + // From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93) + rootViewOrigin.y = MAX(rootViewOrigin.y, MIN(0, -(kbSize.height-keyboardDistanceFromTextField))); + + [self showLog:@"Moving Upward"]; + // Setting adjusted rootViewOrigin.ty + + //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations. + [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{ + + __strong typeof(self) strongSelf = weakSelf; + + // Setting it's new frame + CGRect rect = rootController.view.frame; + rect.origin = rootViewOrigin; + rootController.view.frame = rect; + + //Animating content if needed (Bug ID: #204) + if (strongSelf.layoutIfNeededOnUpdate) + { + //Animating content (Bug ID: #160) + [rootController.view setNeedsLayout]; + [rootController.view layoutIfNeeded]; + } + + [self showLog:[NSString stringWithFormat:@"Set %@ origin to : %@",[rootController _IQDescription],NSStringFromCGPoint(rootViewOrigin)]]; + } completion:NULL]; + + _movedDistance = (_topViewBeginOrigin.y-rootViewOrigin.y); + } + // -Negative + else + { + CGFloat disturbDistance = rootController.view.frame.origin.y-_topViewBeginOrigin.y; + + // disturbDistance Negative = frame disturbed. Pull Request #3 + // disturbDistance positive = frame not disturbed. + if(disturbDistance<=0) + { + rootViewOrigin.y -= MAX(move, disturbDistance); + + [self showLog:@"Moving Downward"]; + // Setting adjusted rootViewRect + + //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations. + [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{ + + __strong typeof(self) strongSelf = weakSelf; + + // Setting it's new frame + CGRect rect = rootController.view.frame; + rect.origin = rootViewOrigin; + rootController.view.frame = rect; + + //Animating content if needed (Bug ID: #204) + if (strongSelf.layoutIfNeededOnUpdate) + { + //Animating content (Bug ID: #160) + [rootController.view setNeedsLayout]; + [rootController.view layoutIfNeeded]; + } + + [self showLog:[NSString stringWithFormat:@"Set %@ origin to : %@",[rootController _IQDescription],NSStringFromCGPoint(rootViewOrigin)]]; + } completion:NULL]; + + _movedDistance = (_topViewBeginOrigin.y-rootController.view.frame.origin.y); + } + } + } + } + + CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime; + [self showLog:[NSString stringWithFormat:@"****** %@ ended: %g seconds ******\n",NSStringFromSelector(_cmd),elapsedTime]]; +} + +-(void)restorePosition +{ + _hasPendingAdjustRequest = NO; + + // Setting rootViewController frame to it's original position. // (Bug ID: #18) + if (_rootViewController && CGPointEqualToPoint(_topViewBeginOrigin, kIQCGPointInvalid) == false) + { + __weak typeof(self) weakSelf = self; + + //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations. + [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{ + + __strong typeof(self) strongSelf = weakSelf; + UIViewController *strongRootController = strongSelf.rootViewController; + + { + [strongSelf showLog:[NSString stringWithFormat:@"Restoring %@ origin to : %@",[strongRootController _IQDescription],NSStringFromCGPoint(strongSelf.topViewBeginOrigin)]]; + + //Restoring + CGRect rect = strongRootController.view.frame; + rect.origin = strongSelf.topViewBeginOrigin; + strongRootController.view.frame = rect; + + strongSelf.movedDistance = 0; + + if (strongRootController.navigationController.interactivePopGestureRecognizer.state == UIGestureRecognizerStateBegan) { + strongSelf.rootViewControllerWhilePopGestureRecognizerActive = strongRootController; + strongSelf.topViewBeginOriginWhilePopGestureRecognizerActive = strongSelf.topViewBeginOrigin; + } + + //Animating content if needed (Bug ID: #204) + if (strongSelf.layoutIfNeededOnUpdate) + { + //Animating content (Bug ID: #160) + [strongRootController.view setNeedsLayout]; + [strongRootController.view layoutIfNeeded]; + } + } + + } completion:NULL]; + _rootViewController = nil; + } +} + +#pragma mark - Public Methods + +/* Refreshes textField/textView position if any external changes is explicitly made by user. */ +- (void)reloadLayoutIfNeeded +{ + if ([self privateIsEnabled] == YES) + { + UIView *textFieldView = _textFieldView; + + if (textFieldView && + _keyboardShowing == YES && + CGPointEqualToPoint(_topViewBeginOrigin, kIQCGPointInvalid) == false && + [textFieldView isAlertViewTextField] == NO) + { + [self optimizedAdjustPosition]; + } + } +} + +#pragma mark - UIKeyboad Notification methods +/* UIKeyboardWillShowNotification. */ +-(void)keyboardWillShow:(NSNotification*)aNotification +{ + _kbShowNotification = aNotification; + + // Boolean to know keyboard is showing/hiding + _keyboardShowing = YES; + + // Getting keyboard animation. + NSInteger curve = [[aNotification userInfo][UIKeyboardAnimationCurveUserInfoKey] integerValue]; + _animationCurve = curve<<16; + + // Getting keyboard animation duration + CGFloat duration = [[aNotification userInfo][UIKeyboardAnimationDurationUserInfoKey] floatValue]; + + //Saving animation duration + if (duration != 0.0) _animationDuration = duration; + + CGSize oldKBSize = _kbSize; + + // Getting UIKeyboardSize. + CGRect kbFrame = [[aNotification userInfo][UIKeyboardFrameEndUserInfoKey] CGRectValue]; + + CGRect screenSize = [[UIScreen mainScreen] bounds]; + + //Calculating actual keyboard displayed size, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381) + CGRect intersectRect = CGRectIntersection(kbFrame, screenSize); + + if (CGRectIsNull(intersectRect)) + { + _kbSize = CGSizeMake(screenSize.size.width, 0); + } + else + { + _kbSize = intersectRect.size; + } + + if ([self privateIsEnabled] == NO) return; + + CFTimeInterval startTime = CACurrentMediaTime(); + [self showLog:[NSString stringWithFormat:@"****** %@ started ******",NSStringFromSelector(_cmd)]]; + + UIView *textFieldView = _textFieldView; + + if (textFieldView && CGPointEqualToPoint(_topViewBeginOrigin, kIQCGPointInvalid)) // (Bug ID: #5) + { + // keyboard is not showing(At the beginning only). We should save rootViewRect. + UIViewController *rootController = [textFieldView parentContainerViewController]; + _rootViewController = rootController; + + if (_rootViewControllerWhilePopGestureRecognizerActive == _rootViewController) + { + _topViewBeginOrigin = _topViewBeginOriginWhilePopGestureRecognizerActive; + } + else + { + _topViewBeginOrigin = rootController.view.frame.origin; + } + + _rootViewControllerWhilePopGestureRecognizerActive = nil; + _topViewBeginOriginWhilePopGestureRecognizerActive = kIQCGPointInvalid; + + [self showLog:[NSString stringWithFormat:@"Saving %@ beginning origin: %@",[rootController _IQDescription] ,NSStringFromCGPoint(_topViewBeginOrigin)]]; + } + + //If last restored keyboard size is different(any orientation accure), then refresh. otherwise not. + if (!CGSizeEqualToSize(_kbSize, oldKBSize)) + { + //If _textFieldView is inside UIAlertView then do nothing. (Bug ID: #37, #74, #76) + //See notes:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70). + if (_keyboardShowing == YES && + textFieldView && + [textFieldView isAlertViewTextField] == NO) + { + [self optimizedAdjustPosition]; + } + } + + CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime; + [self showLog:[NSString stringWithFormat:@"****** %@ ended: %g seconds ******\n",NSStringFromSelector(_cmd),elapsedTime]]; +} + +/* UIKeyboardDidShowNotification. */ +- (void)keyboardDidShow:(NSNotification*)aNotification +{ + if ([self privateIsEnabled] == NO) return; + + CFTimeInterval startTime = CACurrentMediaTime(); + [self showLog:[NSString stringWithFormat:@"****** %@ started ******",NSStringFromSelector(_cmd)]]; + + UIView *textFieldView = _textFieldView; + + // Getting topMost ViewController. + UIViewController *controller = [textFieldView topMostController]; + + //If _textFieldView viewController is presented as formSheet, then adjustPosition again because iOS internally update formSheet frame on keyboardShown. (Bug ID: #37, #74, #76) + if (_keyboardShowing == YES && + textFieldView && + (controller.modalPresentationStyle == UIModalPresentationFormSheet || controller.modalPresentationStyle == UIModalPresentationPageSheet) && + [textFieldView isAlertViewTextField] == NO) + { + [self optimizedAdjustPosition]; + } + + CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime; + [self showLog:[NSString stringWithFormat:@"****** %@ ended: %g seconds ******\n",NSStringFromSelector(_cmd),elapsedTime]]; +} + +/* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */ +- (void)keyboardWillHide:(NSNotification*)aNotification +{ + //If it's not a fake notification generated by [self setEnable:NO]. + if (aNotification) _kbShowNotification = nil; + + // Boolean to know keyboard is showing/hiding + _keyboardShowing = NO; + + // Getting keyboard animation duration + CGFloat aDuration = [[aNotification userInfo][UIKeyboardAnimationDurationUserInfoKey] floatValue]; + if (aDuration!= 0.0f) + { + _animationDuration = aDuration; + } + + //If not enabled then do nothing. + if ([self privateIsEnabled] == NO) return; + + CFTimeInterval startTime = CACurrentMediaTime(); + [self showLog:[NSString stringWithFormat:@"****** %@ started ******",NSStringFromSelector(_cmd)]]; + + //Commented due to #56. Added all the conditions below to handle UIWebView's textFields. (Bug ID: #56) + // We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11) +// if (_textFieldView == nil) return; + + //Restoring the contentOffset of the lastScrollView + if (_lastScrollView) + { + __weak typeof(self) weakSelf = self; + + [UIView animateWithDuration:_animationDuration delay:0 options:(_animationCurve|UIViewAnimationOptionBeginFromCurrentState) animations:^{ + + __strong typeof(self) strongSelf = weakSelf; + + strongSelf.lastScrollView.contentInset = strongSelf.startingContentInsets; + strongSelf.lastScrollView.scrollIndicatorInsets = strongSelf.startingScrollIndicatorInsets; + + if (strongSelf.lastScrollView.shouldRestoreScrollViewContentOffset) + { + strongSelf.lastScrollView.contentOffset = strongSelf.startingContentOffset; + } + + [self showLog:[NSString stringWithFormat:@"Restoring %@ contentInset to : %@ and contentOffset to : %@",[strongSelf.lastScrollView _IQDescription],NSStringFromUIEdgeInsets(strongSelf.startingContentInsets),NSStringFromCGPoint(strongSelf.startingContentOffset)]]; + + // TODO: restore scrollView state + // This is temporary solution. Have to implement the save and restore scrollView state + UIScrollView *superscrollView = strongSelf.lastScrollView; + do + { + CGSize contentSize = CGSizeMake(MAX(superscrollView.contentSize.width, CGRectGetWidth(superscrollView.frame)), MAX(superscrollView.contentSize.height, CGRectGetHeight(superscrollView.frame))); + + CGFloat minimumY = contentSize.height-CGRectGetHeight(superscrollView.frame); + + if (minimumY *textFields = [self responderViews]; + + //Getting index of current textField. + NSUInteger index = [textFields indexOfObject:_textFieldView]; + + //If it is not first textField. then it's previous object can becomeFirstResponder. + if (index != NSNotFound && + index > 0) + { + return YES; + } + else + { + return NO; + } +} + +/** Returns YES if can navigate to next responder textField/textView, otherwise NO. */ +-(BOOL)canGoNext +{ + //Getting all responder view's. + NSArray *textFields = [self responderViews]; + + //Getting index of current textField. + NSUInteger index = [textFields indexOfObject:_textFieldView]; + + //If it is not last textField. then it's next object becomeFirstResponder. + if (index != NSNotFound && + index < textFields.count-1) + { + return YES; + } + else + { + return NO; + } +} + +/** Navigate to previous responder textField/textView. */ +-(BOOL)goPrevious +{ + //Getting all responder view's. + NSArray<__kindof UIView*> *textFields = [self responderViews]; + + //Getting index of current textField. + NSUInteger index = [textFields indexOfObject:_textFieldView]; + + //If it is not first textField. then it's previous object becomeFirstResponder. + if (index != NSNotFound && + index > 0) + { + UITextField *nextTextField = textFields[index-1]; + + // Retaining textFieldView + UIView *textFieldRetain = _textFieldView; + + BOOL isAcceptAsFirstResponder = [nextTextField becomeFirstResponder]; + + // If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96) + if (isAcceptAsFirstResponder == NO) + { + //If next field refuses to become first responder then restoring old textField as first responder. + [textFieldRetain becomeFirstResponder]; + + [self showLog:[NSString stringWithFormat:@"Refuses to become first responder: %@",[nextTextField _IQDescription]]]; + } + + return isAcceptAsFirstResponder; + } + else + { + return NO; + } +} + +/** Navigate to next responder textField/textView. */ +-(BOOL)goNext +{ + //Getting all responder view's. + NSArray<__kindof UIView*> *textFields = [self responderViews]; + + //Getting index of current textField. + NSUInteger index = [textFields indexOfObject:_textFieldView]; + + //If it is not last textField. then it's next object becomeFirstResponder. + if (index != NSNotFound && + index < textFields.count-1) + { + UITextField *nextTextField = textFields[index+1]; + + // Retaining textFieldView + UIView *textFieldRetain = _textFieldView; + + BOOL isAcceptAsFirstResponder = [nextTextField becomeFirstResponder]; + + // If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96) + if (isAcceptAsFirstResponder == NO) + { + //If next field refuses to become first responder then restoring old textField as first responder. + [textFieldRetain becomeFirstResponder]; + + [self showLog:[NSString stringWithFormat:@"Refuses to become first responder: %@",[nextTextField _IQDescription]]]; + } + + return isAcceptAsFirstResponder; + } + else + { + return NO; + } +} + +#pragma mark AutoToolbar methods + +/** Get all UITextField/UITextView siblings of textFieldView. */ +-(NSArray<__kindof UIView*>*)responderViews +{ + UIView *superConsideredView; + + UIView *textFieldView = _textFieldView; + + //If find any consider responderView in it's upper hierarchy then will get deepResponderView. + for (Class consideredClass in _toolbarPreviousNextAllowedClasses) + { + superConsideredView = [textFieldView superviewOfClassType:consideredClass]; + + if (superConsideredView) + break; + } + + //If there is a superConsideredView in view's hierarchy, then fetching all it's subview that responds. No sorting for superConsideredView, it's by subView position. (Enhancement ID: #22) + if (superConsideredView) + { + return [superConsideredView deepResponderViews]; + } + //Otherwise fetching all the siblings + else + { + NSArray *textFields = [textFieldView responderSiblings]; + + //Sorting textFields according to behaviour + switch (_toolbarManageBehaviour) + { + //If autoToolbar behaviour is bySubviews, then returning it. + case IQAutoToolbarBySubviews: + return textFields; + break; + + //If autoToolbar behaviour is by tag, then sorting it according to tag property. + case IQAutoToolbarByTag: + return [textFields sortedArrayByTag]; + break; + + //If autoToolbar behaviour is by tag, then sorting it according to tag property. + case IQAutoToolbarByPosition: + return [textFields sortedArrayByPosition]; + break; + default: + return nil; + break; + } + } +} + +/** Add toolbar if it is required to add on textFields and it's siblings. */ +-(void)addToolbarIfRequired +{ + CFTimeInterval startTime = CACurrentMediaTime(); + [self showLog:[NSString stringWithFormat:@"****** %@ started ******",NSStringFromSelector(_cmd)]]; + + // Getting all the sibling textFields. + NSArray *siblings = [self responderViews]; + + [self showLog:[NSString stringWithFormat:@"Found %lu responder sibling(s)",(unsigned long)siblings.count]]; + + UIView *textFieldView = _textFieldView; + + //Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar). + //setInputAccessoryView: check (Bug ID: #307) + if ([textFieldView respondsToSelector:@selector(setInputAccessoryView:)]) + { + if ([textFieldView inputAccessoryView] == nil || + [[textFieldView inputAccessoryView] tag] == kIQPreviousNextButtonToolbarTag || + [[textFieldView inputAccessoryView] tag] == kIQDoneButtonToolbarTag) + { + UITextField *textField = (UITextField*)textFieldView; + + IQBarButtonItemConfiguration *rightConfiguration = nil; + + //Supporting Custom Done button image (Enhancement ID: #366) + if (_toolbarDoneBarButtonItemImage) + { + rightConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:_toolbarDoneBarButtonItemImage action:@selector(doneAction:)]; + } + //Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376) + else if (_toolbarDoneBarButtonItemText) + { + rightConfiguration = [[IQBarButtonItemConfiguration alloc] initWithTitle:_toolbarDoneBarButtonItemText action:@selector(doneAction:)]; + } + else + { + rightConfiguration = [[IQBarButtonItemConfiguration alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone action:@selector(doneAction:)]; + } + + // If only one object is found, then adding only Done button. + if ((siblings.count==1 && self.previousNextDisplayMode == IQPreviousNextDisplayModeDefault) || self.previousNextDisplayMode == IQPreviousNextDisplayModeAlwaysHide) + { + [textField addKeyboardToolbarWithTarget:self titleText:(_shouldShowToolbarPlaceholder ? textField.drawingToolbarPlaceholder : nil) rightBarButtonConfiguration:rightConfiguration previousBarButtonConfiguration:nil nextBarButtonConfiguration:nil]; + + textField.inputAccessoryView.tag = kIQDoneButtonToolbarTag; // (Bug ID: #78) + } + //If there is multiple siblings of textField + else if ((siblings.count && self.previousNextDisplayMode == IQPreviousNextDisplayModeDefault) || self.previousNextDisplayMode == IQPreviousNextDisplayModeAlwaysShow) + { + IQBarButtonItemConfiguration *prevConfiguration = nil; + + //Supporting Custom Done button image (Enhancement ID: #366) + if (_toolbarPreviousBarButtonItemImage) + { + prevConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:_toolbarPreviousBarButtonItemImage action:@selector(previousAction:)]; + } + //Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376) + else if (_toolbarPreviousBarButtonItemText) + { + prevConfiguration = [[IQBarButtonItemConfiguration alloc] initWithTitle:_toolbarPreviousBarButtonItemText action:@selector(previousAction:)]; + } + else + { + prevConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:[UIImage keyboardPreviousImage] action:@selector(previousAction:)]; + } + + IQBarButtonItemConfiguration *nextConfiguration = nil; + + //Supporting Custom Done button image (Enhancement ID: #366) + if (_toolbarNextBarButtonItemImage) + { + nextConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:_toolbarNextBarButtonItemImage action:@selector(nextAction:)]; + } + //Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376) + else if (_toolbarNextBarButtonItemText) + { + nextConfiguration = [[IQBarButtonItemConfiguration alloc] initWithTitle:_toolbarNextBarButtonItemText action:@selector(nextAction:)]; + } + else + { + nextConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:[UIImage keyboardNextImage] action:@selector(nextAction:)]; + } + + [textField addKeyboardToolbarWithTarget:self titleText:(_shouldShowToolbarPlaceholder ? textField.drawingToolbarPlaceholder : nil) rightBarButtonConfiguration:rightConfiguration previousBarButtonConfiguration:prevConfiguration nextBarButtonConfiguration:nextConfiguration]; + + textField.inputAccessoryView.tag = kIQPreviousNextButtonToolbarTag; // (Bug ID: #78) + } + + IQToolbar *toolbar = textField.keyboardToolbar; + + //Bar style according to keyboard appearance + if ([textField respondsToSelector:@selector(keyboardAppearance)]) + { + switch ([textField keyboardAppearance]) + { + case UIKeyboardAppearanceDark: + { + toolbar.barStyle = UIBarStyleBlack; + [toolbar setTintColor:[UIColor whiteColor]]; + [toolbar setBarTintColor:nil]; + } + break; + default: + { + toolbar.barStyle = UIBarStyleDefault; + toolbar.barTintColor = _toolbarBarTintColor; + + //Setting toolbar tintColor // (Enhancement ID: #30) + if (_shouldToolbarUsesTextFieldTintColor) + { + toolbar.tintColor = [textField tintColor]; + } + else if (_toolbarTintColor) + { + toolbar.tintColor = _toolbarTintColor; + } + else + { + toolbar.tintColor = [UIColor blackColor]; + } + } + break; + } + + //If need to show placeholder + if (_shouldShowToolbarPlaceholder && + textField.shouldHideToolbarPlaceholder == NO) + { + //Updating placeholder //(Bug ID: #148, #272) + if (toolbar.titleBarButton.title == nil || + [toolbar.titleBarButton.title isEqualToString:textField.drawingToolbarPlaceholder] == NO) + { + [toolbar.titleBarButton setTitle:textField.drawingToolbarPlaceholder]; + } + + //Setting toolbar title font. // (Enhancement ID: #30) + if (_placeholderFont && + [_placeholderFont isKindOfClass:[UIFont class]]) + { + [toolbar.titleBarButton setTitleFont:_placeholderFont]; + } + + //Setting toolbar title color. // (Enhancement ID: #880) + if (_placeholderColor && + [_placeholderColor isKindOfClass:[UIColor class]]) + { + [toolbar.titleBarButton setTitleColor:_placeholderColor]; + } + + //Setting toolbar button title color. // (Enhancement ID: #880) + if (_placeholderButtonColor && + [_placeholderButtonColor isKindOfClass:[UIColor class]]) + { + [toolbar.titleBarButton setSelectableTitleColor:_placeholderButtonColor]; + } + } + else + { + //Updating placeholder //(Bug ID: #272) + toolbar.titleBarButton.title = nil; + } + } + + //In case of UITableView (Special), the next/previous buttons has to be refreshed everytime. (Bug ID: #56) + // If firstTextField, then previous should not be enabled. + if (siblings.firstObject == textField) + { + if (siblings.count == 1) + { + textField.keyboardToolbar.previousBarButton.enabled = NO; + textField.keyboardToolbar.nextBarButton.enabled = NO; + } + else + { + textField.keyboardToolbar.previousBarButton.enabled = NO; + textField.keyboardToolbar.nextBarButton.enabled = YES; + } + } + // If lastTextField then next should not be enaled. + else if ([siblings lastObject] == textField) + { + textField.keyboardToolbar.previousBarButton.enabled = YES; + textField.keyboardToolbar.nextBarButton.enabled = NO; + } + else + { + textField.keyboardToolbar.previousBarButton.enabled = YES; + textField.keyboardToolbar.nextBarButton.enabled = YES; + } + } + } + + CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime; + [self showLog:[NSString stringWithFormat:@"****** %@ ended: %g seconds ******\n",NSStringFromSelector(_cmd),elapsedTime]]; +} + +/** Remove any toolbar if it is IQToolbar. */ +-(void)removeToolbarIfRequired // (Bug ID: #18) +{ + CFTimeInterval startTime = CACurrentMediaTime(); + [self showLog:[NSString stringWithFormat:@"****** %@ started ******",NSStringFromSelector(_cmd)]]; + + // Getting all the sibling textFields. + NSArray *siblings = [self responderViews]; + + [self showLog:[NSString stringWithFormat:@"Found %lu responder sibling(s)",(unsigned long)siblings.count]]; + + for (UITextField *textField in siblings) + { + UIView *toolbar = [textField inputAccessoryView]; + + // (Bug ID: #78) + //setInputAccessoryView: check (Bug ID: #307) + if ([textField respondsToSelector:@selector(setInputAccessoryView:)] && + ([toolbar isKindOfClass:[IQToolbar class]] && (toolbar.tag == kIQDoneButtonToolbarTag || toolbar.tag == kIQPreviousNextButtonToolbarTag))) + { + textField.inputAccessoryView = nil; + [textField reloadInputViews]; + } + } + + CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime; + [self showLog:[NSString stringWithFormat:@"****** %@ ended: %g seconds ******\n",NSStringFromSelector(_cmd),elapsedTime]]; +} + +/** reloadInputViews to reload toolbar buttons enable/disable state on the fly Enhancement ID #434. */ +- (void)reloadInputViews +{ + //If enabled then adding toolbar. + if ([self privateIsEnableAutoToolbar] == YES) + { + [self addToolbarIfRequired]; + } + //Else removing toolbar. + else + { + [self removeToolbarIfRequired]; + } +} + +#pragma mark previous/next/done functionality +/** previousAction. */ +-(void)previousAction:(IQBarButtonItem*)barButton +{ + //If user wants to play input Click sound. Then Play Input Click Sound. + if (_shouldPlayInputClicks) + { + [[UIDevice currentDevice] playInputClick]; + } + + if ([self canGoPrevious]) + { + UIView *currentTextFieldView = _textFieldView; + BOOL isAcceptAsFirstResponder = [self goPrevious]; + + NSInvocation *invocation = barButton.invocation; + + //Handling search bar special case + { + UISearchBar *searchBar = currentTextFieldView.searchBar; + + if (searchBar) + { + invocation = searchBar.keyboardToolbar.previousBarButton.invocation; + } + } + + if (isAcceptAsFirstResponder == YES && barButton.invocation) + { + if (barButton.invocation.methodSignature.numberOfArguments > 2) + { + [barButton.invocation setArgument:¤tTextFieldView atIndex:2]; + } + + [barButton.invocation invoke]; + } + } +} + +/** nextAction. */ +-(void)nextAction:(IQBarButtonItem*)barButton +{ + //If user wants to play input Click sound. Then Play Input Click Sound. + if (_shouldPlayInputClicks) + { + [[UIDevice currentDevice] playInputClick]; + } + + if ([self canGoNext]) + { + UIView *currentTextFieldView = _textFieldView; + BOOL isAcceptAsFirstResponder = [self goNext]; + + NSInvocation *invocation = barButton.invocation; + + //Handling search bar special case + { + UISearchBar *searchBar = currentTextFieldView.searchBar; + + if (searchBar) + { + invocation = searchBar.keyboardToolbar.nextBarButton.invocation; + } + } + + if (isAcceptAsFirstResponder == YES && barButton.invocation) + { + if (barButton.invocation.methodSignature.numberOfArguments > 2) + { + [barButton.invocation setArgument:¤tTextFieldView atIndex:2]; + } + + [barButton.invocation invoke]; + } + } +} + +/** doneAction. Resigning current textField. */ +-(void)doneAction:(IQBarButtonItem*)barButton +{ + //If user wants to play input Click sound. Then Play Input Click Sound. + if (_shouldPlayInputClicks) + { + [[UIDevice currentDevice] playInputClick]; + } + + UIView *currentTextFieldView = _textFieldView; + BOOL isResignedFirstResponder = [self resignFirstResponder]; + + NSInvocation *invocation = barButton.invocation; + + //Handling search bar special case + { + UISearchBar *searchBar = currentTextFieldView.searchBar; + + if (searchBar) + { + invocation = searchBar.keyboardToolbar.doneBarButton.invocation; + } + } + + if (isResignedFirstResponder == YES && barButton.invocation) + { + if (barButton.invocation.methodSignature.numberOfArguments > 2) + { + [barButton.invocation setArgument:¤tTextFieldView atIndex:2]; + } + + [barButton.invocation invoke]; + } +} + +#pragma mark - Customised textField/textView support. + +/** + Add customised Notification for third party customised TextField/TextView. + */ +-(void)registerTextFieldViewClass:(nonnull Class)aClass + didBeginEditingNotificationName:(nonnull NSString *)didBeginEditingNotificationName + didEndEditingNotificationName:(nonnull NSString *)didEndEditingNotificationName +{ + [_registeredClasses addObject:aClass]; + + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldViewDidBeginEditing:) name:didBeginEditingNotificationName object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldViewDidEndEditing:) name:didEndEditingNotificationName object:nil]; +} + +/** + Remove customised Notification for third party customised TextField/TextView. + */ +-(void)unregisterTextFieldViewClass:(nonnull Class)aClass + didBeginEditingNotificationName:(nonnull NSString *)didBeginEditingNotificationName + didEndEditingNotificationName:(nonnull NSString *)didEndEditingNotificationName +{ + [_registeredClasses removeObject:aClass]; + + [[NSNotificationCenter defaultCenter] removeObserver:self name:didBeginEditingNotificationName object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:didEndEditingNotificationName object:nil]; +} + +-(void)registerAllNotifications +{ + // Registering for keyboard notification. + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil]; + + // Registering for UITextField notification. + [self registerTextFieldViewClass:[UITextField class] + didBeginEditingNotificationName:UITextFieldTextDidBeginEditingNotification + didEndEditingNotificationName:UITextFieldTextDidEndEditingNotification]; + + // Registering for UITextView notification. + [self registerTextFieldViewClass:[UITextView class] + didBeginEditingNotificationName:UITextViewTextDidBeginEditingNotification + didEndEditingNotificationName:UITextViewTextDidEndEditingNotification]; + + // Registering for orientation changes notification + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willChangeStatusBarOrientation:) name:UIApplicationWillChangeStatusBarOrientationNotification object:[UIApplication sharedApplication]]; +} + +-(void)unregisterAllNotifications +{ + // Unregistering for keyboard notification. + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil]; + + // Unregistering for UITextField notification. + [self unregisterTextFieldViewClass:[UITextField class] + didBeginEditingNotificationName:UITextFieldTextDidBeginEditingNotification + didEndEditingNotificationName:UITextFieldTextDidEndEditingNotification]; + + // Unregistering for UITextView notification. + [self unregisterTextFieldViewClass:[UITextView class] + didBeginEditingNotificationName:UITextViewTextDidBeginEditingNotification + didEndEditingNotificationName:UITextViewTextDidEndEditingNotification]; + + // Unregistering for orientation changes notification + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillChangeStatusBarOrientationNotification object:[UIApplication sharedApplication]]; +} + +-(void)showLog:(NSString*)logString +{ + if (_enableDebugging) + { + NSLog(@"IQKeyboardManager: %@",logString); + } +} + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/IQKeyboardReturnKeyHandler.h b/Pods/IQKeyboardManager/IQKeyboardManager/IQKeyboardReturnKeyHandler.h new file mode 100644 index 0000000..81cdd4b --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/IQKeyboardReturnKeyHandler.h @@ -0,0 +1,99 @@ +// +// IQKeyboardReturnKeyHandler.h +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQKeyboardManagerConstants.h" + +#import +#import + +#import + +@class UITextField, UIView, UIViewController; +@protocol UITextFieldDelegate, UITextViewDelegate; + +/** + Manages the return key to work like next/done in a view hierarchy. + */ +@interface IQKeyboardReturnKeyHandler : NSObject + +///---------------------- +/// @name Initializations +///---------------------- + +/** + Add all the textFields available in UIViewController's view. + */ +-(nonnull instancetype)initWithViewController:(nullable UIViewController*)controller NS_DESIGNATED_INITIALIZER; + +/** + Unavailable. Please use initWithViewController: or init method + */ +-(nonnull instancetype)initWithCoder:(nullable NSCoder *)aDecoder NS_UNAVAILABLE; + +///--------------- +/// @name Settings +///--------------- + +/** + Delegate of textField/textView. + */ +@property(nullable, nonatomic, weak) id delegate; + +/** + Set the last textfield return key type. Default is UIReturnKeyDefault. + */ +@property(nonatomic, assign) UIReturnKeyType lastTextFieldReturnKeyType; + +///---------------------------------------------- +/// @name Registering/Unregistering textFieldView +///---------------------------------------------- + +/** + Should pass UITextField/UITextView instance. Assign textFieldView delegate to self, change it's returnKeyType. + + @param textFieldView UITextField/UITextView object to register. + */ +-(void)addTextFieldView:(nonnull UIView*)textFieldView; + +/** + Should pass UITextField/UITextView instance. Restore it's textFieldView delegate and it's returnKeyType. + + @param textFieldView UITextField/UITextView object to unregister. + */ +-(void)removeTextFieldView:(nonnull UIView*)textFieldView; + +/** + Add all the UITextField/UITextView responderView's. + + @param view object to register all it's responder subviews. + */ +-(void)addResponderFromView:(nonnull UIView*)view; + +/** + Remove all the UITextField/UITextView responderView's. + + @param view object to unregister all it's responder subviews. + */ +-(void)removeResponderFromView:(nonnull UIView*)view; + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/IQKeyboardReturnKeyHandler.m b/Pods/IQKeyboardManager/IQKeyboardManager/IQKeyboardReturnKeyHandler.m new file mode 100644 index 0000000..5fbb415 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/IQKeyboardReturnKeyHandler.m @@ -0,0 +1,637 @@ +// +// IQKeyboardReturnKeyHandler.m +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQKeyboardReturnKeyHandler.h" +#import "IQKeyboardManager.h" +#import "IQUIView+Hierarchy.h" +#import "IQNSArray+Sort.h" + +#import +#import +#import + +@interface IQTextFieldViewInfoModal : NSObject + +@property(nullable, nonatomic, weak) UIView *textFieldView; +@property(nullable, nonatomic, weak) id textFieldDelegate; +@property(nullable, nonatomic, weak) id textViewDelegate; +@property(nonatomic) UIReturnKeyType originalReturnKeyType; + +@end + +@implementation IQTextFieldViewInfoModal + +-(instancetype)initWithTextFieldView:(UIView*)textFieldView textFieldDelegate:(id)textFieldDelegate textViewDelegate:(id)textViewDelegate originalReturnKey:(UIReturnKeyType)returnKeyType +{ + self = [super init]; + + if (self) + { + _textFieldView = textFieldView; + _textFieldDelegate = textFieldDelegate; + _textViewDelegate = textViewDelegate; + _originalReturnKeyType = returnKeyType; + } + + return self; +} + +@end + + +@interface IQKeyboardReturnKeyHandler () + +-(void)updateReturnKeyTypeOnTextField:(UIView*)textField; + +@end + +@implementation IQKeyboardReturnKeyHandler +{ + NSMutableSet *textFieldInfoCache; +} + +@synthesize lastTextFieldReturnKeyType = _lastTextFieldReturnKeyType; +@synthesize delegate = _delegate; + +- (instancetype)init +{ + self = [self initWithViewController:nil]; + return self; +} + +-(instancetype)initWithViewController:(nullable UIViewController*)controller +{ + self = [super init]; + + if (self) + { + textFieldInfoCache = [[NSMutableSet alloc] init]; + + if (controller.view) + { + [self addResponderFromView:controller.view]; + } + } + + return self; +} + +-(IQTextFieldViewInfoModal*)textFieldViewCachedInfo:(UIView*)textField +{ + for (IQTextFieldViewInfoModal *modal in textFieldInfoCache) + if (modal.textFieldView == textField) return modal; + + return nil; +} + +#pragma mark - Add/Remove TextFields +-(void)addResponderFromView:(UIView*)view +{ + NSArray *textFields = [view deepResponderViews]; + + for (UIView *textField in textFields) [self addTextFieldView:textField]; +} + +-(void)removeResponderFromView:(UIView*)view +{ + NSArray *textFields = [view deepResponderViews]; + + for (UIView *textField in textFields) [self removeTextFieldView:textField]; +} + +-(void)removeTextFieldView:(UIView*)view +{ + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:view]; + + if (modal) + { + if ([view isKindOfClass:[UITextField class]]) + { + UITextField *textField = (UITextField*)view; + textField.returnKeyType = modal.originalReturnKeyType; + textField.delegate = modal.textFieldDelegate; + } + else if ([view isKindOfClass:[UITextView class]]) + { + UITextView *textView = (UITextView*)view; + textView.returnKeyType = modal.originalReturnKeyType; + textView.delegate = modal.textViewDelegate; + } + + [textFieldInfoCache removeObject:modal]; + } +} + +-(void)addTextFieldView:(UIView*)view +{ + IQTextFieldViewInfoModal *modal = [[IQTextFieldViewInfoModal alloc] initWithTextFieldView:view textFieldDelegate:nil textViewDelegate:nil originalReturnKey:UIReturnKeyDefault]; + + if ([view isKindOfClass:[UITextField class]]) + { + UITextField *textField = (UITextField*)view; + modal.originalReturnKeyType = textField.returnKeyType; + modal.textFieldDelegate = textField.delegate; + [textField setDelegate:self]; + } + else if ([view isKindOfClass:[UITextView class]]) + { + UITextView *textView = (UITextView*)view; + modal.originalReturnKeyType = textView.returnKeyType; + modal.textViewDelegate = textView.delegate; + [textView setDelegate:self]; + } + + [textFieldInfoCache addObject:modal]; +} + +-(void)updateReturnKeyTypeOnTextField:(UIView*)textField +{ + UIView *superConsideredView; + + //If find any consider responderView in it's upper hierarchy then will get deepResponderView. (Bug ID: #347) + for (Class consideredClass in [[IQKeyboardManager sharedManager] toolbarPreviousNextAllowedClasses]) + { + superConsideredView = [textField superviewOfClassType:consideredClass]; + + if (superConsideredView) + break; + } + + NSArray *textFields = nil; + + //If there is a tableView in view's hierarchy, then fetching all it's subview that responds. No sorting for tableView, it's by subView position. + if (superConsideredView) // // (Enhancement ID: #22) + { + textFields = [superConsideredView deepResponderViews]; + } + //Otherwise fetching all the siblings + else + { + textFields = [textField responderSiblings]; + + //Sorting textFields according to behaviour + switch ([[IQKeyboardManager sharedManager] toolbarManageBehaviour]) + { + //If needs to sort it by tag + case IQAutoToolbarByTag: + textFields = [textFields sortedArrayByTag]; + break; + + //If needs to sort it by Position + case IQAutoToolbarByPosition: + textFields = [textFields sortedArrayByPosition]; + break; + + default: + break; + } + } + + //If it's the last textField in responder view, else next + [(UITextField*)textField setReturnKeyType:(([textFields lastObject] == textField) ? self.lastTextFieldReturnKeyType : UIReturnKeyNext)]; +} + +#pragma mark - Goto next or Resign. + +-(BOOL)goToNextResponderOrResign:(UIView*)textField +{ + UIView *superConsideredView; + + //If find any consider responderView in it's upper hierarchy then will get deepResponderView. (Bug ID: #347) + for (Class consideredClass in [[IQKeyboardManager sharedManager] toolbarPreviousNextAllowedClasses]) + { + superConsideredView = [textField superviewOfClassType:consideredClass]; + + if (superConsideredView) + break; + } + + NSArray *textFields = nil; + + //If there is a tableView in view's hierarchy, then fetching all it's subview that responds. No sorting for tableView, it's by subView position. + if (superConsideredView) // // (Enhancement ID: #22) + { + textFields = [superConsideredView deepResponderViews]; + } + //Otherwise fetching all the siblings + else + { + textFields = [textField responderSiblings]; + + //Sorting textFields according to behaviour + switch ([[IQKeyboardManager sharedManager] toolbarManageBehaviour]) + { + //If needs to sort it by tag + case IQAutoToolbarByTag: + textFields = [textFields sortedArrayByTag]; + break; + + //If needs to sort it by Position + case IQAutoToolbarByPosition: + textFields = [textFields sortedArrayByPosition]; + break; + + default: + break; + } + } + + //Getting index of current textField. + NSUInteger index = [textFields indexOfObject:textField]; + + //If it is not last textField. then it's next object becomeFirstResponder. + if (index != NSNotFound && index < textFields.count-1) + { + [textFields[index+1] becomeFirstResponder]; + return NO; + } + else + { + [textField resignFirstResponder]; + return YES; + } +} + +#pragma mark - TextField delegate +- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textField]; + delegate = modal.textFieldDelegate; + } + + if ([delegate respondsToSelector:@selector(textFieldShouldBeginEditing:)]) + return [delegate textFieldShouldBeginEditing:textField]; + else + return YES; +} + +- (void)textFieldDidBeginEditing:(UITextField *)textField +{ + [self updateReturnKeyTypeOnTextField:textField]; + + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textField]; + delegate = modal.textFieldDelegate; + } + + if ([delegate respondsToSelector:@selector(textFieldDidBeginEditing:)]) + [delegate textFieldDidBeginEditing:textField]; +} + +- (BOOL)textFieldShouldEndEditing:(UITextField *)textField +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textField]; + delegate = modal.textFieldDelegate; + } + + if ([delegate respondsToSelector:@selector(textFieldShouldEndEditing:)]) + return [delegate textFieldShouldEndEditing:textField]; + else + return YES; +} + +- (void)textFieldDidEndEditing:(UITextField *)textField +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textField]; + delegate = modal.textFieldDelegate; + } + + if ([delegate respondsToSelector:@selector(textFieldDidEndEditing:)]) + [delegate textFieldDidEndEditing:textField]; +} + +- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason NS_AVAILABLE_IOS(10_0); +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textField]; + delegate = modal.textFieldDelegate; + } + +#ifdef __IPHONE_11_0 + if (@available(iOS 10.0, *)) { +#endif + if ([delegate respondsToSelector:@selector(textFieldDidEndEditing:reason:)]) + [delegate textFieldDidEndEditing:textField reason:reason]; +#ifdef __IPHONE_11_0 + } +#endif +} + +- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textField]; + delegate = modal.textFieldDelegate; + } + + if ([delegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) + return [delegate textField:textField shouldChangeCharactersInRange:range replacementString:string]; + else + return YES; +} + +- (BOOL)textFieldShouldClear:(UITextField *)textField +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textField]; + delegate = modal.textFieldDelegate; + } + + if ([delegate respondsToSelector:@selector(textFieldShouldClear:)]) + return [delegate textFieldShouldClear:textField]; + else + return YES; +} + +-(BOOL)textFieldShouldReturn:(UITextField *)textField +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textField]; + delegate = modal.textFieldDelegate; + } + + if ([delegate respondsToSelector:@selector(textFieldShouldReturn:)]) + { + BOOL shouldReturn = [delegate textFieldShouldReturn:textField]; + + if (shouldReturn) + { + shouldReturn = [self goToNextResponderOrResign:textField]; + } + + return shouldReturn; + } + else + { + return [self goToNextResponderOrResign:textField]; + } +} + + +#pragma mark - TextView delegate +- (BOOL)textViewShouldBeginEditing:(UITextView *)textView +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textView]; + delegate = modal.textViewDelegate; + } + + if ([delegate respondsToSelector:@selector(textViewShouldBeginEditing:)]) + return [delegate textViewShouldBeginEditing:textView]; + else + return YES; +} + +- (BOOL)textViewShouldEndEditing:(UITextView *)textView +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textView]; + delegate = modal.textViewDelegate; + } + + if ([delegate respondsToSelector:@selector(textViewShouldEndEditing:)]) + return [delegate textViewShouldEndEditing:textView]; + else + return YES; +} + +- (void)textViewDidBeginEditing:(UITextView *)textView +{ + [self updateReturnKeyTypeOnTextField:textView]; + + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textView]; + delegate = modal.textViewDelegate; + } + + if ([delegate respondsToSelector:@selector(textViewDidBeginEditing:)]) + [delegate textViewDidBeginEditing:textView]; +} + +- (void)textViewDidEndEditing:(UITextView *)textView +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textView]; + delegate = modal.textViewDelegate; + } + + if ([delegate respondsToSelector:@selector(textViewDidEndEditing:)]) + [delegate textViewDidEndEditing:textView]; +} + +- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textView]; + delegate = modal.textViewDelegate; + } + + BOOL shouldReturn = YES; + + if ([delegate respondsToSelector:@selector(textView:shouldChangeTextInRange:replacementText:)]) + shouldReturn = [delegate textView:textView shouldChangeTextInRange:range replacementText:text]; + + if (shouldReturn && [text isEqualToString:@"\n"]) + { + shouldReturn = [self goToNextResponderOrResign:textView]; + } + + return shouldReturn; +} + +- (void)textViewDidChange:(UITextView *)textView +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textView]; + delegate = modal.textViewDelegate; + } + + if ([delegate respondsToSelector:@selector(textViewDidChange:)]) + [delegate textViewDidChange:textView]; +} + +- (void)textViewDidChangeSelection:(UITextView *)textView +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textView]; + delegate = modal.textViewDelegate; + } + + if ([delegate respondsToSelector:@selector(textViewDidChangeSelection:)]) + [delegate textViewDidChangeSelection:textView]; +} + +- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction NS_AVAILABLE_IOS(10_0); +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textView]; + delegate = modal.textViewDelegate; + } + +#ifdef __IPHONE_11_0 + if (@available(iOS 10.0, *)) { +#endif + if ([delegate respondsToSelector:@selector(textView:shouldInteractWithURL:inRange:interaction:)]) + return [delegate textView:textView shouldInteractWithURL:URL inRange:characterRange interaction:interaction]; +#ifdef __IPHONE_11_0 + } +#endif + + return YES; +} + +- (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction NS_AVAILABLE_IOS(10_0); +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textView]; + delegate = modal.textViewDelegate; + } + +#ifdef __IPHONE_11_0 + if (@available(iOS 10.0, *)) { +#endif + if ([delegate respondsToSelector:@selector(textView:shouldInteractWithTextAttachment:inRange:interaction:)]) + return [delegate textView:textView shouldInteractWithTextAttachment:textAttachment inRange:characterRange interaction:interaction]; +#ifdef __IPHONE_11_0 + } +#endif + + return YES; +} + +- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textView]; + delegate = modal.textViewDelegate; + } + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + if ([delegate respondsToSelector:@selector(textView:shouldInteractWithURL:inRange:)]) + return [delegate textView:textView shouldInteractWithURL:URL inRange:characterRange]; +#pragma clang diagnostic pop + else + return YES; +} + +- (BOOL)textView:(UITextView *)textView shouldInteractWithTextAttachment:(NSTextAttachment *)textAttachment inRange:(NSRange)characterRange +{ + id delegate = self.delegate; + + if (delegate == nil) + { + IQTextFieldViewInfoModal *modal = [self textFieldViewCachedInfo:textView]; + delegate = modal.textViewDelegate; + } + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + if ([delegate respondsToSelector:@selector(textView:shouldInteractWithTextAttachment:inRange:)]) + return [delegate textView:textView shouldInteractWithTextAttachment:textAttachment inRange:characterRange]; +#pragma clang diagnostic pop + else + return YES; +} + +-(void)dealloc +{ + for (IQTextFieldViewInfoModal *modal in textFieldInfoCache) + { + UIView *textFieldView = modal.textFieldView; + if ([textFieldView isKindOfClass:[UITextField class]]) + { + UITextField *textField = (UITextField*)textFieldView; + textField.returnKeyType = modal.originalReturnKeyType; + textField.delegate = modal.textFieldDelegate + ; + } + else if ([textFieldView isKindOfClass:[UITextView class]]) + { + UITextView *textView = (UITextView*)textFieldView; + textView.returnKeyType = modal.originalReturnKeyType; + textView.delegate = modal.textViewDelegate; + } + } + + [textFieldInfoCache removeAllObjects]; +} + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/IQTextView/IQTextView.h b/Pods/IQKeyboardManager/IQKeyboardManager/IQTextView/IQTextView.h new file mode 100644 index 0000000..8ff1859 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/IQTextView/IQTextView.h @@ -0,0 +1,47 @@ +// +// IQTextView.h +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQKeyboardManagerConstants.h" + +#import + +/** + UITextView with placeholder support + */ +@interface IQTextView : UITextView + +/** + Set textView's placeholder text. Default is nil. + */ +@property(nullable, nonatomic,copy) IBInspectable NSString *placeholder; + +/** + To set textView's placeholder text color. Default is nil. + */ +@property(nullable, nonatomic,copy) IBInspectable UIColor *placeholderTextColor; + +@end + + + + diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/IQTextView/IQTextView.m b/Pods/IQKeyboardManager/IQKeyboardManager/IQTextView/IQTextView.m new file mode 100644 index 0000000..ff06fa3 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/IQTextView/IQTextView.m @@ -0,0 +1,165 @@ +// +// IQTextView.m +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQTextView.h" + +#import +#import +#import + +@interface IQTextView () + +@property(nonatomic, strong) UILabel *placeholderLabel; + +@end + +@implementation IQTextView + +@synthesize placeholder = _placeholder; +@synthesize placeholderLabel = _placeholderLabel; +@synthesize placeholderTextColor = _placeholderTextColor; + +-(void)initialize +{ + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshPlaceholder) name:UITextViewTextDidChangeNotification object:self]; +} + +-(void)dealloc +{ + [_placeholderLabel removeFromSuperview]; + _placeholderLabel = nil; + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +- (instancetype)init +{ + self = [super init]; + if (self) { + [self initialize]; + } + return self; +} + +-(void)awakeFromNib +{ + [super awakeFromNib]; + [self initialize]; +} + +-(void)refreshPlaceholder +{ + if([[self text] length]) + { + [_placeholderLabel setAlpha:0]; + } + else + { + [_placeholderLabel setAlpha:1]; + } + + [self setNeedsLayout]; + [self layoutIfNeeded]; +} + +- (void)setText:(NSString *)text +{ + [super setText:text]; + [self refreshPlaceholder]; +} + +-(void)setFont:(UIFont *)font +{ + [super setFont:font]; + self.placeholderLabel.font = self.font; + + [self setNeedsLayout]; + [self layoutIfNeeded]; +} + +-(void)setTextAlignment:(NSTextAlignment)textAlignment +{ + [super setTextAlignment:textAlignment]; + self.placeholderLabel.textAlignment = textAlignment; + + [self setNeedsLayout]; + [self layoutIfNeeded]; +} + +-(void)layoutSubviews +{ + [super layoutSubviews]; + + UIEdgeInsets placeholderInsets = [self placeholderInsets]; + CGFloat maxWidth = CGRectGetWidth(self.frame)-placeholderInsets.left-placeholderInsets.right; + + CGSize expectedSize = [self.placeholderLabel sizeThatFits:CGSizeMake(maxWidth, CGRectGetHeight(self.frame)-placeholderInsets.top-placeholderInsets.bottom)]; + + self.placeholderLabel.frame = CGRectMake(placeholderInsets.left, placeholderInsets.top, maxWidth, expectedSize.height); +} + +-(void)setPlaceholder:(NSString *)placeholder +{ + _placeholder = placeholder; + + self.placeholderLabel.text = placeholder; + [self refreshPlaceholder]; +} + +-(void)setPlaceholderTextColor:(UIColor*)placeholderTextColor +{ + _placeholderTextColor = placeholderTextColor; + self.placeholderLabel.textColor = placeholderTextColor; +} + +-(UIEdgeInsets)placeholderInsets +{ + return UIEdgeInsetsMake(self.textContainerInset.top, self.textContainerInset.left + self.textContainer.lineFragmentPadding, self.textContainerInset.bottom, self.textContainerInset.right + self.textContainer.lineFragmentPadding); +} + +-(UILabel*)placeholderLabel +{ + if (_placeholderLabel == nil) + { + _placeholderLabel = [[UILabel alloc] init]; + _placeholderLabel.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight); + _placeholderLabel.lineBreakMode = NSLineBreakByWordWrapping; + _placeholderLabel.numberOfLines = 0; + _placeholderLabel.font = self.font; + _placeholderLabel.textAlignment = self.textAlignment; + _placeholderLabel.backgroundColor = [UIColor clearColor]; + _placeholderLabel.textColor = [UIColor colorWithWhite:0.7 alpha:1.0]; + _placeholderLabel.alpha = 0; + [self addSubview:_placeholderLabel]; + } + + return _placeholderLabel; +} + +//When any text changes on textField, the delegate getter is called. At this time we refresh the textView's placeholder +-(id)delegate +{ + [self refreshPlaceholder]; + return [super delegate]; +} + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQBarButtonItem.h b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQBarButtonItem.h new file mode 100644 index 0000000..25bf9ad --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQBarButtonItem.h @@ -0,0 +1,51 @@ +// +// IQBarButtonItem.h +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 + +@class NSInvocation; + +/** + IQBarButtonItem used for IQToolbar. + */ +@interface IQBarButtonItem : UIBarButtonItem + +/** + Boolean to know if it's a system item or custom item + */ +@property (nonatomic, readonly) BOOL isSystemItem; + +/** + Additional target & action to do get callback action. Note that setting custom target & selector doesn't affect native functionality, this is just an additional target to get a callback. + + @param target Target object. + @param action Target Selector. + */ +-(void)setTarget:(nullable id)target action:(nullable SEL)action; + +/** + Customized Invocation to be called when button is pressed. invocation is internally created using setTarget:action: method. + */ +@property (nullable, strong, nonatomic) NSInvocation *invocation; + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQBarButtonItem.m b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQBarButtonItem.m new file mode 100644 index 0000000..fb28fb2 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQBarButtonItem.m @@ -0,0 +1,99 @@ +// +// IQBarButtonItem.m +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQBarButtonItem.h" +#import "IQKeyboardManagerConstantsInternal.h" +#import + +@implementation IQBarButtonItem + ++(void)initialize +{ + [super initialize]; + + IQBarButtonItem *appearanceProxy = [self appearance]; + + NSArray *states = @[@(UIControlStateNormal),@(UIControlStateHighlighted),@(UIControlStateDisabled),@(UIControlStateSelected),@(UIControlStateApplication),@(UIControlStateReserved)]; + + for (NSNumber *state in states) + { + UIControlState controlState = [state unsignedIntegerValue]; + + [appearanceProxy setBackgroundImage:nil forState:controlState barMetrics:UIBarMetricsDefault]; + [appearanceProxy setBackgroundImage:nil forState:controlState style:UIBarButtonItemStyleDone barMetrics:UIBarMetricsDefault]; + [appearanceProxy setBackgroundImage:nil forState:controlState style:UIBarButtonItemStylePlain barMetrics:UIBarMetricsDefault]; + [appearanceProxy setBackButtonBackgroundImage:nil forState:controlState barMetrics:UIBarMetricsDefault]; + } + + [appearanceProxy setTitlePositionAdjustment:UIOffsetZero forBarMetrics:UIBarMetricsDefault]; + [appearanceProxy setBackgroundVerticalPositionAdjustment:0 forBarMetrics:UIBarMetricsDefault]; + [appearanceProxy setBackButtonBackgroundVerticalPositionAdjustment:0 forBarMetrics:UIBarMetricsDefault]; +} + +-(void)setTintColor:(UIColor *)tintColor +{ + [super setTintColor:tintColor]; + + //titleTextAttributes tweak is to overcome an issue comes with iOS11 where appearanceProxy set for NSForegroundColorAttributeName and bar button texts start appearing in appearance proxy color + NSMutableDictionary *textAttributes = [[self titleTextAttributesForState:UIControlStateNormal] mutableCopy]?:[NSMutableDictionary new]; + + textAttributes[NSForegroundColorAttributeName] = tintColor; + + [self setTitleTextAttributes:textAttributes forState:UIControlStateNormal]; +} + +- (instancetype)initWithBarButtonSystemItem:(UIBarButtonSystemItem)systemItem target:(nullable id)target action:(nullable SEL)action +{ + self = [super initWithBarButtonSystemItem:systemItem target:target action:action]; + + if (self) + { + _isSystemItem = YES; + } + + return self; +} + + +-(void)setTarget:(nullable id)target action:(nullable SEL)action +{ + NSInvocation *invocation = nil; + + if (target && action) + { + invocation = [NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:action]]; + invocation.target = target; + invocation.selector = action; + } + + self.invocation = invocation; +} + +-(void)dealloc +{ + self.target = nil; + self.invocation.target = nil; + self.invocation = nil; +} + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQPreviousNextView.h b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQPreviousNextView.h new file mode 100644 index 0000000..aa282ee --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQPreviousNextView.h @@ -0,0 +1,30 @@ +// +// IQPreviousNextView.h +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 +/** + If you need to enable previous/next toolbar button with some complex hierarchy where your textFields are not in same view, then make the top view as IQPreviousNextView. + */ +@interface IQPreviousNextView : UIView + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQPreviousNextView.m b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQPreviousNextView.m new file mode 100644 index 0000000..207d115 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQPreviousNextView.m @@ -0,0 +1,28 @@ +// +// IQPreviousNextView.m +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQPreviousNextView.h" + +@implementation IQPreviousNextView + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQTitleBarButtonItem.h b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQTitleBarButtonItem.h new file mode 100644 index 0000000..bd16835 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQTitleBarButtonItem.h @@ -0,0 +1,71 @@ +// +// IQTitleBarButtonItem.h +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQKeyboardManagerConstants.h" +#import "IQBarButtonItem.h" + +#import + +/** + BarButtonItem with title text. + */ +@interface IQTitleBarButtonItem : IQBarButtonItem + +/** + Font to be used in bar button. Default is (system font 12.0 bold). + */ +@property(nullable, nonatomic, strong) UIFont *titleFont; + +/** + titleColor to be used for displaying button text when displaying title (disabled state). + */ +@property(nullable, nonatomic, strong) UIColor *titleColor; + +/** + selectableTitleColor to be used for displaying button text when button is enabled. + */ +@property(nullable, nonatomic, strong) UIColor *selectableTitleColor; + +/** + Initialize with frame and title. + + @param title Title of barButtonItem. + */ +-(nonnull instancetype)initWithTitle:(nullable NSString *)title NS_DESIGNATED_INITIALIZER; + +/** + Unavailable. Please use initWithFrame:title: method + */ +-(nonnull instancetype)init NS_UNAVAILABLE; + +/** + Unavailable. Please use initWithFrame:title: method + */ +-(nonnull instancetype)initWithCoder:(nullable NSCoder *)aDecoder NS_UNAVAILABLE; + +/** + Unavailable. Please use initWithFrame:title: method + */ ++ (nonnull instancetype)new NS_UNAVAILABLE; + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQTitleBarButtonItem.m b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQTitleBarButtonItem.m new file mode 100644 index 0000000..7a4ffe9 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQTitleBarButtonItem.m @@ -0,0 +1,153 @@ +// +// IQTitleBarButtonItem.m +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQTitleBarButtonItem.h" +#import "IQKeyboardManagerConstants.h" +#import "IQKeyboardManagerConstantsInternal.h" + +#import +#import + +@interface IQTitleBarButtonItem () + +@property(nonatomic, strong) UIView *titleView; +@property(nonatomic, strong) UIButton *titleButton; + +@end + +@implementation IQTitleBarButtonItem + +-(nonnull instancetype)initWithTitle:(nullable NSString *)title +{ + self = [super init]; + if (self) + { + _titleView = [[UIView alloc] init]; + _titleView.backgroundColor = [UIColor clearColor]; + + _titleButton = [UIButton buttonWithType:UIButtonTypeSystem]; + _titleButton.enabled = NO; + _titleButton.titleLabel.numberOfLines = 3; + [_titleButton setTitleColor:[UIColor colorWithRed:0.0 green:0.5 blue:1.0 alpha:1.0] forState:UIControlStateNormal]; + [_titleButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled]; + [_titleButton setBackgroundColor:[UIColor clearColor]]; + [_titleButton.titleLabel setTextAlignment:NSTextAlignmentCenter]; + [self setTitle:title]; + [self setTitleFont:[UIFont systemFontOfSize:13.0]]; + [_titleView addSubview:_titleButton]; + +#ifdef __IPHONE_11_0 + if (@available(iOS 11.0, *)) + { + CGFloat layoutDefaultLowPriority = UILayoutPriorityDefaultLow-1; + CGFloat layoutDefaultHighPriority = UILayoutPriorityDefaultHigh-1; + + _titleView.translatesAutoresizingMaskIntoConstraints = NO; + [_titleView setContentHuggingPriority:layoutDefaultLowPriority forAxis:UILayoutConstraintAxisVertical]; + [_titleView setContentHuggingPriority:layoutDefaultLowPriority forAxis:UILayoutConstraintAxisHorizontal]; + [_titleView setContentCompressionResistancePriority:layoutDefaultHighPriority forAxis:UILayoutConstraintAxisVertical]; + [_titleView setContentCompressionResistancePriority:layoutDefaultHighPriority forAxis:UILayoutConstraintAxisHorizontal]; + + _titleButton.translatesAutoresizingMaskIntoConstraints = NO; + [_titleButton setContentHuggingPriority:layoutDefaultLowPriority forAxis:UILayoutConstraintAxisVertical]; + [_titleButton setContentHuggingPriority:layoutDefaultLowPriority forAxis:UILayoutConstraintAxisHorizontal]; + [_titleButton setContentCompressionResistancePriority:layoutDefaultHighPriority forAxis:UILayoutConstraintAxisVertical]; + [_titleButton setContentCompressionResistancePriority:layoutDefaultHighPriority forAxis:UILayoutConstraintAxisHorizontal]; + + NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:_titleButton attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:_titleView attribute:NSLayoutAttributeTop multiplier:1 constant:0]; + NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:_titleButton attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:_titleView attribute:NSLayoutAttributeBottom multiplier:1 constant:0]; + NSLayoutConstraint *leading = [NSLayoutConstraint constraintWithItem:_titleButton attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:_titleView attribute:NSLayoutAttributeLeading multiplier:1 constant:0]; + NSLayoutConstraint *trailing = [NSLayoutConstraint constraintWithItem:_titleButton attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:_titleView attribute:NSLayoutAttributeTrailing multiplier:1 constant:0]; + [_titleView addConstraints:@[top,bottom,leading,trailing]]; + } + else +#endif + { + _titleView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + _titleButton.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + } + + self.customView = _titleView; + } + return self; +} + +-(void)setTitleFont:(UIFont *)titleFont +{ + _titleFont = titleFont; + + if (titleFont) + { + _titleButton.titleLabel.font = titleFont; + } + else + { + _titleButton.titleLabel.font = [UIFont systemFontOfSize:13]; + } +} + +-(void)setTitle:(NSString *)title +{ + [super setTitle:title]; + [_titleButton setTitle:title forState:UIControlStateNormal]; +} + +-(void)setTitleColor:(UIColor*)titleColor +{ + _titleColor = titleColor; + [_titleButton setTitleColor:_titleColor?:[UIColor lightGrayColor] forState:UIControlStateDisabled]; +} + +-(void)setSelectableTitleColor:(UIColor*)selectableTitleColor +{ + _selectableTitleColor = selectableTitleColor; + [_titleButton setTitleColor:_selectableTitleColor?:[UIColor colorWithRed:0.0 green:0.5 blue:1.0 alpha:1.0] forState:UIControlStateNormal]; +} + +-(void)setInvocation:(NSInvocation *)invocation +{ + [super setInvocation:invocation]; + + if (invocation.target == nil || invocation.selector == NULL) + { + self.enabled = NO; + _titleButton.enabled = NO; + [_titleButton removeTarget:nil action:NULL forControlEvents:UIControlEventTouchUpInside]; + } + else + { + self.enabled = YES; + _titleButton.enabled = YES; + [_titleButton addTarget:invocation.target action:invocation.selector forControlEvents:UIControlEventTouchUpInside]; + } +} + +-(void)dealloc +{ + self.customView = nil; + [_titleButton removeTarget:nil action:NULL forControlEvents:UIControlEventTouchUpInside]; + _titleView = nil; + _titleButton = nil; +} + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQToolbar.h b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQToolbar.h new file mode 100644 index 0000000..3ab3aee --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQToolbar.h @@ -0,0 +1,60 @@ +// +// IQToolbar.h +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQTitleBarButtonItem.h" + +#import +#import + +/** + IQToolbar for IQKeyboardManager. + */ +@interface IQToolbar : UIToolbar + +/** + Previous bar button of toolbar. + */ +@property(nonnull, nonatomic, strong) IQBarButtonItem *previousBarButton; + +/** + Next bar button of toolbar. + */ +@property(nonnull, nonatomic, strong) IQBarButtonItem *nextBarButton; + +/** + Title bar button of toolbar. + */ +@property(nonnull, nonatomic, strong, readonly) IQTitleBarButtonItem *titleBarButton; + +/** + Done bar button of toolbar. + */ +@property(nonnull, nonatomic, strong) IQBarButtonItem *doneBarButton; + +/** + Fixed space bar button of toolbar. + */ +@property(nonnull, nonatomic, strong) IQBarButtonItem *fixedSpaceBarButton; + +@end + diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQToolbar.m b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQToolbar.m new file mode 100644 index 0000000..9bb2270 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQToolbar.m @@ -0,0 +1,300 @@ +// +// IQToolbar.m +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQToolbar.h" +#import "IQKeyboardManagerConstantsInternal.h" +#import "IQUIView+Hierarchy.h" + +#import +#import +#import + +@interface IQTitleBarButtonItem (PrivateAccessor) + +@property(nonatomic, strong) UIButton *titleButton; + +@end + +@implementation IQToolbar +@synthesize previousBarButton = _previousBarButton; +@synthesize nextBarButton = _nextBarButton; +@synthesize titleBarButton = _titleBarButton; +@synthesize doneBarButton = _doneBarButton; +@synthesize fixedSpaceBarButton = _fixedSpaceBarButton; + ++(void)initialize +{ + [super initialize]; + + IQToolbar *appearanceProxy = [self appearance]; + + NSArray *positions = @[@(UIBarPositionAny),@(UIBarPositionBottom),@(UIBarPositionTop),@(UIBarPositionTopAttached)]; + + for (NSNumber *position in positions) + { + UIToolbarPosition toolbarPosition = [position unsignedIntegerValue]; + + [appearanceProxy setBackgroundImage:nil forToolbarPosition:toolbarPosition barMetrics:UIBarMetricsDefault]; + [appearanceProxy setShadowImage:nil forToolbarPosition:toolbarPosition]; + } +} + +-(void)initialize +{ + [self sizeToFit]; + self.autoresizingMask = UIViewAutoresizingFlexibleWidth;// | UIViewAutoresizingFlexibleHeight; + self.translucent = YES; +} + +- (instancetype)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if (self) + { + [self initialize]; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)coder +{ + self = [super initWithCoder:coder]; + if (self) + { + [self initialize]; + } + return self; +} + +-(void)dealloc +{ + self.items = nil; + _previousBarButton = nil; + _nextBarButton = nil; + _titleBarButton = nil; + _doneBarButton = nil; + _fixedSpaceBarButton = nil; +} + +-(IQBarButtonItem *)previousBarButton +{ + if (_previousBarButton == nil) + { + _previousBarButton = [[IQBarButtonItem alloc] initWithImage:nil style:UIBarButtonItemStylePlain target:nil action:nil]; + _previousBarButton.accessibilityLabel = @"Toolbar Previous Button"; + } + + return _previousBarButton; +} + +-(IQBarButtonItem *)nextBarButton +{ + if (_nextBarButton == nil) + { + _nextBarButton = [[IQBarButtonItem alloc] initWithImage:nil style:UIBarButtonItemStylePlain target:nil action:nil]; + _nextBarButton.accessibilityLabel = @"Toolbar Next Button"; + } + + return _nextBarButton; +} + +-(IQTitleBarButtonItem *)titleBarButton +{ + if (_titleBarButton == nil) + { + _titleBarButton = [[IQTitleBarButtonItem alloc] initWithTitle:nil]; + _titleBarButton.accessibilityLabel = @"Toolbar Title Button"; + } + + return _titleBarButton; +} + +-(IQBarButtonItem *)doneBarButton +{ + if (_doneBarButton == nil) + { + _doneBarButton = [[IQBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:nil action:nil]; + _doneBarButton.accessibilityLabel = @"Toolbar Done Button"; + } + + return _doneBarButton; +} + +-(IQBarButtonItem *)fixedSpaceBarButton +{ + if (_fixedSpaceBarButton == nil) + { + _fixedSpaceBarButton = [[IQBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]; +#ifdef __IPHONE_11_0 + if (@available(iOS 10.0, *)) +#else + if (IQ_IS_IOS10_OR_GREATER) +#endif + { + [_fixedSpaceBarButton setWidth:6]; + } + else + { + [_fixedSpaceBarButton setWidth:20]; + } + } + + return _fixedSpaceBarButton; +} + +-(CGSize)sizeThatFits:(CGSize)size +{ + CGSize sizeThatFit = [super sizeThatFits:size]; + + sizeThatFit.height = 44; + + return sizeThatFit; +} + +-(void)setBarStyle:(UIBarStyle)barStyle +{ + [super setBarStyle:barStyle]; + + if (self.titleBarButton.selectableTitleColor == nil) + { + if (barStyle == UIBarStyleDefault) + { + [self.titleBarButton.titleButton setTitleColor:[UIColor colorWithRed:0.0 green:0.5 blue:1.0 alpha:1.0] forState:UIControlStateNormal]; + } + else + { + [self.titleBarButton.titleButton setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal]; + } + } +} + +-(void)setTintColor:(UIColor *)tintColor +{ + [super setTintColor:tintColor]; + + for (UIBarButtonItem *item in self.items) + { + [item setTintColor:tintColor]; + } +} + +-(void)layoutSubviews +{ + [super layoutSubviews]; + + //If running on Xcode9 (iOS11) only then we'll validate for iOS version, otherwise for older versions of Xcode (iOS10 and below) we'll just execute the tweak +#ifdef __IPHONE_11_0 + if (@available(iOS 11.0, *)) {} + else +#endif + { + CGRect leftRect = CGRectNull; + CGRect rightRect = CGRectNull; + + BOOL isTitleBarButtonFound = NO; + + NSArray *subviews = [self.subviews sortedArrayUsingComparator:^NSComparisonResult(UIView *view1, UIView *view2) { + + CGFloat x1 = CGRectGetMinX(view1.frame); + CGFloat y1 = CGRectGetMinY(view1.frame); + CGFloat x2 = CGRectGetMinX(view2.frame); + CGFloat y2 = CGRectGetMinY(view2.frame); + + if (x1 < x2) return NSOrderedAscending; + + else if (x1 > x2) return NSOrderedDescending; + + //Else both y are same so checking for x positions + else if (y1 < y2) return NSOrderedAscending; + + else if (y1 > y2) return NSOrderedDescending; + + else return NSOrderedSame; + }]; + + for (UIView *barButtonItemView in subviews) + { + if (isTitleBarButtonFound == YES) + { + rightRect = barButtonItemView.frame; + break; + } + else if (barButtonItemView == self.titleBarButton.customView) + { + isTitleBarButtonFound = YES; + } + //If it's UIToolbarButton or UIToolbarTextButton (which actually UIBarButtonItem) + else if ([barButtonItemView isKindOfClass:[UIControl class]]) + { + leftRect = barButtonItemView.frame; + } + } + + CGFloat titleMargin = 16; + + CGFloat maxWidth = CGRectGetWidth(self.frame) - titleMargin*2 - (CGRectIsNull(leftRect)?0:CGRectGetMaxX(leftRect)) - (CGRectIsNull(rightRect)?0:CGRectGetWidth(self.frame)-CGRectGetMinX(rightRect)); + CGFloat maxHeight = self.frame.size.height; + + CGSize sizeThatFits = [self.titleBarButton.customView sizeThatFits:CGSizeMake(maxWidth, maxHeight)]; + + CGRect titleRect = CGRectZero; + + CGFloat x = titleMargin; + + if (sizeThatFits.width > 0 && sizeThatFits.height > 0) + { + CGFloat width = MIN(sizeThatFits.width, maxWidth); + CGFloat height = MIN(sizeThatFits.height, maxHeight); + + if (CGRectIsNull(leftRect) == false) + { + x = titleMargin + CGRectGetMaxX(leftRect) + ((maxWidth - width)/2); + } + + CGFloat y = (maxHeight - height)/2; + + titleRect = CGRectMake(x, y, width, height); + } + else + { + if (CGRectIsNull(leftRect) == false) + { + x = titleMargin + CGRectGetMaxX(leftRect); + } + + CGFloat width = CGRectGetWidth(self.frame) - titleMargin*2 - (CGRectIsNull(leftRect)?0:CGRectGetMaxX(leftRect)) - (CGRectIsNull(rightRect)?0:CGRectGetWidth(self.frame)-CGRectGetMinX(rightRect)); + + titleRect = CGRectMake(x, 0, width, maxHeight); + } + + self.titleBarButton.customView.frame = titleRect; + } +} + +#pragma mark - UIInputViewAudioFeedback delegate +- (BOOL) enableInputClicksWhenVisible +{ + return YES; +} + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQUIView+IQKeyboardToolbar.h b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQUIView+IQKeyboardToolbar.h new file mode 100644 index 0000000..eb1dc42 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQUIView+IQKeyboardToolbar.h @@ -0,0 +1,150 @@ +// +// IQUIView+IQKeyboardToolbar.h +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQToolbar.h" + +#import +#import + +@interface IQBarButtonItemConfiguration : NSObject + +-(instancetype)initWithBarButtonSystemItem:(UIBarButtonSystemItem)barButtonSystemItem action:(nullable SEL)action; +-(instancetype)initWithImage:(nonnull UIImage*)image action:(nullable SEL)action; +-(instancetype)initWithTitle:(nonnull NSString*)title action:(nullable SEL)action; + +@property (readonly, nonatomic) UIBarButtonSystemItem barButtonSystemItem; //System Item to be used to instantiate bar button +@property (readonly, nonatomic, nullable) UIImage *image; //Image to show on bar button item if it's not a system item. +@property (readonly, nonatomic, nullable) NSString *title; //Title to show on bar button item if it's not a system item. +@property (readonly, nonatomic, nullable) SEL action; //action for bar button item. Usually 'doneAction:(IQBarButtonItem*)item'. + +@end + +@interface UIImage (IQKeyboardToolbarNextPreviousImage) + ++(UIImage*)keyboardPreviousiOS9Image; ++(UIImage*)keyboardNextiOS9Image; ++(UIImage*)keyboardPreviousiOS10Image; ++(UIImage*)keyboardNextiOS10Image; + ++(UIImage*)keyboardPreviousImage; ++(UIImage*)keyboardNextImage; + +@end + +/** + UIView category methods to add IQToolbar on UIKeyboard. + */ +@interface UIView (IQToolbarAddition) + +///------------------------- +/// @name Toolbar Title +///------------------------- + +/** + IQToolbar references for better customization control. + */ +@property (readonly, nonatomic, nonnull) IQToolbar *keyboardToolbar; + +/** + If `shouldHideToolbarPlaceholder` is YES, then title will not be added to the toolbar. Default to NO. + */ +@property (assign, nonatomic) BOOL shouldHideToolbarPlaceholder; +@property (assign, nonatomic) BOOL shouldHidePlaceholderText __attribute__((deprecated("This is renamed to `shouldHideToolbarPlaceholder` for more clear naming."))); + +/** + `toolbarPlaceholder` to override default `placeholder` text when drawing text on toolbar. + */ +@property (nullable, strong, nonatomic) NSString* toolbarPlaceholder; +@property (nullable, strong, nonatomic) NSString* placeholderText __attribute__((deprecated("This is renamed to `toolbarPlaceholder` for more clear naming."))); + +/** + `drawingToolbarPlaceholder` will be actual text used to draw on toolbar. This would either `placeholder` or `toolbarPlaceholder`. + */ +@property (nullable, strong, nonatomic, readonly) NSString* drawingToolbarPlaceholder; +@property (nullable, strong, nonatomic, readonly) NSString* drawingPlaceholderText __attribute__((deprecated("This is renamed to `drawingToolbarPlaceholder` for more clear naming."))); + +///------------- +/// MARK: Common +///------------- + +- (void)addKeyboardToolbarWithTarget:(nullable id)target titleText:(nullable NSString*)titleText rightBarButtonConfiguration:(nullable IQBarButtonItemConfiguration*)rightBarButtonConfiguration previousBarButtonConfiguration:(nullable IQBarButtonItemConfiguration*)previousBarButtonConfiguration nextBarButtonConfiguration:(nullable IQBarButtonItemConfiguration*)nextBarButtonConfiguration; + +///------------ +/// @name Done +///------------ + +- (void)addDoneOnKeyboardWithTarget:(nullable id)target action:(nullable SEL)action; +- (void)addDoneOnKeyboardWithTarget:(nullable id)target action:(nullable SEL)action shouldShowPlaceholder:(BOOL)shouldShowPlaceholder; +- (void)addDoneOnKeyboardWithTarget:(nullable id)target action:(nullable SEL)action titleText:(nullable NSString*)titleText; + +///------------ +/// @name Right +///------------ + +- (void)addRightButtonOnKeyboardWithText:(nullable NSString*)text target:(nullable id)target action:(nullable SEL)action; +- (void)addRightButtonOnKeyboardWithText:(nullable NSString*)text target:(nullable id)target action:(nullable SEL)action shouldShowPlaceholder:(BOOL)shouldShowPlaceholder; +- (void)addRightButtonOnKeyboardWithText:(nullable NSString*)text target:(nullable id)target action:(nullable SEL)action titleText:(nullable NSString*)titleText; + +- (void)addRightButtonOnKeyboardWithImage:(nullable UIImage*)image target:(nullable id)target action:(nullable SEL)action; +- (void)addRightButtonOnKeyboardWithImage:(nullable UIImage*)image target:(nullable id)target action:(nullable SEL)action shouldShowPlaceholder:(BOOL)shouldShowPlaceholder; +- (void)addRightButtonOnKeyboardWithImage:(nullable UIImage*)image target:(nullable id)target action:(nullable SEL)action titleText:(nullable NSString*)titleText; + +///------------------ +/// @name Cancel/Done +///------------------ + +- (void)addCancelDoneOnKeyboardWithTarget:(nullable id)target cancelAction:(nullable SEL)cancelAction doneAction:(nullable SEL)doneAction; +- (void)addCancelDoneOnKeyboardWithTarget:(nullable id)target cancelAction:(nullable SEL)cancelAction doneAction:(nullable SEL)doneAction shouldShowPlaceholder:(BOOL)shouldShowPlaceholder; +- (void)addCancelDoneOnKeyboardWithTarget:(nullable id)target cancelAction:(nullable SEL)cancelAction doneAction:(nullable SEL)doneAction titleText:(nullable NSString*)titleText; + +///----------------- +/// @name Right/Left +///----------------- + +- (void)addLeftRightOnKeyboardWithTarget:(nullable id)target leftButtonTitle:(nullable NSString*)leftButtonTitle rightButtonTitle:(nullable NSString*)rightButtonTitle leftButtonAction:(nullable SEL)leftButtonAction rightButtonAction:(nullable SEL)rightButtonAction; +- (void)addLeftRightOnKeyboardWithTarget:(nullable id)target leftButtonTitle:(nullable NSString*)leftButtonTitle rightButtonTitle:(nullable NSString*)rightButtonTitle leftButtonAction:(nullable SEL)leftButtonAction rightButtonAction:(nullable SEL)rightButtonAction shouldShowPlaceholder:(BOOL)shouldShowPlaceholder; +- (void)addLeftRightOnKeyboardWithTarget:(nullable id)target leftButtonTitle:(nullable NSString*)leftButtonTitle rightButtonTitle:(nullable NSString*)rightButtonTitle leftButtonAction:(nullable SEL)leftButtonAction rightButtonAction:(nullable SEL)rightButtonAction titleText:(nullable NSString*)titleText; + +///------------------------- +/// @name Previous/Next/Done +///------------------------- + +- (void)addPreviousNextDoneOnKeyboardWithTarget:(nullable id)target previousAction:(nullable SEL)previousAction nextAction:(nullable SEL)nextAction doneAction:(nullable SEL)doneAction; +- (void)addPreviousNextDoneOnKeyboardWithTarget:(nullable id)target previousAction:(nullable SEL)previousAction nextAction:(nullable SEL)nextAction doneAction:(nullable SEL)doneAction shouldShowPlaceholder:(BOOL)shouldShowPlaceholder; +- (void)addPreviousNextDoneOnKeyboardWithTarget:(nullable id)target previousAction:(nullable SEL)previousAction nextAction:(nullable SEL)nextAction doneAction:(nullable SEL)doneAction titleText:(nullable NSString*)titleText; + +///-------------------------- +/// @name Previous/Next/Right +///-------------------------- + +- (void)addPreviousNextRightOnKeyboardWithTarget:(nullable id)target rightButtonTitle:(nullable NSString*)rightButtonTitle previousAction:(nullable SEL)previousAction nextAction:(nullable SEL)nextAction rightButtonAction:(nullable SEL)rightButtonAction; +- (void)addPreviousNextRightOnKeyboardWithTarget:(nullable id)target rightButtonTitle:(nullable NSString*)rightButtonTitle previousAction:(nullable SEL)previousAction nextAction:(nullable SEL)nextAction rightButtonAction:(nullable SEL)rightButtonAction shouldShowPlaceholder:(BOOL)shouldShowPlaceholder; +- (void)addPreviousNextRightOnKeyboardWithTarget:(nullable id)target rightButtonTitle:(nullable NSString*)rightButtonTitle previousAction:(nullable SEL)previousAction nextAction:(nullable SEL)nextAction rightButtonAction:(nullable SEL)rightButtonAction titleText:(nullable NSString*)titleText; + +- (void)addPreviousNextRightOnKeyboardWithTarget:(nullable id)target rightButtonImage:(nullable UIImage*)rightButtonImage previousAction:(nullable SEL)previousAction nextAction:(nullable SEL)nextAction rightButtonAction:(nullable SEL)rightButtonAction; +- (void)addPreviousNextRightOnKeyboardWithTarget:(nullable id)target rightButtonImage:(nullable UIImage*)rightButtonImage previousAction:(nullable SEL)previousAction nextAction:(nullable SEL)nextAction rightButtonAction:(nullable SEL)rightButtonAction shouldShowPlaceholder:(BOOL)shouldShowPlaceholder; +- (void)addPreviousNextRightOnKeyboardWithTarget:(nullable id)target rightButtonImage:(nullable UIImage*)rightButtonImage previousAction:(nullable SEL)previousAction nextAction:(nullable SEL)nextAction rightButtonAction:(nullable SEL)rightButtonAction titleText:(nullable NSString*)titleText; + +@end + + diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQUIView+IQKeyboardToolbar.m b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQUIView+IQKeyboardToolbar.m new file mode 100644 index 0000000..ace13a7 --- /dev/null +++ b/Pods/IQKeyboardManager/IQKeyboardManager/IQToolbar/IQUIView+IQKeyboardToolbar.m @@ -0,0 +1,676 @@ +// +// IQUIView+IQKeyboardToolbar.m +// https://github.com/hackiftekhar/IQKeyboardManager +// Copyright (c) 2013-16 Iftekhar Qurashi. +// +// 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 "IQUIView+IQKeyboardToolbar.h" +#import "IQKeyboardManagerConstantsInternal.h" +#import "IQKeyboardManager.h" + +#import + +#import +#import +#import + +@implementation IQBarButtonItemConfiguration + +-(instancetype)initWithBarButtonSystemItem:(UIBarButtonSystemItem)barButtonSystemItem action:(SEL)action +{ + self = [super init]; + if (self) { + _barButtonSystemItem = barButtonSystemItem; + _action = action; + } + return self; +} + +-(instancetype)initWithImage:(UIImage *)image action:(SEL)action +{ + self = [super init]; + if (self) { + _image = image; + _action = action; + } + return self; +} + +-(instancetype)initWithTitle:(NSString *)title action:(SEL)action +{ + self = [super init]; + if (self) { + _title = title; + _action = action; + } + return self; +} + +@end + +@implementation UIImage (IQKeyboardToolbarNextPreviousImage) + ++(UIImage*)keyboardPreviousiOS9Image +{ + static UIImage *keyboardPreviousiOS9Image = nil; + + if (keyboardPreviousiOS9Image == nil) + { + // Get the top level "bundle" which may actually be the framework + NSBundle *mainBundle = [NSBundle bundleForClass:[IQKeyboardManager class]]; + + // Check to see if the resource bundle exists inside the top level bundle + NSBundle *resourcesBundle = [NSBundle bundleWithPath:[mainBundle pathForResource:@"IQKeyboardManager" ofType:@"bundle"]]; + + if (resourcesBundle == nil) { + resourcesBundle = mainBundle; + } + + keyboardPreviousiOS9Image = [UIImage imageNamed:@"IQButtonBarArrowLeft" inBundle:resourcesBundle compatibleWithTraitCollection:nil];; + + //Support for RTL languages like Arabic, Persia etc... (Bug ID: #448) +#ifdef __IPHONE_11_0 + if (@available(iOS 9.0, *)) { +#endif + if ([UIImage instancesRespondToSelector:@selector(imageFlippedForRightToLeftLayoutDirection)]) + { + keyboardPreviousiOS9Image = [keyboardPreviousiOS9Image imageFlippedForRightToLeftLayoutDirection]; + } +#ifdef __IPHONE_11_0 + } +#endif + } + + return keyboardPreviousiOS9Image; +} + ++(UIImage*)keyboardNextiOS9Image +{ + static UIImage *keyboardNextiOS9Image = nil; + + if (keyboardNextiOS9Image == nil) + { + // Get the top level "bundle" which may actually be the framework + NSBundle *mainBundle = [NSBundle bundleForClass:[IQKeyboardManager class]]; + + // Check to see if the resource bundle exists inside the top level bundle + NSBundle *resourcesBundle = [NSBundle bundleWithPath:[mainBundle pathForResource:@"IQKeyboardManager" ofType:@"bundle"]]; + + if (resourcesBundle == nil) { + resourcesBundle = mainBundle; + } + + keyboardNextiOS9Image = [UIImage imageNamed:@"IQButtonBarArrowRight" inBundle:resourcesBundle compatibleWithTraitCollection:nil]; + + //Support for RTL languages like Arabic, Persia etc... (Bug ID: #448) +#ifdef __IPHONE_11_0 + if (@available(iOS 9.0, *)) { +#endif + if ([UIImage instancesRespondToSelector:@selector(imageFlippedForRightToLeftLayoutDirection)]) + { + keyboardNextiOS9Image = [keyboardNextiOS9Image imageFlippedForRightToLeftLayoutDirection]; + } +#ifdef __IPHONE_11_0 + } +#endif + } + + return keyboardNextiOS9Image; +} + ++(UIImage*)keyboardPreviousiOS10Image +{ + static UIImage *keyboardPreviousiOS10Image = nil; + + if (keyboardPreviousiOS10Image == nil) + { + // Get the top level "bundle" which may actually be the framework + NSBundle *mainBundle = [NSBundle bundleForClass:[IQKeyboardManager class]]; + + // Check to see if the resource bundle exists inside the top level bundle + NSBundle *resourcesBundle = [NSBundle bundleWithPath:[mainBundle pathForResource:@"IQKeyboardManager" ofType:@"bundle"]]; + + if (resourcesBundle == nil) { + resourcesBundle = mainBundle; + } + + keyboardPreviousiOS10Image = [UIImage imageNamed:@"IQButtonBarArrowUp" inBundle:resourcesBundle compatibleWithTraitCollection:nil]; + + //Support for RTL languages like Arabic, Persia etc... (Bug ID: #448) +#ifdef __IPHONE_11_0 + if (@available(iOS 9.0, *)) { +#endif + if ([UIImage instancesRespondToSelector:@selector(imageFlippedForRightToLeftLayoutDirection)]) + { + keyboardPreviousiOS10Image = [keyboardPreviousiOS10Image imageFlippedForRightToLeftLayoutDirection]; + } +#ifdef __IPHONE_11_0 + } +#endif + } + + return keyboardPreviousiOS10Image; +} + ++(UIImage*)keyboardNextiOS10Image +{ + static UIImage *keyboardNextiOS10Image = nil; + + if (keyboardNextiOS10Image == nil) + { + // Get the top level "bundle" which may actually be the framework + NSBundle *mainBundle = [NSBundle bundleForClass:[IQKeyboardManager class]]; + + // Check to see if the resource bundle exists inside the top level bundle + NSBundle *resourcesBundle = [NSBundle bundleWithPath:[mainBundle pathForResource:@"IQKeyboardManager" ofType:@"bundle"]]; + + if (resourcesBundle == nil) { + resourcesBundle = mainBundle; + } + + keyboardNextiOS10Image = [UIImage imageNamed:@"IQButtonBarArrowDown" inBundle:resourcesBundle compatibleWithTraitCollection:nil]; + + //Support for RTL languages like Arabic, Persia etc... (Bug ID: #448) +#ifdef __IPHONE_11_0 + if (@available(iOS 9.0, *)) { +#endif + if ([UIImage instancesRespondToSelector:@selector(imageFlippedForRightToLeftLayoutDirection)]) + { + keyboardNextiOS10Image = [keyboardNextiOS10Image imageFlippedForRightToLeftLayoutDirection]; + } +#ifdef __IPHONE_11_0 + } +#endif + } + + return keyboardNextiOS10Image; +} + ++(UIImage*)keyboardPreviousImage +{ +#ifdef __IPHONE_11_0 + if (@available(iOS 10.0, *)) +#else + if (IQ_IS_IOS10_OR_GREATER) +#endif + { + return [UIImage keyboardPreviousiOS10Image]; + } + else + { + return [UIImage keyboardPreviousiOS9Image]; + } +} + ++(UIImage*)keyboardNextImage +{ +#ifdef __IPHONE_11_0 + if (@available(iOS 10.0, *)) +#else + if (IQ_IS_IOS10_OR_GREATER) +#endif + { + return [UIImage keyboardNextiOS9Image]; + } + else + { + return [UIImage keyboardPreviousiOS9Image]; + } +} + +@end + + +/*UIKeyboardToolbar Category implementation*/ +@implementation UIView (IQToolbarAddition) + +-(IQToolbar *)keyboardToolbar +{ + IQToolbar *keyboardToolbar = nil; + if ([[self inputAccessoryView] isKindOfClass:[IQToolbar class]]) + { + keyboardToolbar = [self inputAccessoryView]; + } + else + { + keyboardToolbar = objc_getAssociatedObject(self, @selector(keyboardToolbar)); + + if (keyboardToolbar == nil) + { + keyboardToolbar = [[IQToolbar alloc] init]; + + objc_setAssociatedObject(self, @selector(keyboardToolbar), keyboardToolbar, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + } + + return keyboardToolbar; +} + +-(void)setShouldHideToolbarPlaceholder:(BOOL)shouldHideToolbarPlaceholder +{ + objc_setAssociatedObject(self, @selector(shouldHideToolbarPlaceholder), @(shouldHideToolbarPlaceholder), OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + self.keyboardToolbar.titleBarButton.title = self.drawingToolbarPlaceholder; +} + +-(BOOL)shouldHideToolbarPlaceholder +{ + NSNumber *shouldHideToolbarPlaceholder = objc_getAssociatedObject(self, @selector(shouldHideToolbarPlaceholder)); + return [shouldHideToolbarPlaceholder boolValue]; +} + +-(void)setShouldHidePlaceholderText:(BOOL)shouldHidePlaceholderText +{ + [self setShouldHideToolbarPlaceholder:shouldHidePlaceholderText]; +} + +-(BOOL)shouldHidePlaceholderText +{ + return [self shouldHideToolbarPlaceholder]; +} + +-(void)setToolbarPlaceholder:(NSString *)toolbarPlaceholder +{ + objc_setAssociatedObject(self, @selector(toolbarPlaceholder), toolbarPlaceholder, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + self.keyboardToolbar.titleBarButton.title = self.drawingToolbarPlaceholder; +} + +-(NSString *)toolbarPlaceholder +{ + NSString *toolbarPlaceholder = objc_getAssociatedObject(self, @selector(toolbarPlaceholder)); + return toolbarPlaceholder; +} + +-(void)setPlaceholderText:(NSString*)placeholderText +{ + [self setToolbarPlaceholder:placeholderText]; +} + +-(NSString*)placeholderText +{ + return [self toolbarPlaceholder]; +} + +-(NSString *)drawingToolbarPlaceholder +{ + if (self.shouldHideToolbarPlaceholder) + { + return nil; + } + else if (self.toolbarPlaceholder.length != 0) + { + return self.toolbarPlaceholder; + } + else if ([self respondsToSelector:@selector(placeholder)]) + { + return [(UITextField*)self placeholder]; + } + else + { + return nil; + } +} + +-(NSString*)drawingPlaceholderText +{ + return [self drawingToolbarPlaceholder]; +} + +#pragma mark - Private helper + ++(IQBarButtonItem*)flexibleBarButtonItem +{ + static IQBarButtonItem *nilButton = nil; + + if (nilButton == nil) + { + nilButton = [[IQBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; + } + + return nilButton; +} + +#pragma mark - Common + +- (void)addKeyboardToolbarWithTarget:(id)target titleText:(NSString*)titleText rightBarButtonConfiguration:(IQBarButtonItemConfiguration*)rightBarButtonConfiguration previousBarButtonConfiguration:(IQBarButtonItemConfiguration*)previousBarButtonConfiguration nextBarButtonConfiguration:(IQBarButtonItemConfiguration*)nextBarButtonConfiguration +{ + //If can't set InputAccessoryView. Then return + if (![self respondsToSelector:@selector(setInputAccessoryView:)]) return; + + // Creating a toolBar for phoneNumber keyboard + IQToolbar *toolbar = self.keyboardToolbar; + + NSMutableArray *items = [[NSMutableArray alloc] init]; + + if(previousBarButtonConfiguration) + { + IQBarButtonItem *prev = toolbar.previousBarButton; + + if (prev.isSystemItem == NO && (previousBarButtonConfiguration.image || previousBarButtonConfiguration.title)) + { + prev.title = previousBarButtonConfiguration.title; + prev.image = previousBarButtonConfiguration.image; + prev.target = target; + prev.action = previousBarButtonConfiguration.action; + } + else if (previousBarButtonConfiguration.image) + { + prev = [[IQBarButtonItem alloc] initWithImage:previousBarButtonConfiguration.image style:UIBarButtonItemStylePlain target:target action:previousBarButtonConfiguration.action]; + prev.invocation = toolbar.previousBarButton.invocation; + prev.accessibilityLabel = toolbar.previousBarButton.accessibilityLabel; + toolbar.previousBarButton = prev; + } + else if (previousBarButtonConfiguration.title) + { + prev = [[IQBarButtonItem alloc] initWithTitle:previousBarButtonConfiguration.title style:UIBarButtonItemStylePlain target:target action:previousBarButtonConfiguration.action]; + prev.invocation = toolbar.previousBarButton.invocation; + prev.accessibilityLabel = toolbar.previousBarButton.accessibilityLabel; + toolbar.previousBarButton = prev; + } + else + { + prev = [[IQBarButtonItem alloc] initWithBarButtonSystemItem:previousBarButtonConfiguration.barButtonSystemItem target:target action:previousBarButtonConfiguration.action]; + prev.invocation = toolbar.previousBarButton.invocation; + prev.accessibilityLabel = toolbar.previousBarButton.accessibilityLabel; + toolbar.previousBarButton = prev; + } + + [items addObject:prev]; + } + + if (previousBarButtonConfiguration != nil && nextBarButtonConfiguration != nil) + { + [items addObject:toolbar.fixedSpaceBarButton]; + } + + if(nextBarButtonConfiguration) + { + IQBarButtonItem *next = toolbar.nextBarButton; + + if (next.isSystemItem == NO && (nextBarButtonConfiguration.image || nextBarButtonConfiguration.title)) + { + next.title = nextBarButtonConfiguration.title; + next.image = nextBarButtonConfiguration.image; + next.target = target; + next.action = nextBarButtonConfiguration.action; + } + else if (nextBarButtonConfiguration.image) + { + next = [[IQBarButtonItem alloc] initWithImage:nextBarButtonConfiguration.image style:UIBarButtonItemStylePlain target:target action:nextBarButtonConfiguration.action]; + next.invocation = toolbar.nextBarButton.invocation; + next.accessibilityLabel = toolbar.nextBarButton.accessibilityLabel; + toolbar.nextBarButton = next; + } + else if (nextBarButtonConfiguration.title) + { + next = [[IQBarButtonItem alloc] initWithTitle:nextBarButtonConfiguration.title style:UIBarButtonItemStylePlain target:target action:nextBarButtonConfiguration.action]; + next.invocation = toolbar.nextBarButton.invocation; + next.accessibilityLabel = toolbar.nextBarButton.accessibilityLabel; + toolbar.nextBarButton = next; + } + else + { + next = [[IQBarButtonItem alloc] initWithBarButtonSystemItem:nextBarButtonConfiguration.barButtonSystemItem target:target action:nextBarButtonConfiguration.action]; + next.invocation = toolbar.nextBarButton.invocation; + next.accessibilityLabel = toolbar.nextBarButton.accessibilityLabel; + toolbar.nextBarButton = next; + } + + [items addObject:next]; + } + + //Title + { + //Flexible space + [items addObject:[[self class] flexibleBarButtonItem]]; + + //Title button + toolbar.titleBarButton.title = titleText; +#ifdef __IPHONE_11_0 + if (@available(iOS 11.0, *)) {} + else +#endif + { + toolbar.titleBarButton.customView.frame = CGRectZero; + } + [items addObject:toolbar.titleBarButton]; + + //Flexible space + [items addObject:[[self class] flexibleBarButtonItem]]; + } + + if(rightBarButtonConfiguration) + { + IQBarButtonItem *done = toolbar.doneBarButton; + + if (done.isSystemItem == NO && (rightBarButtonConfiguration.image || rightBarButtonConfiguration.title)) + { + done.title = rightBarButtonConfiguration.title; + done.image = rightBarButtonConfiguration.image; + done.target = target; + done.action = rightBarButtonConfiguration.action; + } + else if (rightBarButtonConfiguration.image) + { + done = [[IQBarButtonItem alloc] initWithImage:rightBarButtonConfiguration.image style:UIBarButtonItemStylePlain target:target action:rightBarButtonConfiguration.action]; + done.invocation = toolbar.doneBarButton.invocation; + done.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel; + toolbar.doneBarButton = done; + } + else if (rightBarButtonConfiguration.title) + { + done = [[IQBarButtonItem alloc] initWithTitle:rightBarButtonConfiguration.title style:UIBarButtonItemStylePlain target:target action:rightBarButtonConfiguration.action]; + done.invocation = toolbar.doneBarButton.invocation; + done.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel; + toolbar.doneBarButton = done; + } + else + { + done = [[IQBarButtonItem alloc] initWithBarButtonSystemItem:rightBarButtonConfiguration.barButtonSystemItem target:target action:rightBarButtonConfiguration.action]; + done.invocation = toolbar.doneBarButton.invocation; + done.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel; + toolbar.doneBarButton = done; + } + + [items addObject:done]; + } + + // Adding button to toolBar. + [toolbar setItems:items]; + + // Setting toolbar to keyboard. + [(UITextField*)self setInputAccessoryView:toolbar]; + + + if ([self respondsToSelector:@selector(keyboardAppearance)]) + { + switch ([(UITextField*)self keyboardAppearance]) + { + case UIKeyboardAppearanceDark: toolbar.barStyle = UIBarStyleBlack; break; + default: toolbar.barStyle = UIBarStyleDefault; break; + } + } +} + +#pragma mark - Right + +- (void)addRightButtonOnKeyboardWithText:(NSString*)text target:(id)target action:(SEL)action +{ + [self addRightButtonOnKeyboardWithText:text target:target action:action titleText:nil]; +} + +- (void)addRightButtonOnKeyboardWithText:(NSString*)text target:(id)target action:(SEL)action shouldShowPlaceholder:(BOOL)shouldShowPlaceholder +{ + [self addRightButtonOnKeyboardWithText:text target:target action:action titleText:(shouldShowPlaceholder?[self drawingToolbarPlaceholder]:nil)]; +} + +- (void)addRightButtonOnKeyboardWithText:(NSString*)text target:(id)target action:(SEL)action titleText:(NSString*)titleText +{ + IQBarButtonItemConfiguration *rightConfiguration = [[IQBarButtonItemConfiguration alloc] initWithTitle:text action:action]; + + [self addKeyboardToolbarWithTarget:target titleText:titleText rightBarButtonConfiguration:rightConfiguration previousBarButtonConfiguration:nil nextBarButtonConfiguration:nil]; +} + + +- (void)addRightButtonOnKeyboardWithImage:(UIImage*)image target:(id)target action:(SEL)action +{ + [self addRightButtonOnKeyboardWithImage:image target:target action:action titleText:nil]; +} + +- (void)addRightButtonOnKeyboardWithImage:(UIImage*)image target:(id)target action:(SEL)action shouldShowPlaceholder:(BOOL)shouldShowPlaceholder +{ + [self addRightButtonOnKeyboardWithImage:image target:target action:action titleText:(shouldShowPlaceholder?[self drawingToolbarPlaceholder]:nil)]; +} + +- (void)addRightButtonOnKeyboardWithImage:(UIImage*)image target:(id)target action:(SEL)action titleText:(NSString*)titleText +{ + IQBarButtonItemConfiguration *rightConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:image action:action]; + + [self addKeyboardToolbarWithTarget:target titleText:titleText rightBarButtonConfiguration:rightConfiguration previousBarButtonConfiguration:nil nextBarButtonConfiguration:nil]; +} + + +-(void)addDoneOnKeyboardWithTarget:(id)target action:(SEL)action +{ + [self addDoneOnKeyboardWithTarget:target action:action titleText:nil]; +} + +-(void)addDoneOnKeyboardWithTarget:(id)target action:(SEL)action shouldShowPlaceholder:(BOOL)shouldShowPlaceholder +{ + [self addDoneOnKeyboardWithTarget:target action:action titleText:(shouldShowPlaceholder?[self drawingToolbarPlaceholder]:nil)]; +} + +- (void)addDoneOnKeyboardWithTarget:(id)target action:(SEL)action titleText:(NSString*)titleText +{ + IQBarButtonItemConfiguration *rightConfiguration = [[IQBarButtonItemConfiguration alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone action:action]; + + [self addKeyboardToolbarWithTarget:target titleText:titleText rightBarButtonConfiguration:rightConfiguration previousBarButtonConfiguration:nil nextBarButtonConfiguration:nil]; +} + + +- (void)addLeftRightOnKeyboardWithTarget:(id)target leftButtonTitle:(NSString*)leftTitle rightButtonTitle:(NSString*)rightTitle leftButtonAction:(SEL)leftAction rightButtonAction:(SEL)rightAction +{ + [self addLeftRightOnKeyboardWithTarget:target leftButtonTitle:leftTitle rightButtonTitle:rightTitle leftButtonAction:leftAction rightButtonAction:rightAction titleText:nil]; +} + +- (void)addLeftRightOnKeyboardWithTarget:(id)target leftButtonTitle:(NSString*)leftTitle rightButtonTitle:(NSString*)rightTitle leftButtonAction:(SEL)leftAction rightButtonAction:(SEL)rightAction shouldShowPlaceholder:(BOOL)shouldShowPlaceholder +{ + [self addLeftRightOnKeyboardWithTarget:target leftButtonTitle:leftTitle rightButtonTitle:rightTitle leftButtonAction:leftAction rightButtonAction:rightAction titleText:(shouldShowPlaceholder?[self drawingToolbarPlaceholder]:nil)]; +} + +- (void)addLeftRightOnKeyboardWithTarget:(id)target leftButtonTitle:(NSString*)leftTitle rightButtonTitle:(NSString*)rightTitle leftButtonAction:(SEL)leftAction rightButtonAction:(SEL)rightAction titleText:(NSString*)titleText +{ + IQBarButtonItemConfiguration *leftConfiguration = [[IQBarButtonItemConfiguration alloc] initWithTitle:leftTitle action:leftAction]; + + IQBarButtonItemConfiguration *rightConfiguration = [[IQBarButtonItemConfiguration alloc] initWithTitle:rightTitle action:rightAction]; + + [self addKeyboardToolbarWithTarget:target titleText:titleText rightBarButtonConfiguration:rightConfiguration previousBarButtonConfiguration:leftConfiguration nextBarButtonConfiguration:nil]; +} + + +-(void)addCancelDoneOnKeyboardWithTarget:(id)target cancelAction:(SEL)cancelAction doneAction:(SEL)doneAction +{ + [self addCancelDoneOnKeyboardWithTarget:target cancelAction:cancelAction doneAction:doneAction titleText:nil]; +} + +-(void)addCancelDoneOnKeyboardWithTarget:(id)target cancelAction:(SEL)cancelAction doneAction:(SEL)doneAction shouldShowPlaceholder:(BOOL)shouldShowPlaceholder +{ + [self addCancelDoneOnKeyboardWithTarget:target cancelAction:cancelAction doneAction:doneAction titleText:(shouldShowPlaceholder?[self drawingToolbarPlaceholder]:nil)]; +} + +- (void)addCancelDoneOnKeyboardWithTarget:(id)target cancelAction:(SEL)cancelAction doneAction:(SEL)doneAction titleText:(NSString*)titleText +{ + IQBarButtonItemConfiguration *leftConfiguration = [[IQBarButtonItemConfiguration alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel action:cancelAction]; + + IQBarButtonItemConfiguration *rightConfiguration = [[IQBarButtonItemConfiguration alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone action:doneAction]; + + [self addKeyboardToolbarWithTarget:target titleText:titleText rightBarButtonConfiguration:rightConfiguration previousBarButtonConfiguration:leftConfiguration nextBarButtonConfiguration:nil]; +} + + +-(void)addPreviousNextDoneOnKeyboardWithTarget:(id)target previousAction:(SEL)previousAction nextAction:(SEL)nextAction doneAction:(SEL)doneAction +{ + [self addPreviousNextDoneOnKeyboardWithTarget:target previousAction:previousAction nextAction:nextAction doneAction:doneAction titleText:nil]; +} + +-(void)addPreviousNextDoneOnKeyboardWithTarget:(id)target previousAction:(SEL)previousAction nextAction:(SEL)nextAction doneAction:(SEL)doneAction shouldShowPlaceholder:(BOOL)shouldShowPlaceholder +{ + [self addPreviousNextDoneOnKeyboardWithTarget:target previousAction:previousAction nextAction:nextAction doneAction:doneAction titleText:(shouldShowPlaceholder?[self drawingToolbarPlaceholder]:nil)]; +} + +- (void)addPreviousNextDoneOnKeyboardWithTarget:(id)target previousAction:(SEL)previousAction nextAction:(SEL)nextAction doneAction:(SEL)doneAction titleText:(NSString*)titleText +{ + IQBarButtonItemConfiguration *previousConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:[UIImage keyboardPreviousImage] action:previousAction]; + + IQBarButtonItemConfiguration *nextConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:[UIImage keyboardNextImage] action:nextAction]; + + IQBarButtonItemConfiguration *rightConfiguration = [[IQBarButtonItemConfiguration alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone action:doneAction]; + + [self addKeyboardToolbarWithTarget:target titleText:titleText rightBarButtonConfiguration:rightConfiguration previousBarButtonConfiguration:previousConfiguration nextBarButtonConfiguration:nextConfiguration]; +} + + +- (void)addPreviousNextRightOnKeyboardWithTarget:(nullable id)target rightButtonImage:(nullable UIImage*)rightButtonImage previousAction:(nullable SEL)previousAction nextAction:(nullable SEL)nextAction rightButtonAction:(nullable SEL)rightButtonAction +{ + [self addPreviousNextRightOnKeyboardWithTarget:target rightButtonImage:rightButtonImage previousAction:previousAction nextAction:nextAction rightButtonAction:rightButtonAction titleText:nil]; +} + +- (void)addPreviousNextRightOnKeyboardWithTarget:(nullable id)target rightButtonImage:(nullable UIImage*)rightButtonImage previousAction:(nullable SEL)previousAction nextAction:(nullable SEL)nextAction rightButtonAction:(nullable SEL)rightButtonAction shouldShowPlaceholder:(BOOL)shouldShowPlaceholder +{ + [self addPreviousNextRightOnKeyboardWithTarget:target rightButtonImage:rightButtonImage previousAction:previousAction nextAction:nextAction rightButtonAction:rightButtonAction titleText:(shouldShowPlaceholder?[self drawingToolbarPlaceholder]:nil)]; +} + +- (void)addPreviousNextRightOnKeyboardWithTarget:(id)target rightButtonImage:(UIImage*)rightButtonImage previousAction:(SEL)previousAction nextAction:(SEL)nextAction rightButtonAction:(SEL)rightButtonAction titleText:(NSString*)titleText +{ + IQBarButtonItemConfiguration *previousConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:[UIImage keyboardPreviousImage] action:previousAction]; + + IQBarButtonItemConfiguration *nextConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:[UIImage keyboardNextImage] action:nextAction]; + + IQBarButtonItemConfiguration *rightConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:rightButtonImage action:rightButtonAction]; + + [self addKeyboardToolbarWithTarget:target titleText:titleText rightBarButtonConfiguration:rightConfiguration previousBarButtonConfiguration:previousConfiguration nextBarButtonConfiguration:nextConfiguration]; +} + + +- (void)addPreviousNextRightOnKeyboardWithTarget:(id)target rightButtonTitle:(NSString*)rightButtonTitle previousAction:(SEL)previousAction nextAction:(SEL)nextAction rightButtonAction:(SEL)rightButtonAction +{ + [self addPreviousNextRightOnKeyboardWithTarget:target rightButtonTitle:rightButtonTitle previousAction:previousAction nextAction:nextAction rightButtonAction:rightButtonAction titleText:nil]; +} + +- (void)addPreviousNextRightOnKeyboardWithTarget:(id)target rightButtonTitle:(NSString*)rightButtonTitle previousAction:(SEL)previousAction nextAction:(SEL)nextAction rightButtonAction:(SEL)rightButtonAction shouldShowPlaceholder:(BOOL)shouldShowPlaceholder +{ + [self addPreviousNextRightOnKeyboardWithTarget:target rightButtonTitle:rightButtonTitle previousAction:previousAction nextAction:nextAction rightButtonAction:rightButtonAction titleText:(shouldShowPlaceholder?[self drawingToolbarPlaceholder]:nil)]; +} + +- (void)addPreviousNextRightOnKeyboardWithTarget:(id)target rightButtonTitle:(NSString*)rightButtonTitle previousAction:(SEL)previousAction nextAction:(SEL)nextAction rightButtonAction:(SEL)rightButtonAction titleText:(NSString*)titleText +{ + IQBarButtonItemConfiguration *previousConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:[UIImage keyboardPreviousImage] action:previousAction]; + + IQBarButtonItemConfiguration *nextConfiguration = [[IQBarButtonItemConfiguration alloc] initWithImage:[UIImage keyboardNextImage] action:nextAction]; + + IQBarButtonItemConfiguration *rightConfiguration = [[IQBarButtonItemConfiguration alloc] initWithTitle:rightButtonTitle action:rightButtonAction]; + + [self addKeyboardToolbarWithTarget:target titleText:titleText rightBarButtonConfiguration:rightConfiguration previousBarButtonConfiguration:previousConfiguration nextBarButtonConfiguration:nextConfiguration]; +} + + +@end diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowDown@2x.png b/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowDown@2x.png new file mode 100644 index 0000000..81db2ed Binary files /dev/null and b/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowDown@2x.png differ diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowDown@3x.png b/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowDown@3x.png new file mode 100644 index 0000000..dd34122 Binary files /dev/null and b/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowDown@3x.png differ diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowLeft@2x.png b/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowLeft@2x.png new file mode 100644 index 0000000..cfc40d6 Binary files /dev/null and b/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowLeft@2x.png differ diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowLeft@3x.png b/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowLeft@3x.png new file mode 100644 index 0000000..849b991 Binary files /dev/null and b/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowLeft@3x.png differ diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowRight@2x.png b/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowRight@2x.png new file mode 100644 index 0000000..c8b9a87 Binary files /dev/null and b/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowRight@2x.png differ diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowRight@3x.png b/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowRight@3x.png new file mode 100644 index 0000000..95c4397 Binary files /dev/null and b/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowRight@3x.png differ diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowUp@2x.png b/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowUp@2x.png new file mode 100644 index 0000000..8ec96a9 Binary files /dev/null and b/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowUp@2x.png differ diff --git a/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowUp@3x.png b/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowUp@3x.png new file mode 100644 index 0000000..9304f50 Binary files /dev/null and b/Pods/IQKeyboardManager/IQKeyboardManager/Resources/IQKeyboardManager.bundle/IQButtonBarArrowUp@3x.png differ diff --git a/Pods/IQKeyboardManager/LICENSE.md b/Pods/IQKeyboardManager/LICENSE.md new file mode 100644 index 0000000..c17c107 --- /dev/null +++ b/Pods/IQKeyboardManager/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013-2017 Iftekhar Qurashi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Pods/IQKeyboardManager/README.md b/Pods/IQKeyboardManager/README.md new file mode 100644 index 0000000..b3900c0 --- /dev/null +++ b/Pods/IQKeyboardManager/README.md @@ -0,0 +1,210 @@ +

+ Icon +

+

IQKeyboardManager

+

+ GitHub license + + +[![Build Status](https://travis-ci.org/hackiftekhar/IQKeyboardManager.svg)](https://travis-ci.org/hackiftekhar/IQKeyboardManager) + + +Often while developing an app, We ran into an issues where the iPhone keyboard slide up and cover the `UITextField/UITextView`. `IQKeyboardManager` allows you to prevent issues of the keyboard sliding up and cover `UITextField/UITextView` without needing you to enter any code and no additional setup required. To use `IQKeyboardManager` you simply need to add source files to your project. + + +#### Key Features + +1) `**CODELESS**, Zero Lines Of Code` + +2) `Works Automatically` + +3) `No More UIScrollView` + +4) `No More Subclasses` + +5) `No More Manual Work` + +6) `No More #imports` + +`IQKeyboardManager` works on all orientations, and with the toolbar. There are also nice optional features allowing you to customize the distance from the text field, add the next/previous done button as a keyboard UIToolbar, play sounds when the user navigations through the form and more. + + +## Screenshot +[![IQKeyboardManager](https://raw.githubusercontent.com/hackiftekhar/IQKeyboardManager/v3.3.0/Screenshot/IQKeyboardManagerScreenshot.png)](http://youtu.be/6nhLw6hju2A) +[![Settings](https://raw.githubusercontent.com/hackiftekhar/IQKeyboardManager/v3.3.0/Screenshot/IQKeyboardManagerSettings.png)](http://youtu.be/6nhLw6hju2A) + +## GIF animation +[![IQKeyboardManager](https://raw.githubusercontent.com/hackiftekhar/IQKeyboardManager/v3.3.0/Screenshot/IQKeyboardManager.gif)](http://youtu.be/6nhLw6hju2A) + +## Video + + + +## Tutorial video by @rebeloper ([#1135](https://github.com/hackiftekhar/IQKeyboardManager/issues/1135)) + +@rebeloper demonstrated two videos on how to implement **IQKeyboardManager** at it's core: + + + +https://www.youtube.com/playlist?list=PL_csAAO9PQ8aTL87XnueOXi3RpWE2m_8v + +## Warning + +- **If you're planning to build SDK/library/framework and wants to handle UITextField/UITextView with IQKeyboardManager then you're totally going on wrong way.** I would never suggest to add **IQKeyboardManager** as **dependency/adding/shipping** with any third-party library, instead of adding **IQKeyboardManager** you should implement your own solution to achieve same kind of results. **IQKeyboardManager** is totally designed for projects to help developers for their convenience, it's not designed for **adding/dependency/shipping** with any **third-party library**, because **doing this could block adoption by other developers for their projects as well(who are not using IQKeyboardManager and implemented their custom solution to handle UITextField/UITextView thought the project).** +- If **IQKeyboardManager** conflicts with other **third-party library**, then it's **developer responsibility** to **enable/disable IQKeyboardManager** when **presenting/dismissing** third-party library UI. Third-party libraries are not responsible to handle IQKeyboardManager. + +## Requirements +[![Platform iOS](https://img.shields.io/badge/Platform-iOS-blue.svg?style=fla)]() + +| | Language | Minimum iOS Target | Minimum Xcode Version | +|------------------------|----------|--------------------|-----------------------| +| IQKeyboardManager | Obj-C | iOS 8.0 | Xcode 8.2.1 | +| IQKeyboardManagerSwift | Swift | iOS 8.0 | Xcode 8.2.1 | +| Demo Project | | | Xcode 9.3 | + +**Note** +- 3.3.7 is the last iOS 7 supported version. + +#### Swift versions support + +| Swift | Xcode | IQKeyboardManagerSwift | +|-------------------|-------|------------------------| +| 4.2, 4.0, 3.2, 3.0| 10.0 | >= 6.0.4 | +| 4.0, 3.2, 3.0 | 9.0 | 5.0.0 | +| 3.1 | 8.3 | 4.0.10 | +| 3.0 (3.0.2) | 8.2 | 4.0.8 | +| 2.2 or 2.3 | 7.3 | 4.0.5 | +| 2.1.1 | 7.2 | 4.0.0 | +| 2.1 | 7.2 | 3.3.7 | +| 2.0 | 7.0 | 3.3.3.1 | +| 1.2 | 6.3 | 3.3.1 | +| 1.0 | 6.0 | 3.3.2 | + +Installation +========================== + +#### Installation with CocoaPods + +[![CocoaPods](https://img.shields.io/cocoapods/v/IQKeyboardManager.svg)](http://cocoadocs.org/docsets/IQKeyboardManager) + +***IQKeyboardManager (Objective-C):*** IQKeyboardManager is available through [CocoaPods](http://cocoapods.org), to install +it simply add the following line to your Podfile: ([#9](https://github.com/hackiftekhar/IQKeyboardManager/issues/9)) + +```ruby +pod 'IQKeyboardManager' #iOS8 and later + +pod 'IQKeyboardManager', '3.3.7' #iOS7 +``` + +***IQKeyboardManager (Swift):*** IQKeyboardManagerSwift is available through [CocoaPods](http://cocoapods.org), to install +it simply add the following line to your Podfile: ([#236](https://github.com/hackiftekhar/IQKeyboardManager/issues/236)) + +*Swift 4.2, 4.0, 3.2, 3.0 (Xcode 9)* + +```ruby +pod 'IQKeyboardManagerSwift' +``` + +*Or you can choose version you need based on Swift support table from [Requirements](README.md#requirements)* + +```ruby +pod 'IQKeyboardManagerSwift', '5.0.0' +``` + +In AppDelegate.swift, just import IQKeyboardManagerSwift framework and enable IQKeyboardManager. + +```swift +import IQKeyboardManagerSwift + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { + + IQKeyboardManager.shared.enable = true + + return true + } +} +``` + +#### Installation with Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](http://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate `IQKeyboardManger` or `IQKeyboardManagerSwift` into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "hackiftekhar/IQKeyboardManager" +``` + +Run `carthage` to build the frameworks and drag the appropriate framework (`IQKeyboardManager.framework` or `IQKeyboardManagerSwift.framework`) into your Xcode project according to your need. Make sure to add only one framework and not both. + + +#### Installation with Source Code + +[![Github tag](https://img.shields.io/github/tag/hackiftekhar/iqkeyboardmanager.svg)]() + + + +***IQKeyboardManager (Objective-C):*** Just ***drag and drop*** `IQKeyboardManager` directory from demo project to your project. That's it. + +***IQKeyboardManager (Swift):*** ***Drag and drop*** `IQKeyboardManagerSwift` directory from demo project to your project + +In AppDelegate.swift, just enable IQKeyboardManager. + +```swift +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { + + IQKeyboardManager.shared.enable = true + + return true + } +} +``` + +Migration Guide +========================== +- [IQKeyboardManager 6.0.0 Migration Guide](https://github.com/hackiftekhar/IQKeyboardManager/wiki/IQKeyboardManager-6.0.0-Migration-Guide) + +Other Links +========================== + +- [Known Issues](https://github.com/hackiftekhar/IQKeyboardManager/wiki/Known-Issues) +- [Manual Management Tweaks](https://github.com/hackiftekhar/IQKeyboardManager/wiki/Manual-Management) +- [Properties and functions usage](https://github.com/hackiftekhar/IQKeyboardManager/wiki/Properties-&-Functions) + +## Flow Diagram +[![IQKeyboardManager CFD](https://raw.githubusercontent.com/hackiftekhar/IQKeyboardManager/master/Screenshot/IQKeyboardManagerFlowDiagram.jpg)](https://raw.githubusercontent.com/hackiftekhar/IQKeyboardManager/master/Screenshot/IQKeyboardManagerFlowDiagram.jpg) + +If you would like to see detailed Flow diagram then see [Detailed Flow Diagram](https://raw.githubusercontent.com/hackiftekhar/IQKeyboardManager/v3.3.0/Screenshot/IQKeyboardManagerCFD.jpg). + + +LICENSE +--- +Distributed under the MIT License. + +Contributions +--- +Any contribution is more than welcome! You can contribute through pull requests and issues on GitHub. + +Author +--- +If you wish to contact me, email at: hack.iftekhar@gmail.com diff --git a/Pods/JCore/libjcore-ios-1.2.2.a b/Pods/JCore/libjcore-ios-1.2.2.a new file mode 100755 index 0000000..e70d1de Binary files /dev/null and b/Pods/JCore/libjcore-ios-1.2.2.a differ diff --git a/Pods/JPush/JPUSHService.h b/Pods/JPush/JPUSHService.h new file mode 100755 index 0000000..6ca5411 --- /dev/null +++ b/Pods/JPush/JPUSHService.h @@ -0,0 +1,611 @@ +/* + * | | | | \ \ / / | | | | / _______| + * | |____| | \ \/ / | |____| | / / + * | |____| | \ / | |____| | | | _____ + * | | | | / \ | | | | | | |____ | + * | | | | / /\ \ | | | | \ \______| | + * | | | | /_/ \_\ | | | | \_________| + * + * Copyright (c) 2011 ~ 2017 Shenzhen HXHG. All rights reserved. + */ + +#define JPUSH_VERSION_NUMBER 3.1.0 + +#import + +@class CLRegion; +@class UILocalNotification; +@class CLLocation; +@class UNNotificationCategory; +@class UNNotificationSettings; +@class UNNotificationRequest; +@class UNNotification; +@protocol JPUSHRegisterDelegate; + +typedef void (^JPUSHTagsOperationCompletion)(NSInteger iResCode, NSSet *iTags, NSInteger seq); +typedef void (^JPUSHTagValidOperationCompletion)(NSInteger iResCode, NSSet *iTags, NSInteger seq, BOOL isBind); +typedef void (^JPUSHAliasOperationCompletion)(NSInteger iResCode, NSString *iAlias, NSInteger seq); + +extern NSString *const kJPFNetworkIsConnectingNotification; // 正在连接中 +extern NSString *const kJPFNetworkDidSetupNotification; // 建立连接 +extern NSString *const kJPFNetworkDidCloseNotification; // 关闭连接 +extern NSString *const kJPFNetworkDidRegisterNotification; // 注册成功 +extern NSString *const kJPFNetworkFailedRegisterNotification; //注册失败 +extern NSString *const kJPFNetworkDidLoginNotification; // 登录成功 +extern NSString *const kJPFNetworkDidReceiveMessageNotification; // 收到消息(非APNS) +extern NSString *const kJPFServiceErrorNotification; // 错误提示 + +typedef NS_OPTIONS(NSUInteger, JPAuthorizationOptions) { + JPAuthorizationOptionNone = 0, // the application may not present any UI upon a notification being received + JPAuthorizationOptionBadge = (1 << 0), // the application may badge its icon upon a notification being received + JPAuthorizationOptionSound = (1 << 1), // the application may play a sound upon a notification being received + JPAuthorizationOptionAlert = (1 << 2), // the application may display an alert upon a notification being received +}; + +/*! + * 通知注册实体类 + */ +@interface JPUSHRegisterEntity : NSObject + +/*! + * 支持的类型 + * badge,sound,alert + */ +@property (nonatomic, assign) NSInteger types; +/*! + * 注入的类别 + * iOS10 UNNotificationCategory + * iOS8-iOS9 UIUserNotificationCategory + */ +@property (nonatomic, strong) NSSet *categories; +@end + +/*! + * 进行删除、查找推送实体类 + */ +@interface JPushNotificationIdentifier : NSObject + +@property (nonatomic, copy) NSArray *identifiers; // 推送的标识数组 +@property (nonatomic, copy) UILocalNotification *notificationObj NS_DEPRECATED_IOS(4_0, 10_0); // iOS10以下可以传UILocalNotification对象数据,iOS10以上无效 +@property (nonatomic, assign) BOOL delivered NS_AVAILABLE_IOS(10_0); // 在通知中心显示的或待推送的标志,默认为NO,YES表示在通知中心显示的,NO表示待推送的 +@property (nonatomic, copy) void (^findCompletionHandler)(NSArray *results); // 用于查询回调,调用[findNotification:]方法前必须设置,results为返回相应对象数组,iOS10以下返回UILocalNotification对象数组;iOS10以上根据delivered传入值返回UNNotification或UNNotificationRequest对象数组(delivered传入YES,则返回UNNotification对象数组,否则返回UNNotificationRequest对象数组) + +@end + +/*! + * 推送内容实体类 + */ +@interface JPushNotificationContent : NSObject + +@property (nonatomic, copy) NSString *title; // 推送标题 +@property (nonatomic, copy) NSString *subtitle; // 推送副标题 +@property (nonatomic, copy) NSString *body; // 推送内容 +@property (nonatomic, copy) NSNumber *badge; // 角标的数字。如果不需要改变角标传@(-1) +@property (nonatomic, copy) NSString *action NS_DEPRECATED_IOS(8_0, 10_0); // 弹框的按钮显示的内容(IOS 8默认为"打开", 其他默认为"启动",iOS10以上无效) +@property (nonatomic, copy) NSString *categoryIdentifier; // 行为分类标识 +@property (nonatomic, copy) NSDictionary *userInfo; // 本地推送时可以设置userInfo来增加附加信息,远程推送时设置的payload推送内容作为此userInfo +@property (nonatomic, copy) NSString *sound; // 声音名称,不设置则为默认声音 +@property (nonatomic, copy) NSArray *attachments NS_AVAILABLE_IOS(10_0); // 附件,iOS10以上有效,需要传入UNNotificationAttachment对象数组类型 +@property (nonatomic, copy) NSString *threadIdentifier NS_AVAILABLE_IOS(10_0); // 线程或与推送请求相关对话的标识,iOS10以上有效,可用来对推送进行分组 +@property (nonatomic, copy) NSString *launchImageName NS_AVAILABLE_IOS(10_0); // 启动图片名,iOS10以上有效,从推送启动时将会用到 + +@end + +/*! + * 推送触发方式实体类 + * 注:dateComponents、timeInterval、region在iOS10以上可选择其中一个参数传入有效值,如果同时传入值会根据优先级I、II、III使其中一种触发方式生效,fireDate为iOS10以下根据时间触发时须传入的参数 + */ +@interface JPushNotificationTrigger : NSObject + +@property (nonatomic, assign) BOOL repeat; // 设置是否重复,默认为NO +@property (nonatomic, copy) NSDate *fireDate NS_DEPRECATED_IOS(2_0, 10_0); // 用来设置触发推送的时间,iOS10以上无效 +@property (nonatomic, copy) CLRegion *region NS_AVAILABLE_IOS(8_0); // 用来设置触发推送的位置,iOS8以上有效,iOS10以上优先级为I,应用需要有允许使用定位的授权 +@property (nonatomic, copy) NSDateComponents *dateComponents NS_AVAILABLE_IOS(10_0); // 用来设置触发推送的日期时间,iOS10以上有效,优先级为II +@property (nonatomic, assign) NSTimeInterval timeInterval NS_AVAILABLE_IOS(10_0); // 用来设置触发推送的时间,iOS10以上有效,优先级为III + +@end + +/*! + * 注册或更新推送实体类 + */ +@interface JPushNotificationRequest : NSObject + +@property (nonatomic, copy) NSString *requestIdentifier; // 推送请求标识 +@property (nonatomic, copy) JPushNotificationContent *content; // 设置推送的具体内容 +@property (nonatomic, copy) JPushNotificationTrigger *trigger; // 设置推送的触发方式 +@property (nonatomic, copy) void (^completionHandler)(id result); // 注册或更新推送成功回调,iOS10以上成功则result为UNNotificationRequest对象,失败则result为nil;iOS10以下成功result为UILocalNotification对象,失败则result为nil + +@end + +/*! + * JPush 核心头文件 + */ +@interface JPUSHService : NSObject + + +///---------------------------------------------------- +/// @name Setup 启动相关 +///---------------------------------------------------- + +/*! + * @abstract 启动SDK + * + * @discussion 这是旧版本的启动方法, 依赖于 PushConfig.plist 文件. 建议不要使用, 已经过期. + */ ++ (void)setupWithOption:(NSDictionary *)launchingOption __attribute__((deprecated("JPush 2.1.0 版本已过期"))); + +/*! + * @abstract 启动SDK + * + * @param launchingOption 启动参数. + * @param appKey 一个JPush 应用必须的,唯一的标识. 请参考 JPush 相关说明文档来获取这个标识. + * @param channel 发布渠道. 可选. + * @param isProduction 是否生产环境. 如果为开发状态,设置为 NO; 如果为生产状态,应改为 YES. + * App 证书环境取决于profile provision的配置,此处建议与证书环境保持一致. + * @param advertisingIdentifier 广告标识符(IDFA) 如果不需要使用IDFA,传nil. + * + * @discussion 提供SDK启动必须的参数, 来启动 SDK. + * 此接口必须在 App 启动时调用, 否则 JPush SDK 将无法正常工作. + */ ++ (void)setupWithOption:(NSDictionary *)launchingOption + appKey:(NSString *)appKey + channel:(NSString *)channel + apsForProduction:(BOOL)isProduction; + + ++ (void)setupWithOption:(NSDictionary *)launchingOption + appKey:(NSString *)appKey + channel:(NSString *)channel + apsForProduction:(BOOL)isProduction + advertisingIdentifier:(NSString *)advertisingId; + + +///---------------------------------------------------- +/// @name APNs about 通知相关 +///---------------------------------------------------- + +/*! + * @abstract 注册要处理的远程通知类型 + * + * @param types 通知类型 + * @param categories 类别组 + * + */ ++ (void)registerForRemoteNotificationTypes:(NSUInteger)types + categories:(NSSet *)categories; +/*! + * @abstract 新版本的注册方法(兼容iOS10) + * + * @param config 注册通知配置 + * @param delegate 代理 + * + */ ++ (void)registerForRemoteNotificationConfig:(JPUSHRegisterEntity *)config delegate:(id)delegate; + + ++ (void)registerDeviceToken:(NSData *)deviceToken; + + +/*! + * @abstract 处理收到的 APNs 消息 + */ ++ (void)handleRemoteNotification:(NSDictionary *)remoteInfo; + +/*! + * Tags操作接口 + * 支持增加/覆盖/删除/清空/查询操作 + * 详情请参考文档:https://docs.jiguang.cn/jpush/client/iOS/ios_api/) + */ + +/** + 增加tags + + @param tags 需要增加的tags集合 + @param completion 响应回调 + @param seq 请求序列号 + */ ++ (void)addTags:(NSSet *)tags + completion:(JPUSHTagsOperationCompletion)completion + seq:(NSInteger)seq; + +/** + 覆盖tags + 调用该接口会覆盖用户所有的tags + + @param tags 需要设置的tags集合 + @param completion 响应回调 + @param seq 请求序列号 + */ ++ (void)setTags:(NSSet *)tags + completion:(JPUSHTagsOperationCompletion)completion + seq:(NSInteger)seq; + +/** + 删除指定tags + + @param tags 需要删除的tags集合 + @param completion 响应回调 + @param seq 请求序列号 + */ ++ (void)deleteTags:(NSSet *)tags + completion:(JPUSHTagsOperationCompletion)completion + seq:(NSInteger)seq; + +/** + 清空所有tags + @param completion 响应回调 + @param seq 请求序列号 + */ ++ (void)cleanTags:(JPUSHTagsOperationCompletion)completion + seq:(NSInteger)seq; + +/** + 查询全部tags + + @param completion 响应回调,请在回调中获取查询结果 + @param seq 请求序列号 + */ ++ (void)getAllTags:(JPUSHTagsOperationCompletion)completion + seq:(NSInteger)seq; + +/** + 验证tag是否绑定 + + @param completion 响应回调,回调中查看是否绑定 + @param seq 请求序列号 + */ ++ (void)validTag:(NSString *)tag + completion:(JPUSHTagValidOperationCompletion)completion + seq:(NSInteger)seq; + +/** + 设置Alias + + @param alias 需要设置的alias + @param completion 响应回调 + @param seq 请求序列号 + */ ++ (void)setAlias:(NSString *)alias + completion:(JPUSHAliasOperationCompletion)completion + seq:(NSInteger)seq; + +/** + 删除alias + + @param completion 响应回调 + @param seq 请求序列号 + */ ++ (void)deleteAlias:(JPUSHAliasOperationCompletion)completion + seq:(NSInteger)seq; + +/** + 查询当前alias + + @param completion 响应回调 + @param seq 请求序列号 + */ ++ (void)getAlias:(JPUSHAliasOperationCompletion)completion + seq:(NSInteger)seq; + + +/*! + * @abstract 过滤掉无效的 tags + * + * @discussion 如果 tags 数量超过限制数量, 则返回靠前的有效的 tags. + * 建议设置 tags 前用此接口校验. SDK 内部也会基于此接口来做过滤. + */ ++ (NSSet *)filterValidTags:(NSSet *)tags; + +///---------------------------------------------------- +/// @name Stats 统计功能 +///---------------------------------------------------- + +/*! + * @abstract 开始记录页面停留 + * + * @param pageName 页面名称 + * @discussion JCore 1.1.8 版本后,如需统计页面流,请使用 JAnalytics + */ ++ (void)startLogPageView:(NSString *)pageName __attribute__((deprecated("JCore 1.1.8 版本已过期"))); + +/*! + * @abstract 停止记录页面停留 + * + * @param pageName 页面 + * @discussion JCore 1.1.8 版本后,如需统计页面流,请使用 JAnalytics + */ ++ (void)stopLogPageView:(NSString *)pageName __attribute__((deprecated("JCore 1.1.8 版本已过期"))); + +/*! + * @abstract 直接上报在页面的停留时间 + * + * @param pageName 页面 + * @param seconds 停留的秒数 + * @discussion JCore 1.1.8 版本后,如需统计页面流,请使用 JAnalytics + */ ++ (void)beginLogPageView:(NSString *)pageName duration:(int)seconds __attribute__((deprecated("JCore 1.1.8 版本已过期"))); + +/*! + * @abstract 开启Crash日志收集 + * + * @discussion 默认是关闭状态. + */ ++ (void)crashLogON; + +/*! + * @abstract 地理位置上报 + * + * @param latitude 纬度. + * @param longitude 经度. + * + */ ++ (void)setLatitude:(double)latitude longitude:(double)longitude; + +/*! + * @abstract 地理位置上报 + * + * @param location 直接传递 CLLocation * 型的地理信息 + * + * @discussion 需要链接 CoreLocation.framework 并且 #import + */ ++ (void)setLocation:(CLLocation *)location; + + +///---------------------------------------------------- +/// @name Local Notification 本地通知 +///---------------------------------------------------- +/*! + * @abstract 注册或更新推送 (支持iOS10,并兼容iOS10以下版本) + * + * JPush 2.1.9新接口 + * @param request JPushNotificationRequest类型,设置推送的属性,设置已有推送的request.requestIdentifier即更新已有的推送,否则为注册新推送,更新推送仅仅在iOS10以上有效,结果通过request.completionHandler返回 + * @discussion 旧的注册本地推送接口被废弃,使用此接口可以替换 + * + */ ++ (void)addNotification:(JPushNotificationRequest *)request; + +/*! + * @abstract 移除推送 (支持iOS10,并兼容iOS10以下版本) + * + * JPush 2.1.9新接口 + * @param identifier JPushNotificationIdentifier类型,iOS10以上identifier设置为nil,则移除所有在通知中心显示推送和待推送请求,也可以通过设置identifier.delivered和identifier.identifiers来移除相应在通知中心显示推送或待推送请求,identifier.identifiers如果设置为nil或空数组则移除相应标志下所有在通知中心显示推送或待推送请求;iOS10以下identifier设置为nil,则移除所有推送,identifier.delivered属性无效,另外可以通过identifier.notificationObj传入特定推送对象来移除此推送。 + * @discussion 旧的所有删除推送接口被废弃,使用此接口可以替换 + * + */ ++ (void)removeNotification:(JPushNotificationIdentifier *)identifier; + +/*! + * @abstract 查找推送 (支持iOS10,并兼容iOS10以下版本) + * + * JPush 2.1.9新接口 + * @param identifier JPushNotificationIdentifier类型,iOS10以上可以通过设置identifier.delivered和identifier.identifiers来查找相应在通知中心显示推送或待推送请求,identifier.identifiers如果设置为nil或空数组则返回相应标志下所有在通知中心显示推送或待推送请求;iOS10以下identifier.delivered属性无效,identifier.identifiers如果设置nil或空数组则返回所有未触发的推送。须要设置identifier.findCompletionHandler回调才能得到查找结果,通过(NSArray *results)返回相应对象数组。 + * @discussion 旧的查找推送接口被废弃,使用此接口可以替换 + * + */ ++ (void)findNotification:(JPushNotificationIdentifier *)identifier; + +/*! + * @abstract 本地推送,最多支持64个 + * + * @param fireDate 本地推送触发的时间 + * @param alertBody 本地推送需要显示的内容 + * @param badge 角标的数字。如果不需要改变角标传-1 + * @param alertAction 弹框的按钮显示的内容(IOS 8默认为"打开", 其他默认为"启动") + * @param notificationKey 本地推送标示符 + * @param userInfo 自定义参数,可以用来标识推送和增加附加信息 + * @param soundName 自定义通知声音,设置为nil为默认声音 + * + * @discussion 最多支持 64 个定义,此方法被[addNotification:]方法取代 + */ ++ (UILocalNotification *)setLocalNotification:(NSDate *)fireDate + alertBody:(NSString *)alertBody + badge:(int)badge + alertAction:(NSString *)alertAction + identifierKey:(NSString *)notificationKey + userInfo:(NSDictionary *)userInfo + soundName:(NSString *)soundName __attribute__((deprecated("JPush 2.1.9 版本已过期"))); + +/*! + * @abstract 本地推送 (支持 iOS8 新参数) + * + * IOS8新参数 + * @param region 自定义参数 + * @param regionTriggersOnce 自定义参数 + * @param category 自定义参数 + * @discussion 此方法被[addNotification:]方法取代 + */ ++ (UILocalNotification *)setLocalNotification:(NSDate *)fireDate + alertBody:(NSString *)alertBody + badge:(int)badge + alertAction:(NSString *)alertAction + identifierKey:(NSString *)notificationKey + userInfo:(NSDictionary *)userInfo + soundName:(NSString *)soundName + region:(CLRegion *)region + regionTriggersOnce:(BOOL)regionTriggersOnce + category:(NSString *)category NS_AVAILABLE_IOS(8_0) __attribute__((deprecated("JPush 2.1.9 版本已过期"))); + +/*! + * @abstract 前台展示本地推送 + * + * @param notification 本地推送对象 + * @param notificationKey 需要前台显示的本地推送通知的标示符 + * + * @discussion 默认App在前台运行时不会进行弹窗,在程序接收通知调用此接口可实现指定的推送弹窗。--iOS10以下还可继续使用,iOS10以上在[UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:]方法中调用completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);即可 + */ ++ (void)showLocalNotificationAtFront:(UILocalNotification *)notification + identifierKey:(NSString *)notificationKey __attribute__((deprecated("JPush 2.1.9 版本已过期"))); +/*! + * @abstract 删除本地推送定义 + * + * @param notificationKey 本地推送标示符 + * @discussion 此方法被[removeNotification:]方法取代 + */ ++ (void)deleteLocalNotificationWithIdentifierKey:(NSString *)notificationKey __attribute__((deprecated("JPush 2.1.9 版本已过期"))); + +/*! + * @abstract 删除本地推送定义 + * @discussion 此方法被[removeNotification:]方法取代 + */ ++ (void)deleteLocalNotification:(UILocalNotification *)localNotification __attribute__((deprecated("JPush 2.1.9 版本已过期"))); + +/*! + * @abstract 获取指定通知 + * + * @param notificationKey 本地推送标示符 + * @return 本地推送对象数组, [array count]为0时表示没找到 + * @discussion 此方法被[findNotification:]方法取代 + */ ++ (NSArray *)findLocalNotificationWithIdentifier:(NSString *)notificationKey __attribute__((deprecated("JPush 2.1.9 版本已过期"))); + +/*! + * @abstract 清除所有本地推送对象 + * @discussion 此方法被[removeNotification:]方法取代 + */ ++ (void)clearAllLocalNotifications __attribute__((deprecated("JPush 2.1.9 版本已过期"))); + + +///---------------------------------------------------- +/// @name Server badge 服务器端 badge 功能 +///---------------------------------------------------- + +/*! + * @abstract 设置角标(到服务器) + * + * @param value 新的值. 会覆盖服务器上保存的值(这个用户) + * + * @discussion 本接口不会改变应用本地的角标值. + * 本地仍须调用 UIApplication:setApplicationIconBadgeNumber 函数来设置脚标. + * + * 本接口用于配合 JPush 提供的服务器端角标功能. + * 该功能解决的问题是, 服务器端推送 APNs 时, 并不知道客户端原来已经存在的角标是多少, 指定一个固定的数字不太合理. + * + * JPush 服务器端脚标功能提供: + * + * - 通过本 API 把当前客户端(当前这个用户的) 的实际 badge 设置到服务器端保存起来; + * - 调用服务器端 API 发 APNs 时(通常这个调用是批量针对大量用户), + * 使用 "+1" 的语义, 来表达需要基于目标用户实际的 badge 值(保存的) +1 来下发通知时带上新的 badge 值; + */ ++ (BOOL)setBadge:(NSInteger)value; + +/*! + * @abstract 重置脚标(为0) + * + * @discussion 相当于 [setBadge:0] 的效果. + * 参考 [JPUSHService setBadge:] 说明来理解其作用. + */ ++ (void)resetBadge; + +///---------------------------------------------------- +/// @name Other Feature 其他功能 +///---------------------------------------------------- + +/*! + * @abstract 设置手机号码(到服务器) + * + * @param mobileNumber 手机号码. 会与用户信息一一对应。可为空,为空则清除号码 + * @param completion 响应回调。成功则error为空,失败则error带有错误码及错误信息 + * + * @discussion 设置手机号码后,可实现“推送不到短信到”的通知方式,提高推送达到率。结果信息通过completion异步返回,也可将completion设置为nil不处理结果信息。 + * + */ ++ (void)setMobileNumber:(NSString *)mobileNumber completion:(void (^)(NSError *error))completion; + +///---------------------------------------------------- +/// @name Logs and others 日志与其他 +///---------------------------------------------------- + +/*! + * @abstract JPush标识此设备的 registrationID + * + * @discussion SDK注册成功后, 调用此接口获取到 registrationID 才能够获取到. + * + * JPush 支持根据 registrationID 来进行推送. + * 如果你需要此功能, 应该通过此接口获取到 registrationID 后, 上报到你自己的服务器端, 并保存下来. + * registrationIDCompletionHandler:是新增的获取registrationID的方法,需要在block中获取registrationID,resCode为返回码,模拟器调用此接口resCode返回1011,registrationID返回nil. + * 更多的理解请参考 JPush 的文档网站. + */ ++ (NSString *)registrationID; + ++ (void)registrationIDCompletionHandler:(void(^)(int resCode,NSString *registrationID))completionHandler; + +/*! + * @abstract 打开日志级别到 Debug + * + * @discussion JMessage iOS 的日志系统参考 Android 设计了级别. + * 从低到高是: Verbose, Debug, Info, Warning, Error. + * 对日志级别的进一步理解, 请参考 Android 相关的说明. + * + * SDK 默认开启的日志级别为: Info. 只显示必要的信息, 不打印调试日志. + * + * 请在SDK启动后调用本接口,调用本接口可打开日志级别为: Debug, 打印调试日志. + */ ++ (void)setDebugMode; + +/*! + * @abstract 关闭日志 + * + * @discussion 关于日志级别的说明, 参考 [JPUSHService setDebugMode] + * + * 虽说是关闭日志, 但还是会打印 Warning, Error 日志. 这二种日志级别, 在程序运行正常时, 不应有打印输出. + * + * 建议在发布的版本里, 调用此接口, 关闭掉日志打印. + */ ++ (void)setLogOFF; + +///---------------------------------------------------- +///********************下列方法已过期******************** +///**************请使用新版tag/alias操作接口************** +///---------------------------------------------------- +/// @name Tag alias setting 设置别名与标签 +///---------------------------------------------------- + +/*! + * 下面的接口是可选的 + * 设置标签和(或)别名(若参数为nil,则忽略;若是空对象,则清空;详情请参考文档:https://docs.jiguang.cn/jpush/client/iOS/ios_api/) + * setTags:alias:fetchCompletionHandle:是新的设置标签别名的方法,不再需要显示声明回调函数,只需要在block里面处理设置结果即可. + * WARN: 使用block时需要注意循环引用问题 + */ ++ (void) setTags:(NSSet *)tags + alias:(NSString *)alias +callbackSelector:(SEL)cbSelector + target:(id)theTarget __attribute__((deprecated("JPush 2.1.1 版本已过期"))); ++ (void) setTags:(NSSet *)tags + alias:(NSString *)alias +callbackSelector:(SEL)cbSelector + object:(id)theTarget __attribute__((deprecated("JPush 3.0.6 版本已过期"))); ++ (void) setTags:(NSSet *)tags +callbackSelector:(SEL)cbSelector + object:(id)theTarget __attribute__((deprecated("JPush 3.0.6 版本已过期"))); ++ (void)setTags:(NSSet *)tags + alias:(NSString *)alias +fetchCompletionHandle:(void (^)(int iResCode, NSSet *iTags, NSString *iAlias))completionHandler __attribute__((deprecated("JPush 3.0.6 版本已过期"))); ++ (void) setTags:(NSSet *)tags +aliasInbackground:(NSString *)alias __attribute__((deprecated("JPush 3.0.6 版本已过期"))); ++ (void)setAlias:(NSString *)alias +callbackSelector:(SEL)cbSelector + object:(id)theTarget __attribute__((deprecated("JPush 3.0.6 版本已过期"))); + +@end + +@class UNUserNotificationCenter; +@class UNNotificationResponse; + +@protocol JPUSHRegisterDelegate + +/* + * @brief handle UserNotifications.framework [willPresentNotification:withCompletionHandler:] + * @param center [UNUserNotificationCenter currentNotificationCenter] 新特性用户通知中心 + * @param notification 前台得到的的通知对象 + * @param completionHandler 该callback中的options 请使用UNNotificationPresentationOptions + */ +- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger options))completionHandler; +/* + * @brief handle UserNotifications.framework [didReceiveNotificationResponse:withCompletionHandler:] + * @param center [UNUserNotificationCenter currentNotificationCenter] 新特性用户通知中心 + * @param response 通知响应对象 + * @param completionHandler + */ +- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler; + +@end diff --git a/Pods/JPush/libjpush-ios-3.1.0.a b/Pods/JPush/libjpush-ios-3.1.0.a new file mode 100755 index 0000000..e3a90f6 Binary files /dev/null and b/Pods/JPush/libjpush-ios-3.1.0.a differ diff --git a/Pods/JSONModel/JSONModel/JSONModel/JSONModel.h b/Pods/JSONModel/JSONModel/JSONModel/JSONModel.h new file mode 100644 index 0000000..ca673bc --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModel/JSONModel.h @@ -0,0 +1,274 @@ +// +// JSONModel.h +// JSONModel +// + +#import + +#import "JSONModelError.h" +#import "JSONValueTransformer.h" +#import "JSONKeyMapper.h" + +///////////////////////////////////////////////////////////////////////////////////////////// +#if TARGET_IPHONE_SIMULATOR +#define JMLog( s, ... ) NSLog( @"[%@:%d] %@", [[NSString stringWithUTF8String:__FILE__] \ +lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] ) +#else +#define JMLog( s, ... ) +#endif +///////////////////////////////////////////////////////////////////////////////////////////// + +DEPRECATED_ATTRIBUTE +@protocol ConvertOnDemand +@end + +DEPRECATED_ATTRIBUTE +@protocol Index +@end + +#pragma mark - Property Protocols +/** + * Protocol for defining properties in a JSON Model class that should not be considered at all + * neither while importing nor when exporting JSON. + * + * @property (strong, nonatomic) NSString<Ignore> *propertyName; + * + */ +@protocol Ignore +@end + +/** + * Protocol for defining optional properties in a JSON Model class. Use like below to define + * model properties that are not required to have values in the JSON input: + * + * @property (strong, nonatomic) NSString<Optional> *propertyName; + * + */ +@protocol Optional +@end + +/** + * Make all objects compatible to avoid compiler warnings + */ +@interface NSObject (JSONModelPropertyCompatibility) +@end + +///////////////////////////////////////////////////////////////////////////////////////////// +#pragma mark - JSONModel protocol +/** + * A protocol describing an abstract JSONModel class + * JSONModel conforms to this protocol, so it can use itself abstractly + */ +@protocol AbstractJSONModelProtocol + +@required +/** + * All JSONModel classes should implement initWithDictionary: + * + * For most classes the default initWithDictionary: inherited from JSONModel itself + * should suffice, but developers have the option to also overwrite it if needed. + * + * @param dict a dictionary holding JSON objects, to be imported in the model. + * @param err an error or NULL + */ +- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err; + + +/** + * All JSONModel classes should implement initWithData:error: + * + * For most classes the default initWithData: inherited from JSONModel itself + * should suffice, but developers have the option to also overwrite it if needed. + * + * @param data representing a JSON response (usually fetched from web), to be imported in the model. + * @param error an error or NULL + */ +- (instancetype)initWithData:(NSData *)data error:(NSError **)error; + +/** + * All JSONModel classes should be able to export themselves as a dictionary of + * JSON compliant objects. + * + * For most classes the inherited from JSONModel default toDictionary implementation + * should suffice. + * + * @return NSDictionary dictionary of JSON compliant objects + * @exception JSONModelTypeNotAllowedException thrown when one of your model's custom class properties + * does not have matching transformer method in an JSONValueTransformer. + */ +- (NSDictionary *)toDictionary; + +/** + * Export a model class to a dictionary, including only given properties + * + * @param propertyNames the properties to export; if nil, all properties exported + * @return NSDictionary dictionary of JSON compliant objects + * @exception JSONModelTypeNotAllowedException thrown when one of your model's custom class properties + * does not have matching transformer method in an JSONValueTransformer. + */ +- (NSDictionary *)toDictionaryWithKeys:(NSArray *)propertyNames; +@end + +///////////////////////////////////////////////////////////////////////////////////////////// +#pragma mark - JSONModel interface +/** + * The JSONModel is an abstract model class, you should not instantiate it directly, + * as it does not have any properties, and therefore cannot serve as a data model. + * Instead you should subclass it, and define the properties you want your data model + * to have as properties of your own class. + */ +@interface JSONModel : NSObject + +// deprecated ++ (NSMutableArray *)arrayOfModelsFromDictionaries:(NSArray *)array DEPRECATED_MSG_ATTRIBUTE("use arrayOfModelsFromDictionaries:error:"); ++ (void)setGlobalKeyMapper:(JSONKeyMapper *)globalKeyMapper DEPRECATED_MSG_ATTRIBUTE("override +keyMapper in a base model class instead"); ++ (NSString *)protocolForArrayProperty:(NSString *)propertyName DEPRECATED_MSG_ATTRIBUTE("use classForCollectionProperty:"); +- (void)mergeFromDictionary:(NSDictionary *)dict useKeyMapping:(BOOL)useKeyMapping DEPRECATED_MSG_ATTRIBUTE("use mergeFromDictionary:useKeyMapping:error:"); +- (NSString *)indexPropertyName DEPRECATED_ATTRIBUTE; +- (NSComparisonResult)compare:(id)object DEPRECATED_ATTRIBUTE; + +/** @name Creating and initializing models */ + +/** + * Create a new model instance and initialize it with the JSON from a text parameter. The method assumes UTF8 encoded input text. + * @param string JSON text data + * @param err an initialization error or nil + * @exception JSONModelTypeNotAllowedException thrown when unsupported type is found in the incoming JSON, + * or a property type in your model is not supported by JSONValueTransformer and its categories + * @see initWithString:usingEncoding:error: for use of custom text encodings + */ +- (instancetype)initWithString:(NSString *)string error:(JSONModelError **)err; + +/** + * Create a new model instance and initialize it with the JSON from a text parameter using the given encoding. + * @param string JSON text data + * @param encoding the text encoding to use when parsing the string (see NSStringEncoding) + * @param err an initialization error or nil + * @exception JSONModelTypeNotAllowedException thrown when unsupported type is found in the incoming JSON, + * or a property type in your model is not supported by JSONValueTransformer and its categories + */ +- (instancetype)initWithString:(NSString *)string usingEncoding:(NSStringEncoding)encoding error:(JSONModelError **)err; + +/** @name Exporting model contents */ + +/** + * Export the whole object to a JSON data text string + * @return JSON text describing the data model + */ +- (NSString *)toJSONString; + +/** + * Export the whole object to a JSON data text string + * @return JSON text data describing the data model + */ +- (NSData *)toJSONData; + +/** + * Export the specified properties of the object to a JSON data text string + * @param propertyNames the properties to export; if nil, all properties exported + * @return JSON text describing the data model + */ +- (NSString *)toJSONStringWithKeys:(NSArray *)propertyNames; + +/** + * Export the specified properties of the object to a JSON data text string + * @param propertyNames the properties to export; if nil, all properties exported + * @return JSON text data describing the data model + */ +- (NSData *)toJSONDataWithKeys:(NSArray *)propertyNames; + +/** @name Batch methods */ + +/** + * If you have a list of dictionaries in a JSON feed, you can use this method to create an NSArray + * of model objects. Handy when importing JSON data lists. + * This method will loop over the input list and initialize a data model for every dictionary in the list. + * + * @param array list of dictionaries to be imported as models + * @return list of initialized data model objects + * @exception JSONModelTypeNotAllowedException thrown when unsupported type is found in the incoming JSON, + * or a property type in your model is not supported by JSONValueTransformer and its categories + * @exception JSONModelInvalidDataException thrown when the input data does not include all required keys + * @see arrayOfDictionariesFromModels: + */ ++ (NSMutableArray *)arrayOfModelsFromDictionaries:(NSArray *)array error:(NSError **)err; ++ (NSMutableArray *)arrayOfModelsFromData:(NSData *)data error:(NSError **)err; ++ (NSMutableArray *)arrayOfModelsFromString:(NSString *)string error:(NSError **)err; ++ (NSMutableDictionary *)dictionaryOfModelsFromDictionary:(NSDictionary *)dictionary error:(NSError **)err; ++ (NSMutableDictionary *)dictionaryOfModelsFromData:(NSData *)data error:(NSError **)err; ++ (NSMutableDictionary *)dictionaryOfModelsFromString:(NSString *)string error:(NSError **)err; + +/** + * If you have an NSArray of data model objects, this method takes it in and outputs a list of the + * matching dictionaries. This method does the opposite of arrayOfObjectsFromDictionaries: + * @param array list of JSONModel objects + * @return a list of NSDictionary objects + * @exception JSONModelTypeNotAllowedException thrown when unsupported type is found in the incoming JSON, + * or a property type in your model is not supported by JSONValueTransformer and its categories + * @see arrayOfModelsFromDictionaries: + */ ++ (NSMutableArray *)arrayOfDictionariesFromModels:(NSArray *)array; ++ (NSMutableDictionary *)dictionaryOfDictionariesFromModels:(NSDictionary *)dictionary; + +/** @name Validation */ + +/** + * Overwrite the validate method in your own models if you need to perform some custom validation over the model data. + * This method gets called at the very end of the JSONModel initializer, thus the model is in the state that you would + * get it back when initialized. Check the values of any property that needs to be validated and if any invalid values + * are encountered return NO and set the error parameter to an NSError object. If the model is valid return YES. + * + * NB: Only setting the error parameter is not enough to fail the validation, you also need to return a NO value. + * + * @param error a pointer to an NSError object, to pass back an error if needed + * @return a BOOL result, showing whether the model data validates or not. You can use the convenience method + * [JSONModelError errorModelIsInvalid] to set the NSError param if the data fails your custom validation + */ +- (BOOL)validate:(NSError **)error; + +/** @name Key mapping */ +/** + * Overwrite in your models if your property names don't match your JSON key names. + * Lookup JSONKeyMapper docs for more details. + */ ++ (JSONKeyMapper *)keyMapper; + +/** + * Indicates whether the property with the given name is Optional. + * To have a model with all of its properties being Optional just return YES. + * This method returns by default NO, since the default behaviour is to have all properties required. + * @param propertyName the name of the property + * @return a BOOL result indicating whether the property is optional + */ ++ (BOOL)propertyIsOptional:(NSString *)propertyName; + +/** + * Indicates whether the property with the given name is Ignored. + * To have a model with all of its properties being Ignored just return YES. + * This method returns by default NO, since the default behaviour is to have all properties required. + * @param propertyName the name of the property + * @return a BOOL result indicating whether the property is ignored + */ ++ (BOOL)propertyIsIgnored:(NSString *)propertyName; + +/** + * Indicates the class used for the elements of a collection property. + * Rather than using: + * @property (strong) NSArray *things; + * You can implement classForCollectionProperty: and keep your property + * defined like: + * @property (strong) NSArray *things; + * @param propertyName the name of the property + * @return Class the class used to deserialize the elements of the collection + */ ++ (Class)classForCollectionProperty:(NSString *)propertyName; + +/** + * Merges values from the given dictionary into the model instance. + * @param dict dictionary with values + * @param useKeyMapping if YES the method will use the model's key mapper and the global key mapper, if NO + * it'll just try to match the dictionary keys to the model's properties + */ +- (BOOL)mergeFromDictionary:(NSDictionary *)dict useKeyMapping:(BOOL)useKeyMapping error:(NSError **)error; + +@end diff --git a/Pods/JSONModel/JSONModel/JSONModel/JSONModel.m b/Pods/JSONModel/JSONModel/JSONModel/JSONModel.m new file mode 100644 index 0000000..7cbafbd --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModel/JSONModel.m @@ -0,0 +1,1401 @@ +// +// JSONModel.m +// JSONModel +// + +#if !__has_feature(objc_arc) +#error The JSONMOdel framework is ARC only, you can enable ARC on per file basis. +#endif + + +#import +#import + + +#import "JSONModel.h" +#import "JSONModelClassProperty.h" + +#pragma mark - associated objects names +static const char * kMapperObjectKey; +static const char * kClassPropertiesKey; +static const char * kClassRequiredPropertyNamesKey; +static const char * kIndexPropertyNameKey; + +#pragma mark - class static variables +static NSArray* allowedJSONTypes = nil; +static NSArray* allowedPrimitiveTypes = nil; +static JSONValueTransformer* valueTransformer = nil; +static Class JSONModelClass = NULL; + +#pragma mark - model cache +static JSONKeyMapper* globalKeyMapper = nil; + +#pragma mark - JSONModel implementation +@implementation JSONModel +{ + NSString* _description; +} + +#pragma mark - initialization methods + ++(void)load +{ + static dispatch_once_t once; + dispatch_once(&once, ^{ + // initialize all class static objects, + // which are common for ALL JSONModel subclasses + + @autoreleasepool { + allowedJSONTypes = @[ + [NSString class], [NSNumber class], [NSDecimalNumber class], [NSArray class], [NSDictionary class], [NSNull class], //immutable JSON classes + [NSMutableString class], [NSMutableArray class], [NSMutableDictionary class] //mutable JSON classes + ]; + + allowedPrimitiveTypes = @[ + @"BOOL", @"float", @"int", @"long", @"double", @"short", + //and some famous aliases + @"NSInteger", @"NSUInteger", + @"Block" + ]; + + valueTransformer = [[JSONValueTransformer alloc] init]; + + // This is quite strange, but I found the test isSubclassOfClass: (line ~291) to fail if using [JSONModel class]. + // somewhat related: https://stackoverflow.com/questions/6524165/nsclassfromstring-vs-classnamednsstring + // //; seems to break the unit tests + + // Using NSClassFromString instead of [JSONModel class], as this was breaking unit tests, see below + //http://stackoverflow.com/questions/21394919/xcode-5-unit-test-seeing-wrong-class + JSONModelClass = NSClassFromString(NSStringFromClass(self)); + } + }); +} + +-(void)__setup__ +{ + //if first instance of this model, generate the property list + if (!objc_getAssociatedObject(self.class, &kClassPropertiesKey)) { + [self __inspectProperties]; + } + + //if there's a custom key mapper, store it in the associated object + id mapper = [[self class] keyMapper]; + if ( mapper && !objc_getAssociatedObject(self.class, &kMapperObjectKey) ) { + objc_setAssociatedObject( + self.class, + &kMapperObjectKey, + mapper, + OBJC_ASSOCIATION_RETAIN // This is atomic + ); + } +} + +-(id)init +{ + self = [super init]; + if (self) { + //do initial class setup + [self __setup__]; + } + return self; +} + +-(instancetype)initWithData:(NSData *)data error:(NSError *__autoreleasing *)err +{ + //check for nil input + if (!data) { + if (err) *err = [JSONModelError errorInputIsNil]; + return nil; + } + //read the json + JSONModelError* initError = nil; + id obj = [NSJSONSerialization JSONObjectWithData:data + options:kNilOptions + error:&initError]; + + if (initError) { + if (err) *err = [JSONModelError errorBadJSON]; + return nil; + } + + //init with dictionary + id objModel = [self initWithDictionary:obj error:&initError]; + if (initError && err) *err = initError; + return objModel; +} + +-(id)initWithString:(NSString*)string error:(JSONModelError**)err +{ + JSONModelError* initError = nil; + id objModel = [self initWithString:string usingEncoding:NSUTF8StringEncoding error:&initError]; + if (initError && err) *err = initError; + return objModel; +} + +-(id)initWithString:(NSString *)string usingEncoding:(NSStringEncoding)encoding error:(JSONModelError**)err +{ + //check for nil input + if (!string) { + if (err) *err = [JSONModelError errorInputIsNil]; + return nil; + } + + JSONModelError* initError = nil; + id objModel = [self initWithData:[string dataUsingEncoding:encoding] error:&initError]; + if (initError && err) *err = initError; + return objModel; + +} + +-(id)initWithDictionary:(NSDictionary*)dict error:(NSError**)err +{ + //check for nil input + if (!dict) { + if (err) *err = [JSONModelError errorInputIsNil]; + return nil; + } + + //invalid input, just create empty instance + if (![dict isKindOfClass:[NSDictionary class]]) { + if (err) *err = [JSONModelError errorInvalidDataWithMessage:@"Attempt to initialize JSONModel object using initWithDictionary:error: but the dictionary parameter was not an 'NSDictionary'."]; + return nil; + } + + //create a class instance + self = [self init]; + if (!self) { + + //super init didn't succeed + if (err) *err = [JSONModelError errorModelIsInvalid]; + return nil; + } + + //check incoming data structure + if (![self __doesDictionary:dict matchModelWithKeyMapper:self.__keyMapper error:err]) { + return nil; + } + + //import the data from a dictionary + if (![self __importDictionary:dict withKeyMapper:self.__keyMapper validation:YES error:err]) { + return nil; + } + + //run any custom model validation + if (![self validate:err]) { + return nil; + } + + //model is valid! yay! + return self; +} + +-(JSONKeyMapper*)__keyMapper +{ + //get the model key mapper + return objc_getAssociatedObject(self.class, &kMapperObjectKey); +} + +-(BOOL)__doesDictionary:(NSDictionary*)dict matchModelWithKeyMapper:(JSONKeyMapper*)keyMapper error:(NSError**)err +{ + //check if all required properties are present + NSArray* incomingKeysArray = [dict allKeys]; + NSMutableSet* requiredProperties = [self __requiredPropertyNames].mutableCopy; + NSSet* incomingKeys = [NSSet setWithArray: incomingKeysArray]; + + //transform the key names, if necessary + if (keyMapper || globalKeyMapper) { + + NSMutableSet* transformedIncomingKeys = [NSMutableSet setWithCapacity: requiredProperties.count]; + NSString* transformedName = nil; + + //loop over the required properties list + for (JSONModelClassProperty* property in [self __properties__]) { + + transformedName = (keyMapper||globalKeyMapper) ? [self __mapString:property.name withKeyMapper:keyMapper] : property.name; + + //check if exists and if so, add to incoming keys + id value; + @try { + value = [dict valueForKeyPath:transformedName]; + } + @catch (NSException *exception) { + value = dict[transformedName]; + } + + if (value) { + [transformedIncomingKeys addObject: property.name]; + } + } + + //overwrite the raw incoming list with the mapped key names + incomingKeys = transformedIncomingKeys; + } + + //check for missing input keys + if (![requiredProperties isSubsetOfSet:incomingKeys]) { + + //get a list of the missing properties + [requiredProperties minusSet:incomingKeys]; + + //not all required properties are in - invalid input + JMLog(@"Incoming data was invalid [%@ initWithDictionary:]. Keys missing: %@", self.class, requiredProperties); + + if (err) *err = [JSONModelError errorInvalidDataWithMissingKeys:requiredProperties]; + return NO; + } + + //not needed anymore + incomingKeys= nil; + requiredProperties= nil; + + return YES; +} + +-(NSString*)__mapString:(NSString*)string withKeyMapper:(JSONKeyMapper*)keyMapper +{ + if (keyMapper) { + //custom mapper + NSString* mappedName = [keyMapper convertValue:string]; + if (globalKeyMapper && [mappedName isEqualToString: string]) { + mappedName = [globalKeyMapper convertValue:string]; + } + string = mappedName; + } else if (globalKeyMapper) { + //global keymapper + string = [globalKeyMapper convertValue:string]; + } + + return string; +} + +-(BOOL)__importDictionary:(NSDictionary*)dict withKeyMapper:(JSONKeyMapper*)keyMapper validation:(BOOL)validation error:(NSError**)err +{ + //loop over the incoming keys and set self's properties + for (JSONModelClassProperty* property in [self __properties__]) { + + //convert key name to model keys, if a mapper is provided + NSString* jsonKeyPath = (keyMapper||globalKeyMapper) ? [self __mapString:property.name withKeyMapper:keyMapper] : property.name; + //JMLog(@"keyPath: %@", jsonKeyPath); + + //general check for data type compliance + id jsonValue; + @try { + jsonValue = [dict valueForKeyPath: jsonKeyPath]; + } + @catch (NSException *exception) { + jsonValue = dict[jsonKeyPath]; + } + + //check for Optional properties + if (isNull(jsonValue)) { + //skip this property, continue with next property + if (property.isOptional || !validation) continue; + + if (err) { + //null value for required property + NSString* msg = [NSString stringWithFormat:@"Value of required model key %@ is null", property.name]; + JSONModelError* dataErr = [JSONModelError errorInvalidDataWithMessage:msg]; + *err = [dataErr errorByPrependingKeyPathComponent:property.name]; + } + return NO; + } + + Class jsonValueClass = [jsonValue class]; + BOOL isValueOfAllowedType = NO; + + for (Class allowedType in allowedJSONTypes) { + if ( [jsonValueClass isSubclassOfClass: allowedType] ) { + isValueOfAllowedType = YES; + break; + } + } + + if (isValueOfAllowedType==NO) { + //type not allowed + JMLog(@"Type %@ is not allowed in JSON.", NSStringFromClass(jsonValueClass)); + + if (err) { + NSString* msg = [NSString stringWithFormat:@"Type %@ is not allowed in JSON.", NSStringFromClass(jsonValueClass)]; + JSONModelError* dataErr = [JSONModelError errorInvalidDataWithMessage:msg]; + *err = [dataErr errorByPrependingKeyPathComponent:property.name]; + } + return NO; + } + + //check if there's matching property in the model + if (property) { + + // check for custom setter, than the model doesn't need to do any guessing + // how to read the property's value from JSON + if ([self __customSetValue:jsonValue forProperty:property]) { + //skip to next JSON key + continue; + }; + + // 0) handle primitives + if (property.type == nil && property.structName==nil) { + + //generic setter + if (jsonValue != [self valueForKey:property.name]) { + [self setValue:jsonValue forKey: property.name]; + } + + //skip directly to the next key + continue; + } + + // 0.5) handle nils + if (isNull(jsonValue)) { + if ([self valueForKey:property.name] != nil) { + [self setValue:nil forKey: property.name]; + } + continue; + } + + + // 1) check if property is itself a JSONModel + if ([self __isJSONModelSubClass:property.type]) { + + //initialize the property's model, store it + JSONModelError* initErr = nil; + id value = [[property.type alloc] initWithDictionary: jsonValue error:&initErr]; + + if (!value) { + //skip this property, continue with next property + if (property.isOptional || !validation) continue; + + // Propagate the error, including the property name as the key-path component + if((err != nil) && (initErr != nil)) + { + *err = [initErr errorByPrependingKeyPathComponent:property.name]; + } + return NO; + } + if (![value isEqual:[self valueForKey:property.name]]) { + [self setValue:value forKey: property.name]; + } + + //for clarity, does the same without continue + continue; + + } else { + + // 2) check if there's a protocol to the property + // ) might or not be the case there's a built in transform for it + if (property.protocol) { + + //JMLog(@"proto: %@", p.protocol); + jsonValue = [self __transform:jsonValue forProperty:property error:err]; + if (!jsonValue) { + if ((err != nil) && (*err == nil)) { + NSString* msg = [NSString stringWithFormat:@"Failed to transform value, but no error was set during transformation. (%@)", property]; + JSONModelError* dataErr = [JSONModelError errorInvalidDataWithMessage:msg]; + *err = [dataErr errorByPrependingKeyPathComponent:property.name]; + } + return NO; + } + } + + // 3.1) handle matching standard JSON types + if (property.isStandardJSONType && [jsonValue isKindOfClass: property.type]) { + + //mutable properties + if (property.isMutable) { + jsonValue = [jsonValue mutableCopy]; + } + + //set the property value + if (![jsonValue isEqual:[self valueForKey:property.name]]) { + [self setValue:jsonValue forKey: property.name]; + } + continue; + } + + // 3.3) handle values to transform + if ( + (![jsonValue isKindOfClass:property.type] && !isNull(jsonValue)) + || + //the property is mutable + property.isMutable + || + //custom struct property + property.structName + ) { + + // searched around the web how to do this better + // but did not find any solution, maybe that's the best idea? (hardly) + Class sourceClass = [JSONValueTransformer classByResolvingClusterClasses:[jsonValue class]]; + + //JMLog(@"to type: [%@] from type: [%@] transformer: [%@]", p.type, sourceClass, selectorName); + + //build a method selector for the property and json object classes + NSString* selectorName = [NSString stringWithFormat:@"%@From%@:", + (property.structName? property.structName : property.type), //target name + sourceClass]; //source name + SEL selector = NSSelectorFromString(selectorName); + + //check for custom transformer + BOOL foundCustomTransformer = NO; + if ([valueTransformer respondsToSelector:selector]) { + foundCustomTransformer = YES; + } else { + //try for hidden custom transformer + selectorName = [NSString stringWithFormat:@"__%@",selectorName]; + selector = NSSelectorFromString(selectorName); + if ([valueTransformer respondsToSelector:selector]) { + foundCustomTransformer = YES; + } + } + + //check if there's a transformer with that name + if (foundCustomTransformer) { + + //it's OK, believe me... +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + //transform the value + jsonValue = [valueTransformer performSelector:selector withObject:jsonValue]; +#pragma clang diagnostic pop + + if (![jsonValue isEqual:[self valueForKey:property.name]]) { + [self setValue:jsonValue forKey: property.name]; + } + + } else { + NSString* msg = [NSString stringWithFormat:@"%@ type not supported for %@.%@", property.type, [self class], property.name]; + JSONModelError* dataErr = [JSONModelError errorInvalidDataWithTypeMismatch:msg]; + *err = [dataErr errorByPrependingKeyPathComponent:property.name]; + return NO; + } + + } else { + // 3.4) handle "all other" cases (if any) + if (![jsonValue isEqual:[self valueForKey:property.name]]) { + [self setValue:jsonValue forKey: property.name]; + } + } + } + } + } + + return YES; +} + +#pragma mark - property inspection methods + +-(BOOL)__isJSONModelSubClass:(Class)class +{ +// http://stackoverflow.com/questions/19883472/objc-nsobject-issubclassofclass-gives-incorrect-failure +#ifdef UNIT_TESTING + return [@"JSONModel" isEqualToString: NSStringFromClass([class superclass])]; +#else + return [class isSubclassOfClass:JSONModelClass]; +#endif +} + +//returns a set of the required keys for the model +-(NSMutableSet*)__requiredPropertyNames +{ + //fetch the associated property names + NSMutableSet* classRequiredPropertyNames = objc_getAssociatedObject(self.class, &kClassRequiredPropertyNamesKey); + + if (!classRequiredPropertyNames) { + classRequiredPropertyNames = [NSMutableSet set]; + [[self __properties__] enumerateObjectsUsingBlock:^(JSONModelClassProperty* p, NSUInteger idx, BOOL *stop) { + if (!p.isOptional) [classRequiredPropertyNames addObject:p.name]; + }]; + + //persist the list + objc_setAssociatedObject( + self.class, + &kClassRequiredPropertyNamesKey, + classRequiredPropertyNames, + OBJC_ASSOCIATION_RETAIN // This is atomic + ); + } + return classRequiredPropertyNames; +} + +//returns a list of the model's properties +-(NSArray*)__properties__ +{ + //fetch the associated object + NSDictionary* classProperties = objc_getAssociatedObject(self.class, &kClassPropertiesKey); + if (classProperties) return [classProperties allValues]; + + //if here, the class needs to inspect itself + [self __setup__]; + + //return the property list + classProperties = objc_getAssociatedObject(self.class, &kClassPropertiesKey); + return [classProperties allValues]; +} + +//inspects the class, get's a list of the class properties +-(void)__inspectProperties +{ + //JMLog(@"Inspect class: %@", [self class]); + + NSMutableDictionary* propertyIndex = [NSMutableDictionary dictionary]; + + //temp variables for the loops + Class class = [self class]; + NSScanner* scanner = nil; + NSString* propertyType = nil; + + // inspect inherited properties up to the JSONModel class + while (class != [JSONModel class]) { + //JMLog(@"inspecting: %@", NSStringFromClass(class)); + + unsigned int propertyCount; + objc_property_t *properties = class_copyPropertyList(class, &propertyCount); + + //loop over the class properties + for (unsigned int i = 0; i < propertyCount; i++) { + + JSONModelClassProperty* p = [[JSONModelClassProperty alloc] init]; + + //get property name + objc_property_t property = properties[i]; + const char *propertyName = property_getName(property); + p.name = @(propertyName); + + //JMLog(@"property: %@", p.name); + + //get property attributes + const char *attrs = property_getAttributes(property); + NSString* propertyAttributes = @(attrs); + NSArray* attributeItems = [propertyAttributes componentsSeparatedByString:@","]; + + //ignore read-only properties + if ([attributeItems containsObject:@"R"]) { + continue; //to next property + } + + //check for 64b BOOLs + if ([propertyAttributes hasPrefix:@"Tc,"]) { + //mask BOOLs as structs so they can have custom converters + p.structName = @"BOOL"; + } + + scanner = [NSScanner scannerWithString: propertyAttributes]; + + //JMLog(@"attr: %@", [NSString stringWithCString:attrs encoding:NSUTF8StringEncoding]); + [scanner scanUpToString:@"T" intoString: nil]; + [scanner scanString:@"T" intoString:nil]; + + //check if the property is an instance of a class + if ([scanner scanString:@"@\"" intoString: &propertyType]) { + + [scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@"\"<"] + intoString:&propertyType]; + + //JMLog(@"type: %@", propertyClassName); + p.type = NSClassFromString(propertyType); + p.isMutable = ([propertyType rangeOfString:@"Mutable"].location != NSNotFound); + p.isStandardJSONType = [allowedJSONTypes containsObject:p.type]; + + //read through the property protocols + while ([scanner scanString:@"<" intoString:NULL]) { + + NSString* protocolName = nil; + + [scanner scanUpToString:@">" intoString: &protocolName]; + + if ([protocolName isEqualToString:@"Optional"]) { + p.isOptional = YES; + } else if([protocolName isEqualToString:@"Index"]) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" + p.isIndex = YES; +#pragma GCC diagnostic pop + + objc_setAssociatedObject( + self.class, + &kIndexPropertyNameKey, + p.name, + OBJC_ASSOCIATION_RETAIN // This is atomic + ); + } else if([protocolName isEqualToString:@"Ignore"]) { + p = nil; + } else { + p.protocol = protocolName; + } + + [scanner scanString:@">" intoString:NULL]; + } + + } + //check if the property is a structure + else if ([scanner scanString:@"{" intoString: &propertyType]) { + [scanner scanCharactersFromSet:[NSCharacterSet alphanumericCharacterSet] + intoString:&propertyType]; + + p.isStandardJSONType = NO; + p.structName = propertyType; + + } + //the property must be a primitive + else { + + //the property contains a primitive data type + [scanner scanUpToCharactersFromSet:[NSCharacterSet characterSetWithCharactersInString:@","] + intoString:&propertyType]; + + //get the full name of the primitive type + propertyType = valueTransformer.primitivesNames[propertyType]; + + if (![allowedPrimitiveTypes containsObject:propertyType]) { + + //type not allowed - programmer mistaken -> exception + @throw [NSException exceptionWithName:@"JSONModelProperty type not allowed" + reason:[NSString stringWithFormat:@"Property type of %@.%@ is not supported by JSONModel.", self.class, p.name] + userInfo:nil]; + } + + } + + NSString *nsPropertyName = @(propertyName); + if([[self class] propertyIsOptional:nsPropertyName]){ + p.isOptional = YES; + } + + if([[self class] propertyIsIgnored:nsPropertyName]){ + p = nil; + } + + Class customClass = [[self class] classForCollectionProperty:nsPropertyName]; + if (customClass) { + p.protocol = NSStringFromClass(customClass); + } + + //few cases where JSONModel will ignore properties automatically + if ([propertyType isEqualToString:@"Block"]) { + p = nil; + } + + //add the property object to the temp index + if (p && ![propertyIndex objectForKey:p.name]) { + [propertyIndex setValue:p forKey:p.name]; + } + + // generate custom setters and getter + if (p) + { + NSString *name = [p.name stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[p.name substringToIndex:1].uppercaseString]; + + // getter + SEL getter = NSSelectorFromString([NSString stringWithFormat:@"JSONObjectFor%@", name]); + + if ([self respondsToSelector:getter]) + p.customGetter = getter; + + // setters + p.customSetters = [NSMutableDictionary new]; + + SEL genericSetter = NSSelectorFromString([NSString stringWithFormat:@"set%@WithJSONObject:", name]); + + if ([self respondsToSelector:genericSetter]) + p.customSetters[@"generic"] = [NSValue valueWithBytes:&genericSetter objCType:@encode(SEL)]; + + for (Class type in allowedJSONTypes) + { + NSString *class = NSStringFromClass([JSONValueTransformer classByResolvingClusterClasses:type]); + + if (p.customSetters[class]) + continue; + + SEL setter = NSSelectorFromString([NSString stringWithFormat:@"set%@With%@:", name, class]); + + if ([self respondsToSelector:setter]) + p.customSetters[class] = [NSValue valueWithBytes:&setter objCType:@encode(SEL)]; + } + } + } + + free(properties); + + //ascend to the super of the class + //(will do that until it reaches the root class - JSONModel) + class = [class superclass]; + } + + //finally store the property index in the static property index + objc_setAssociatedObject( + self.class, + &kClassPropertiesKey, + [propertyIndex copy], + OBJC_ASSOCIATION_RETAIN // This is atomic + ); +} + +#pragma mark - built-in transformer methods +//few built-in transformations +-(id)__transform:(id)value forProperty:(JSONModelClassProperty*)property error:(NSError**)err +{ + Class protocolClass = NSClassFromString(property.protocol); + if (!protocolClass) { + + //no other protocols on arrays and dictionaries + //except JSONModel classes + if ([value isKindOfClass:[NSArray class]]) { + @throw [NSException exceptionWithName:@"Bad property protocol declaration" + reason:[NSString stringWithFormat:@"<%@> is not allowed JSONModel property protocol, and not a JSONModel class.", property.protocol] + userInfo:nil]; + } + return value; + } + + //if the protocol is actually a JSONModel class + if ([self __isJSONModelSubClass:protocolClass]) { + + //check if it's a list of models + if ([property.type isSubclassOfClass:[NSArray class]]) { + + // Expecting an array, make sure 'value' is an array + if(![[value class] isSubclassOfClass:[NSArray class]]) + { + if(err != nil) + { + NSString* mismatch = [NSString stringWithFormat:@"Property '%@' is declared as NSArray<%@>* but the corresponding JSON value is not a JSON Array.", property.name, property.protocol]; + JSONModelError* typeErr = [JSONModelError errorInvalidDataWithTypeMismatch:mismatch]; + *err = [typeErr errorByPrependingKeyPathComponent:property.name]; + } + return nil; + } + + //one shot conversion + JSONModelError* arrayErr = nil; + value = [[protocolClass class] arrayOfModelsFromDictionaries:value error:&arrayErr]; + if((err != nil) && (arrayErr != nil)) + { + *err = [arrayErr errorByPrependingKeyPathComponent:property.name]; + return nil; + } + } + + //check if it's a dictionary of models + if ([property.type isSubclassOfClass:[NSDictionary class]]) { + + // Expecting a dictionary, make sure 'value' is a dictionary + if(![[value class] isSubclassOfClass:[NSDictionary class]]) + { + if(err != nil) + { + NSString* mismatch = [NSString stringWithFormat:@"Property '%@' is declared as NSDictionary<%@>* but the corresponding JSON value is not a JSON Object.", property.name, property.protocol]; + JSONModelError* typeErr = [JSONModelError errorInvalidDataWithTypeMismatch:mismatch]; + *err = [typeErr errorByPrependingKeyPathComponent:property.name]; + } + return nil; + } + + NSMutableDictionary* res = [NSMutableDictionary dictionary]; + + for (NSString* key in [value allKeys]) { + JSONModelError* initErr = nil; + id obj = [[[protocolClass class] alloc] initWithDictionary:value[key] error:&initErr]; + if (obj == nil) + { + // Propagate the error, including the property name as the key-path component + if((err != nil) && (initErr != nil)) + { + initErr = [initErr errorByPrependingKeyPathComponent:key]; + *err = [initErr errorByPrependingKeyPathComponent:property.name]; + } + return nil; + } + [res setValue:obj forKey:key]; + } + value = [NSDictionary dictionaryWithDictionary:res]; + } + } + + return value; +} + +//built-in reverse transformations (export to JSON compliant objects) +-(id)__reverseTransform:(id)value forProperty:(JSONModelClassProperty*)property +{ + Class protocolClass = NSClassFromString(property.protocol); + if (!protocolClass) return value; + + //if the protocol is actually a JSONModel class + if ([self __isJSONModelSubClass:protocolClass]) { + + //check if should export list of dictionaries + if (property.type == [NSArray class] || property.type == [NSMutableArray class]) { + NSMutableArray* tempArray = [NSMutableArray arrayWithCapacity: [(NSArray*)value count] ]; + for (NSObject* model in (NSArray*)value) { + if ([model respondsToSelector:@selector(toDictionary)]) { + [tempArray addObject: [model toDictionary]]; + } else + [tempArray addObject: model]; + } + return [tempArray copy]; + } + + //check if should export dictionary of dictionaries + if (property.type == [NSDictionary class] || property.type == [NSMutableDictionary class]) { + NSMutableDictionary* res = [NSMutableDictionary dictionary]; + for (NSString* key in [(NSDictionary*)value allKeys]) { + id model = value[key]; + [res setValue: [model toDictionary] forKey: key]; + } + return [NSDictionary dictionaryWithDictionary:res]; + } + } + + return value; +} + +#pragma mark - custom transformations +- (BOOL)__customSetValue:(id )value forProperty:(JSONModelClassProperty *)property +{ + NSString *class = NSStringFromClass([JSONValueTransformer classByResolvingClusterClasses:[value class]]); + + SEL setter = nil; + [property.customSetters[class] getValue:&setter]; + + if (!setter) + [property.customSetters[@"generic"] getValue:&setter]; + + if (!setter) + return NO; + + IMP imp = [self methodForSelector:setter]; + void (*func)(id, SEL, id ) = (void *)imp; + func(self, setter, value); + + return YES; +} + +- (BOOL)__customGetValue:(id *)value forProperty:(JSONModelClassProperty *)property +{ + SEL getter = property.customGetter; + + if (!getter) + return NO; + + IMP imp = [self methodForSelector:getter]; + id (*func)(id, SEL) = (void *)imp; + *value = func(self, getter); + + return YES; +} + +#pragma mark - persistance +-(void)__createDictionariesForKeyPath:(NSString*)keyPath inDictionary:(NSMutableDictionary**)dict +{ + //find if there's a dot left in the keyPath + NSUInteger dotLocation = [keyPath rangeOfString:@"."].location; + if (dotLocation==NSNotFound) return; + + //inspect next level + NSString* nextHierarchyLevelKeyName = [keyPath substringToIndex: dotLocation]; + NSDictionary* nextLevelDictionary = (*dict)[nextHierarchyLevelKeyName]; + + if (nextLevelDictionary==nil) { + //create non-existing next level here + nextLevelDictionary = [NSMutableDictionary dictionary]; + } + + //recurse levels + [self __createDictionariesForKeyPath:[keyPath substringFromIndex: dotLocation+1] + inDictionary:&nextLevelDictionary ]; + + //create the hierarchy level + [*dict setValue:nextLevelDictionary forKeyPath: nextHierarchyLevelKeyName]; +} + +-(NSDictionary*)toDictionary +{ + return [self toDictionaryWithKeys:nil]; +} + +-(NSString*)toJSONString +{ + return [self toJSONStringWithKeys:nil]; +} + +-(NSData*)toJSONData +{ + return [self toJSONDataWithKeys:nil]; +} + +//exports the model as a dictionary of JSON compliant objects +-(NSDictionary*)toDictionaryWithKeys:(NSArray*)propertyNames +{ + NSArray* properties = [self __properties__]; + NSMutableDictionary* tempDictionary = [NSMutableDictionary dictionaryWithCapacity:properties.count]; + + id value; + + //loop over all properties + for (JSONModelClassProperty* p in properties) { + + //skip if unwanted + if (propertyNames != nil && ![propertyNames containsObject:p.name]) + continue; + + //fetch key and value + NSString* keyPath = (self.__keyMapper||globalKeyMapper) ? [self __mapString:p.name withKeyMapper:self.__keyMapper] : p.name; + value = [self valueForKey: p.name]; + + //JMLog(@"toDictionary[%@]->[%@] = '%@'", p.name, keyPath, value); + + if ([keyPath rangeOfString:@"."].location != NSNotFound) { + //there are sub-keys, introduce dictionaries for them + [self __createDictionariesForKeyPath:keyPath inDictionary:&tempDictionary]; + } + + //check for custom getter + if ([self __customGetValue:&value forProperty:p]) { + //custom getter, all done + [tempDictionary setValue:value forKeyPath:keyPath]; + continue; + } + + //export nil when they are not optional values as JSON null, so that the structure of the exported data + //is still valid if it's to be imported as a model again + if (isNull(value)) { + + if (value == nil) + { + [tempDictionary removeObjectForKey:keyPath]; + } + else + { + [tempDictionary setValue:[NSNull null] forKeyPath:keyPath]; + } + continue; + } + + //check if the property is another model + if ([value isKindOfClass:JSONModelClass]) { + + //recurse models + value = [(JSONModel*)value toDictionary]; + [tempDictionary setValue:value forKeyPath: keyPath]; + + //for clarity + continue; + + } else { + + // 1) check for built-in transformation + if (p.protocol) { + value = [self __reverseTransform:value forProperty:p]; + } + + // 2) check for standard types OR 2.1) primitives + if (p.structName==nil && (p.isStandardJSONType || p.type==nil)) { + + //generic get value + [tempDictionary setValue:value forKeyPath: keyPath]; + + continue; + } + + // 3) try to apply a value transformer + if (YES) { + + //create selector from the property's class name + NSString* selectorName = [NSString stringWithFormat:@"%@From%@:", @"JSONObject", p.type?p.type:p.structName]; + SEL selector = NSSelectorFromString(selectorName); + + BOOL foundCustomTransformer = NO; + if ([valueTransformer respondsToSelector:selector]) { + foundCustomTransformer = YES; + } else { + //try for hidden transformer + selectorName = [NSString stringWithFormat:@"__%@",selectorName]; + selector = NSSelectorFromString(selectorName); + if ([valueTransformer respondsToSelector:selector]) { + foundCustomTransformer = YES; + } + } + + //check if there's a transformer declared + if (foundCustomTransformer) { + + //it's OK, believe me... +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + value = [valueTransformer performSelector:selector withObject:value]; +#pragma clang diagnostic pop + + [tempDictionary setValue:value forKeyPath: keyPath]; + + } else { + + //in this case most probably a custom property was defined in a model + //but no default reverse transformer for it + @throw [NSException exceptionWithName:@"Value transformer not found" + reason:[NSString stringWithFormat:@"[JSONValueTransformer %@] not found", selectorName] + userInfo:nil]; + return nil; + } + } + } + } + + return [tempDictionary copy]; +} + +//exports model to a dictionary and then to a JSON string +-(NSData*)toJSONDataWithKeys:(NSArray*)propertyNames +{ + NSData* jsonData = nil; + NSError* jsonError = nil; + + @try { + NSDictionary* dict = [self toDictionaryWithKeys:propertyNames]; + jsonData = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&jsonError]; + } + @catch (NSException *exception) { + //this should not happen in properly design JSONModel + //usually means there was no reverse transformer for a custom property + JMLog(@"EXCEPTION: %@", exception.description); + return nil; + } + + return jsonData; +} + +-(NSString*)toJSONStringWithKeys:(NSArray*)propertyNames +{ + return [[NSString alloc] initWithData: [self toJSONDataWithKeys: propertyNames] + encoding: NSUTF8StringEncoding]; +} + +#pragma mark - import/export of lists +//loop over an NSArray of JSON objects and turn them into models ++(NSMutableArray*)arrayOfModelsFromDictionaries:(NSArray*)array +{ + return [self arrayOfModelsFromDictionaries:array error:nil]; +} + ++ (NSMutableArray *)arrayOfModelsFromData:(NSData *)data error:(NSError **)err +{ + id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:err]; + if (!json || ![json isKindOfClass:[NSArray class]]) return nil; + + return [self arrayOfModelsFromDictionaries:json error:err]; +} + ++ (NSMutableArray *)arrayOfModelsFromString:(NSString *)string error:(NSError **)err +{ + return [self arrayOfModelsFromData:[string dataUsingEncoding:NSUTF8StringEncoding] error:err]; +} + +// Same as above, but with error reporting ++(NSMutableArray*)arrayOfModelsFromDictionaries:(NSArray*)array error:(NSError**)err +{ + //bail early + if (isNull(array)) return nil; + + //parse dictionaries to objects + NSMutableArray* list = [NSMutableArray arrayWithCapacity: [array count]]; + + for (id d in array) + { + if ([d isKindOfClass:NSDictionary.class]) + { + JSONModelError* initErr = nil; + id obj = [[self alloc] initWithDictionary:d error:&initErr]; + if (obj == nil) + { + // Propagate the error, including the array index as the key-path component + if((err != nil) && (initErr != nil)) + { + NSString* path = [NSString stringWithFormat:@"[%lu]", (unsigned long)list.count]; + *err = [initErr errorByPrependingKeyPathComponent:path]; + } + return nil; + } + + [list addObject: obj]; + } else if ([d isKindOfClass:NSArray.class]) + { + [list addObjectsFromArray:[self arrayOfModelsFromDictionaries:d error:err]]; + } else + { + // This is very bad + } + + } + + return list; +} + ++ (NSMutableDictionary *)dictionaryOfModelsFromString:(NSString *)string error:(NSError **)err +{ + return [self dictionaryOfModelsFromData:[string dataUsingEncoding:NSUTF8StringEncoding] error:err]; +} + ++ (NSMutableDictionary *)dictionaryOfModelsFromData:(NSData *)data error:(NSError **)err +{ + id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:err]; + if (!json || ![json isKindOfClass:[NSDictionary class]]) return nil; + + return [self dictionaryOfModelsFromDictionary:json error:err]; +} + ++ (NSMutableDictionary *)dictionaryOfModelsFromDictionary:(NSDictionary *)dictionary error:(NSError **)err +{ + NSMutableDictionary *output = [NSMutableDictionary dictionaryWithCapacity:dictionary.count]; + + for (NSString *key in dictionary.allKeys) + { + id object = dictionary[key]; + + if ([object isKindOfClass:NSDictionary.class]) + { + id obj = [[self alloc] initWithDictionary:object error:err]; + if (obj == nil) return nil; + output[key] = obj; + } + else if ([object isKindOfClass:NSArray.class]) + { + id obj = [self arrayOfModelsFromDictionaries:object error:err]; + if (obj == nil) return nil; + output[key] = obj; + } + else + { + *err = [JSONModelError errorInvalidDataWithTypeMismatch:@"Only dictionaries and arrays are supported"]; + return nil; + } + } + + return output; +} + +//loop over NSArray of models and export them to JSON objects ++(NSMutableArray*)arrayOfDictionariesFromModels:(NSArray*)array +{ + //bail early + if (isNull(array)) return nil; + + //convert to dictionaries + NSMutableArray* list = [NSMutableArray arrayWithCapacity: [array count]]; + + for (id object in array) { + + id obj = [object toDictionary]; + if (!obj) return nil; + + [list addObject: obj]; + } + return list; +} + +//loop over NSArray of models and export them to JSON objects with specific properties ++(NSMutableArray*)arrayOfDictionariesFromModels:(NSArray*)array propertyNamesToExport:(NSArray*)propertyNamesToExport; +{ + //bail early + if (isNull(array)) return nil; + + //convert to dictionaries + NSMutableArray* list = [NSMutableArray arrayWithCapacity: [array count]]; + + for (id object in array) { + + id obj = [object toDictionaryWithKeys:propertyNamesToExport]; + if (!obj) return nil; + + [list addObject: obj]; + } + return list; +} + ++(NSMutableDictionary *)dictionaryOfDictionariesFromModels:(NSDictionary *)dictionary +{ + //bail early + if (isNull(dictionary)) return nil; + + NSMutableDictionary *output = [NSMutableDictionary dictionaryWithCapacity:dictionary.count]; + + for (NSString *key in dictionary.allKeys) { + id object = dictionary[key]; + id obj = [object toDictionary]; + if (!obj) return nil; + output[key] = obj; + } + + return output; +} + +#pragma mark - custom comparison methods + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +-(NSString*)indexPropertyName +{ + //custom getter for an associated object + return objc_getAssociatedObject(self.class, &kIndexPropertyNameKey); +} + +-(BOOL)isEqual:(id)object +{ + //bail early if different classes + if (![object isMemberOfClass:[self class]]) return NO; + + if (self.indexPropertyName) { + //there's a defined ID property + id objectId = [object valueForKey: self.indexPropertyName]; + return [[self valueForKey: self.indexPropertyName] isEqual:objectId]; + } + + //default isEqual implementation + return [super isEqual:object]; +} + +-(NSComparisonResult)compare:(id)object +{ + if (self.indexPropertyName) { + id objectId = [object valueForKey: self.indexPropertyName]; + if ([objectId respondsToSelector:@selector(compare:)]) { + return [[self valueForKey:self.indexPropertyName] compare:objectId]; + } + } + + //on purpose postponing the asserts for speed optimization + //these should not happen anyway in production conditions + NSAssert(self.indexPropertyName, @"Can't compare models with no property"); + NSAssert1(NO, @"The property of %@ is not comparable class.", [self class]); + return kNilOptions; +} + +- (NSUInteger)hash +{ + if (self.indexPropertyName) { + id val = [self valueForKey:self.indexPropertyName]; + + if (val) { + return [val hash]; + } + } + + return [super hash]; +} + +#pragma GCC diagnostic pop + +#pragma mark - custom data validation +-(BOOL)validate:(NSError**)error +{ + return YES; +} + +#pragma mark - custom recursive description +//custom description method for debugging purposes +-(NSString*)description +{ + NSMutableString* text = [NSMutableString stringWithFormat:@"<%@> \n", [self class]]; + + for (JSONModelClassProperty *p in [self __properties__]) { + + id value = ([p.name isEqualToString:@"description"])?self->_description:[self valueForKey:p.name]; + NSString* valueDescription = (value)?[value description]:@""; + + if (p.isStandardJSONType && ![value respondsToSelector:@selector(count)] && [valueDescription length]>60) { + + //cap description for longer values + valueDescription = [NSString stringWithFormat:@"%@...", [valueDescription substringToIndex:59]]; + } + valueDescription = [valueDescription stringByReplacingOccurrencesOfString:@"\n" withString:@"\n "]; + [text appendFormat:@" [%@]: %@\n", p.name, valueDescription]; + } + + [text appendFormat:@"", [self class]]; + return text; +} + +#pragma mark - key mapping ++(JSONKeyMapper*)keyMapper +{ + return nil; +} + ++(void)setGlobalKeyMapper:(JSONKeyMapper*)globalKeyMapperParam +{ + globalKeyMapper = globalKeyMapperParam; +} + ++(BOOL)propertyIsOptional:(NSString*)propertyName +{ + return NO; +} + ++(BOOL)propertyIsIgnored:(NSString *)propertyName +{ + return NO; +} + ++(NSString*)protocolForArrayProperty:(NSString *)propertyName +{ + return nil; +} + ++(Class)classForCollectionProperty:(NSString *)propertyName +{ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" + NSString *protocolName = [self protocolForArrayProperty:propertyName]; +#pragma GCC diagnostic pop + + if (!protocolName) + return nil; + + return NSClassFromString(protocolName); +} + +#pragma mark - working with incomplete models +- (void)mergeFromDictionary:(NSDictionary *)dict useKeyMapping:(BOOL)useKeyMapping +{ + [self mergeFromDictionary:dict useKeyMapping:useKeyMapping error:nil]; +} + +- (BOOL)mergeFromDictionary:(NSDictionary *)dict useKeyMapping:(BOOL)useKeyMapping error:(NSError **)error +{ + return [self __importDictionary:dict withKeyMapper:(useKeyMapping)? self.__keyMapper:nil validation:NO error:error]; +} + +#pragma mark - NSCopying, NSCoding +-(instancetype)copyWithZone:(NSZone *)zone +{ + return [NSKeyedUnarchiver unarchiveObjectWithData: + [NSKeyedArchiver archivedDataWithRootObject:self] + ]; +} + +-(instancetype)initWithCoder:(NSCoder *)decoder +{ + NSString* json; + + if ([decoder respondsToSelector:@selector(decodeObjectOfClass:forKey:)]) { + json = [decoder decodeObjectOfClass:[NSString class] forKey:@"json"]; + } else { + json = [decoder decodeObjectForKey:@"json"]; + } + + JSONModelError *error = nil; + self = [self initWithString:json error:&error]; + if (error) { + JMLog(@"%@",[error localizedDescription]); + } + return self; +} + +-(void)encodeWithCoder:(NSCoder *)encoder +{ + [encoder encodeObject:self.toJSONString forKey:@"json"]; +} + ++ (BOOL)supportsSecureCoding +{ + return YES; +} + +@end diff --git a/Pods/JSONModel/JSONModel/JSONModel/JSONModelClassProperty.h b/Pods/JSONModel/JSONModel/JSONModel/JSONModelClassProperty.h new file mode 100644 index 0000000..67405ab --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModel/JSONModelClassProperty.h @@ -0,0 +1,48 @@ +// +// JSONModelClassProperty.h +// JSONModel +// + +#import + +/** + * **You do not need to instantiate this class yourself.** This class is used internally by JSONModel + * to inspect the declared properties of your model class. + * + * Class to contain the information, representing a class property + * It features the property's name, type, whether it's a required property, + * and (optionally) the class protocol + */ +@interface JSONModelClassProperty : NSObject + +// deprecated +@property (assign, nonatomic) BOOL isIndex DEPRECATED_ATTRIBUTE; + +/** The name of the declared property (not the ivar name) */ +@property (copy, nonatomic) NSString *name; + +/** A property class type */ +@property (assign, nonatomic) Class type; + +/** Struct name if a struct */ +@property (strong, nonatomic) NSString *structName; + +/** The name of the protocol the property conforms to (or nil) */ +@property (copy, nonatomic) NSString *protocol; + +/** If YES, it can be missing in the input data, and the input would be still valid */ +@property (assign, nonatomic) BOOL isOptional; + +/** If YES - don't call any transformers on this property's value */ +@property (assign, nonatomic) BOOL isStandardJSONType; + +/** If YES - create a mutable object for the value of the property */ +@property (assign, nonatomic) BOOL isMutable; + +/** a custom getter for this property, found in the owning model */ +@property (assign, nonatomic) SEL customGetter; + +/** custom setters for this property, found in the owning model */ +@property (strong, nonatomic) NSMutableDictionary *customSetters; + +@end diff --git a/Pods/JSONModel/JSONModel/JSONModel/JSONModelClassProperty.m b/Pods/JSONModel/JSONModel/JSONModel/JSONModelClassProperty.m new file mode 100644 index 0000000..5330c92 --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModel/JSONModelClassProperty.m @@ -0,0 +1,53 @@ +// +// JSONModelClassProperty.m +// JSONModel +// + +#import "JSONModelClassProperty.h" + +@implementation JSONModelClassProperty + +-(NSString*)description +{ + //build the properties string for the current class property + NSMutableArray* properties = [NSMutableArray arrayWithCapacity:8]; + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" + if (self.isIndex) [properties addObject:@"Index"]; +#pragma GCC diagnostic pop + + if (self.isOptional) [properties addObject:@"Optional"]; + if (self.isMutable) [properties addObject:@"Mutable"]; + if (self.isStandardJSONType) [properties addObject:@"Standard JSON type"]; + if (self.customGetter) [properties addObject:[NSString stringWithFormat: @"Getter = %@", NSStringFromSelector(self.customGetter)]]; + + if (self.customSetters) + { + NSMutableArray *setters = [NSMutableArray array]; + + for (id obj in self.customSetters.allValues) + { + SEL selector; + [obj getValue:&selector]; + [setters addObject:NSStringFromSelector(selector)]; + } + + [properties addObject:[NSString stringWithFormat: @"Setters = [%@]", [setters componentsJoinedByString:@", "]]]; + } + + NSString* propertiesString = @""; + if (properties.count>0) { + propertiesString = [NSString stringWithFormat:@"(%@)", [properties componentsJoinedByString:@", "]]; + } + + //return the name, type and additional properties + return [NSString stringWithFormat:@"@property %@%@ %@ %@", + self.type?[NSString stringWithFormat:@"%@*",self.type]:(self.structName?self.structName:@"primitive"), + self.protocol?[NSString stringWithFormat:@"<%@>", self.protocol]:@"", + self.name, + propertiesString + ]; +} + +@end diff --git a/Pods/JSONModel/JSONModel/JSONModel/JSONModelError.h b/Pods/JSONModel/JSONModel/JSONModel/JSONModelError.h new file mode 100644 index 0000000..266e6cc --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModel/JSONModelError.h @@ -0,0 +1,103 @@ +// +// JSONModelError.h +// JSONModel +// + +#import + +///////////////////////////////////////////////////////////////////////////////////////////// +typedef NS_ENUM(int, kJSONModelErrorTypes) +{ + kJSONModelErrorInvalidData = 1, + kJSONModelErrorBadResponse = 2, + kJSONModelErrorBadJSON = 3, + kJSONModelErrorModelIsInvalid = 4, + kJSONModelErrorNilInput = 5 +}; + +///////////////////////////////////////////////////////////////////////////////////////////// +/** The domain name used for the JSONModelError instances */ +extern NSString *const JSONModelErrorDomain; + +/** + * If the model JSON input misses keys that are required, check the + * userInfo dictionary of the JSONModelError instance you get back - + * under the kJSONModelMissingKeys key you will find a list of the + * names of the missing keys. + */ +extern NSString *const kJSONModelMissingKeys; + +/** + * If JSON input has a different type than expected by the model, check the + * userInfo dictionary of the JSONModelError instance you get back - + * under the kJSONModelTypeMismatch key you will find a description + * of the mismatched types. + */ +extern NSString *const kJSONModelTypeMismatch; + +/** + * If an error occurs in a nested model, check the userInfo dictionary of + * the JSONModelError instance you get back - under the kJSONModelKeyPath + * key you will find key-path at which the error occurred. + */ +extern NSString *const kJSONModelKeyPath; + +///////////////////////////////////////////////////////////////////////////////////////////// +/** + * Custom NSError subclass with shortcut methods for creating + * the common JSONModel errors + */ +@interface JSONModelError : NSError + +@property (strong, nonatomic) NSHTTPURLResponse *httpResponse; + +@property (strong, nonatomic) NSData *responseData; + +/** + * Creates a JSONModelError instance with code kJSONModelErrorInvalidData = 1 + */ ++ (id)errorInvalidDataWithMessage:(NSString *)message; + +/** + * Creates a JSONModelError instance with code kJSONModelErrorInvalidData = 1 + * @param keys a set of field names that were required, but not found in the input + */ ++ (id)errorInvalidDataWithMissingKeys:(NSSet *)keys; + +/** + * Creates a JSONModelError instance with code kJSONModelErrorInvalidData = 1 + * @param mismatchDescription description of the type mismatch that was encountered. + */ ++ (id)errorInvalidDataWithTypeMismatch:(NSString *)mismatchDescription; + +/** + * Creates a JSONModelError instance with code kJSONModelErrorBadResponse = 2 + */ ++ (id)errorBadResponse; + +/** + * Creates a JSONModelError instance with code kJSONModelErrorBadJSON = 3 + */ ++ (id)errorBadJSON; + +/** + * Creates a JSONModelError instance with code kJSONModelErrorModelIsInvalid = 4 + */ ++ (id)errorModelIsInvalid; + +/** + * Creates a JSONModelError instance with code kJSONModelErrorNilInput = 5 + */ ++ (id)errorInputIsNil; + +/** + * Creates a new JSONModelError with the same values plus information about the key-path of the error. + * Properties in the new error object are the same as those from the receiver, + * except that a new key kJSONModelKeyPath is added to the userInfo dictionary. + * This key contains the component string parameter. If the key is already present + * then the new error object has the component string prepended to the existing value. + */ +- (instancetype)errorByPrependingKeyPathComponent:(NSString *)component; + +///////////////////////////////////////////////////////////////////////////////////////////// +@end diff --git a/Pods/JSONModel/JSONModel/JSONModel/JSONModelError.m b/Pods/JSONModel/JSONModel/JSONModel/JSONModelError.m new file mode 100644 index 0000000..f357e70 --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModel/JSONModelError.m @@ -0,0 +1,82 @@ +// +// JSONModelError.m +// JSONModel +// + +#import "JSONModelError.h" + +NSString* const JSONModelErrorDomain = @"JSONModelErrorDomain"; +NSString* const kJSONModelMissingKeys = @"kJSONModelMissingKeys"; +NSString* const kJSONModelTypeMismatch = @"kJSONModelTypeMismatch"; +NSString* const kJSONModelKeyPath = @"kJSONModelKeyPath"; + +@implementation JSONModelError + ++(id)errorInvalidDataWithMessage:(NSString*)message +{ + message = [NSString stringWithFormat:@"Invalid JSON data: %@", message]; + return [JSONModelError errorWithDomain:JSONModelErrorDomain + code:kJSONModelErrorInvalidData + userInfo:@{NSLocalizedDescriptionKey:message}]; +} + ++(id)errorInvalidDataWithMissingKeys:(NSSet *)keys +{ + return [JSONModelError errorWithDomain:JSONModelErrorDomain + code:kJSONModelErrorInvalidData + userInfo:@{NSLocalizedDescriptionKey:@"Invalid JSON data. Required JSON keys are missing from the input. Check the error user information.",kJSONModelMissingKeys:[keys allObjects]}]; +} + ++(id)errorInvalidDataWithTypeMismatch:(NSString*)mismatchDescription +{ + return [JSONModelError errorWithDomain:JSONModelErrorDomain + code:kJSONModelErrorInvalidData + userInfo:@{NSLocalizedDescriptionKey:@"Invalid JSON data. The JSON type mismatches the expected type. Check the error user information.",kJSONModelTypeMismatch:mismatchDescription}]; +} + ++(id)errorBadResponse +{ + return [JSONModelError errorWithDomain:JSONModelErrorDomain + code:kJSONModelErrorBadResponse + userInfo:@{NSLocalizedDescriptionKey:@"Bad network response. Probably the JSON URL is unreachable."}]; +} + ++(id)errorBadJSON +{ + return [JSONModelError errorWithDomain:JSONModelErrorDomain + code:kJSONModelErrorBadJSON + userInfo:@{NSLocalizedDescriptionKey:@"Malformed JSON. Check the JSONModel data input."}]; +} + ++(id)errorModelIsInvalid +{ + return [JSONModelError errorWithDomain:JSONModelErrorDomain + code:kJSONModelErrorModelIsInvalid + userInfo:@{NSLocalizedDescriptionKey:@"Model does not validate. The custom validation for the input data failed."}]; +} + ++(id)errorInputIsNil +{ + return [JSONModelError errorWithDomain:JSONModelErrorDomain + code:kJSONModelErrorNilInput + userInfo:@{NSLocalizedDescriptionKey:@"Initializing model with nil input object."}]; +} + +- (instancetype)errorByPrependingKeyPathComponent:(NSString*)component +{ + // Create a mutable copy of the user info so that we can add to it and update it + NSMutableDictionary* userInfo = [self.userInfo mutableCopy]; + + // Create or update the key-path + NSString* existingPath = userInfo[kJSONModelKeyPath]; + NSString* separator = [existingPath hasPrefix:@"["] ? @"" : @"."; + NSString* updatedPath = (existingPath == nil) ? component : [component stringByAppendingFormat:@"%@%@", separator, existingPath]; + userInfo[kJSONModelKeyPath] = updatedPath; + + // Create the new error + return [JSONModelError errorWithDomain:self.domain + code:self.code + userInfo:[NSDictionary dictionaryWithDictionary:userInfo]]; +} + +@end diff --git a/Pods/JSONModel/JSONModel/JSONModelLib.h b/Pods/JSONModel/JSONModel/JSONModelLib.h new file mode 100644 index 0000000..564ca46 --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModelLib.h @@ -0,0 +1,19 @@ +// +// JSONModelLib.h +// JSONModel +// + +#import + +// core +#import "JSONModel.h" +#import "JSONModelError.h" + +// transformations +#import "JSONValueTransformer.h" +#import "JSONKeyMapper.h" + +// networking (deprecated) +#import "JSONHTTPClient.h" +#import "JSONModel+networking.h" +#import "JSONAPI.h" diff --git a/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONAPI.h b/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONAPI.h new file mode 100644 index 0000000..30a8743 --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONAPI.h @@ -0,0 +1,19 @@ +// +// JSONAPI.h +// JSONModel +// + +#import +#import "JSONHTTPClient.h" + +DEPRECATED_ATTRIBUTE +@interface JSONAPI : NSObject + ++ (void)setAPIBaseURLWithString:(NSString *)base DEPRECATED_ATTRIBUTE; ++ (void)setContentType:(NSString *)ctype DEPRECATED_ATTRIBUTE; ++ (void)getWithPath:(NSString *)path andParams:(NSDictionary *)params completion:(JSONObjectBlock)completeBlock DEPRECATED_ATTRIBUTE; ++ (void)postWithPath:(NSString *)path andParams:(NSDictionary *)params completion:(JSONObjectBlock)completeBlock DEPRECATED_ATTRIBUTE; ++ (void)rpcWithMethodName:(NSString *)method andArguments:(NSArray *)args completion:(JSONObjectBlock)completeBlock DEPRECATED_ATTRIBUTE; ++ (void)rpc2WithMethodName:(NSString *)method andParams:(id)params completion:(JSONObjectBlock)completeBlock DEPRECATED_ATTRIBUTE; + +@end diff --git a/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONAPI.m b/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONAPI.m new file mode 100644 index 0000000..a7e3326 --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONAPI.m @@ -0,0 +1,145 @@ +// +// JSONAPI.m +// JSONModel +// + +#import "JSONAPI.h" + +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#pragma GCC diagnostic ignored "-Wdeprecated-implementations" + +#pragma mark - helper error model class +@interface JSONAPIRPCErrorModel: JSONModel +@property (assign, nonatomic) int code; +@property (strong, nonatomic) NSString* message; +@property (strong, nonatomic) id data; +@end + +#pragma mark - static variables + +static JSONAPI* sharedInstance = nil; + +static long jsonRpcId = 0; + +#pragma mark - JSONAPI() private interface + +@interface JSONAPI () +@property (strong, nonatomic) NSString* baseURLString; +@end + +#pragma mark - JSONAPI implementation + +@implementation JSONAPI + +#pragma mark - initialize + ++(void)initialize +{ + static dispatch_once_t once; + dispatch_once(&once, ^{ + sharedInstance = [[JSONAPI alloc] init]; + }); +} + +#pragma mark - api config methods + ++(void)setAPIBaseURLWithString:(NSString*)base +{ + sharedInstance.baseURLString = base; +} + ++(void)setContentType:(NSString*)ctype +{ + [JSONHTTPClient setRequestContentType: ctype]; +} + +#pragma mark - GET methods ++(void)getWithPath:(NSString*)path andParams:(NSDictionary*)params completion:(JSONObjectBlock)completeBlock +{ + NSString* fullURL = [NSString stringWithFormat:@"%@%@", sharedInstance.baseURLString, path]; + + [JSONHTTPClient getJSONFromURLWithString: fullURL params:params completion:^(NSDictionary *json, JSONModelError *e) { + completeBlock(json, e); + }]; +} + +#pragma mark - POST methods ++(void)postWithPath:(NSString*)path andParams:(NSDictionary*)params completion:(JSONObjectBlock)completeBlock +{ + NSString* fullURL = [NSString stringWithFormat:@"%@%@", sharedInstance.baseURLString, path]; + + [JSONHTTPClient postJSONFromURLWithString: fullURL params:params completion:^(NSDictionary *json, JSONModelError *e) { + completeBlock(json, e); + }]; +} + +#pragma mark - RPC methods ++(void)__rpcRequestWithObject:(id)jsonObject completion:(JSONObjectBlock)completeBlock +{ + + NSData* jsonRequestData = [NSJSONSerialization dataWithJSONObject:jsonObject + options:kNilOptions + error:nil]; + NSString* jsonRequestString = [[NSString alloc] initWithData:jsonRequestData encoding: NSUTF8StringEncoding]; + + NSAssert(sharedInstance.baseURLString, @"API base URL not set"); + [JSONHTTPClient postJSONFromURLWithString: sharedInstance.baseURLString + bodyString: jsonRequestString + completion:^(NSDictionary *json, JSONModelError* e) { + + if (completeBlock) { + //handle the rpc response + NSDictionary* result = json[@"result"]; + + if (!result) { + JSONAPIRPCErrorModel* error = [[JSONAPIRPCErrorModel alloc] initWithDictionary:json[@"error"] error:nil]; + if (error) { + //custom server error + if (!error.message) error.message = @"Generic json rpc error"; + e = [JSONModelError errorWithDomain:JSONModelErrorDomain + code:error.code + userInfo: @{ NSLocalizedDescriptionKey : error.message}]; + } else { + //generic error + e = [JSONModelError errorBadResponse]; + } + } + + //invoke the callback + completeBlock(result, e); + } + }]; +} + ++(void)rpcWithMethodName:(NSString*)method andArguments:(NSArray*)args completion:(JSONObjectBlock)completeBlock +{ + NSAssert(method, @"No method specified"); + if (!args) args = @[]; + + [self __rpcRequestWithObject:@{ + //rpc 1.0 + @"id": @(++jsonRpcId), + @"params": args, + @"method": method + } completion:completeBlock]; +} + ++(void)rpc2WithMethodName:(NSString*)method andParams:(id)params completion:(JSONObjectBlock)completeBlock +{ + NSAssert(method, @"No method specified"); + if (!params) params = @[]; + + [self __rpcRequestWithObject:@{ + //rpc 2.0 + @"jsonrpc": @"2.0", + @"id": @(++jsonRpcId), + @"params": params, + @"method": method + } completion:completeBlock]; +} + +@end + +#pragma mark - helper rpc error model class implementation +@implementation JSONAPIRPCErrorModel +@end diff --git a/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONHTTPClient.h b/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONHTTPClient.h new file mode 100644 index 0000000..0f47cef --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONHTTPClient.h @@ -0,0 +1,33 @@ +// +// JSONModelHTTPClient.h +// JSONModel +// + +#import "JSONModel.h" + +extern NSString *const kHTTPMethodGET DEPRECATED_ATTRIBUTE; +extern NSString *const kHTTPMethodPOST DEPRECATED_ATTRIBUTE; +extern NSString *const kContentTypeAutomatic DEPRECATED_ATTRIBUTE; +extern NSString *const kContentTypeJSON DEPRECATED_ATTRIBUTE; +extern NSString *const kContentTypeWWWEncoded DEPRECATED_ATTRIBUTE; + +typedef void (^JSONObjectBlock)(id json, JSONModelError *err) DEPRECATED_ATTRIBUTE; + +DEPRECATED_ATTRIBUTE +@interface JSONHTTPClient : NSObject + ++ (NSMutableDictionary *)requestHeaders DEPRECATED_ATTRIBUTE; ++ (void)setDefaultTextEncoding:(NSStringEncoding)encoding DEPRECATED_ATTRIBUTE; ++ (void)setCachingPolicy:(NSURLRequestCachePolicy)policy DEPRECATED_ATTRIBUTE; ++ (void)setTimeoutInSeconds:(int)seconds DEPRECATED_ATTRIBUTE; ++ (void)setRequestContentType:(NSString *)contentTypeString DEPRECATED_ATTRIBUTE; ++ (void)getJSONFromURLWithString:(NSString *)urlString completion:(JSONObjectBlock)completeBlock DEPRECATED_ATTRIBUTE; ++ (void)getJSONFromURLWithString:(NSString *)urlString params:(NSDictionary *)params completion:(JSONObjectBlock)completeBlock DEPRECATED_ATTRIBUTE; ++ (void)JSONFromURLWithString:(NSString *)urlString method:(NSString *)method params:(NSDictionary *)params orBodyString:(NSString *)bodyString completion:(JSONObjectBlock)completeBlock DEPRECATED_ATTRIBUTE; ++ (void)JSONFromURLWithString:(NSString *)urlString method:(NSString *)method params:(NSDictionary *)params orBodyString:(NSString *)bodyString headers:(NSDictionary *)headers completion:(JSONObjectBlock)completeBlock DEPRECATED_ATTRIBUTE; ++ (void)JSONFromURLWithString:(NSString *)urlString method:(NSString *)method params:(NSDictionary *)params orBodyData:(NSData *)bodyData headers:(NSDictionary *)headers completion:(JSONObjectBlock)completeBlock DEPRECATED_ATTRIBUTE; ++ (void)postJSONFromURLWithString:(NSString *)urlString params:(NSDictionary *)params completion:(JSONObjectBlock)completeBlock DEPRECATED_ATTRIBUTE; ++ (void)postJSONFromURLWithString:(NSString *)urlString bodyString:(NSString *)bodyString completion:(JSONObjectBlock)completeBlock DEPRECATED_ATTRIBUTE; ++ (void)postJSONFromURLWithString:(NSString *)urlString bodyData:(NSData *)bodyData completion:(JSONObjectBlock)completeBlock DEPRECATED_ATTRIBUTE; + +@end diff --git a/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONHTTPClient.m b/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONHTTPClient.m new file mode 100644 index 0000000..6c72dc5 --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONHTTPClient.m @@ -0,0 +1,361 @@ +// +// JSONModelHTTPClient.m +// JSONModel +// + +#import "JSONHTTPClient.h" + +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#pragma GCC diagnostic ignored "-Wdeprecated-implementations" + +typedef void (^RequestResultBlock)(NSData *data, JSONModelError *error); + +#pragma mark - constants +NSString* const kHTTPMethodGET = @"GET"; +NSString* const kHTTPMethodPOST = @"POST"; + +NSString* const kContentTypeAutomatic = @"jsonmodel/automatic"; +NSString* const kContentTypeJSON = @"application/json"; +NSString* const kContentTypeWWWEncoded = @"application/x-www-form-urlencoded"; + +#pragma mark - static variables + +/** + * Defaults for HTTP requests + */ +static NSStringEncoding defaultTextEncoding = NSUTF8StringEncoding; +static NSURLRequestCachePolicy defaultCachePolicy = NSURLRequestReloadIgnoringLocalCacheData; + +static int defaultTimeoutInSeconds = 60; + +/** + * Custom HTTP headers to send over with *each* request + */ +static NSMutableDictionary* requestHeaders = nil; + +/** + * Default request content type + */ +static NSString* requestContentType = nil; + +#pragma mark - implementation +@implementation JSONHTTPClient + +#pragma mark - initialization ++(void)initialize +{ + static dispatch_once_t once; + dispatch_once(&once, ^{ + requestHeaders = [NSMutableDictionary dictionary]; + requestContentType = kContentTypeAutomatic; + }); +} + +#pragma mark - configuration methods ++(NSMutableDictionary*)requestHeaders +{ + return requestHeaders; +} + ++(void)setDefaultTextEncoding:(NSStringEncoding)encoding +{ + defaultTextEncoding = encoding; +} + ++(void)setCachingPolicy:(NSURLRequestCachePolicy)policy +{ + defaultCachePolicy = policy; +} + ++(void)setTimeoutInSeconds:(int)seconds +{ + defaultTimeoutInSeconds = seconds; +} + ++(void)setRequestContentType:(NSString*)contentTypeString +{ + requestContentType = contentTypeString; +} + +#pragma mark - helper methods ++(NSString*)contentTypeForRequestString:(NSString*)requestString +{ + //fetch the charset name from the default string encoding + NSString* contentType = requestContentType; + + if (requestString.length>0 && [contentType isEqualToString:kContentTypeAutomatic]) { + //check for "eventual" JSON array or dictionary + NSString* firstAndLastChar = [NSString stringWithFormat:@"%@%@", + [requestString substringToIndex:1], + [requestString substringFromIndex: requestString.length -1] + ]; + + if ([firstAndLastChar isEqualToString:@"{}"] || [firstAndLastChar isEqualToString:@"[]"]) { + //guessing for a JSON request + contentType = kContentTypeJSON; + } else { + //fallback to www form encoded params + contentType = kContentTypeWWWEncoded; + } + } + + //type is set, just add charset + NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)); + return [NSString stringWithFormat:@"%@; charset=%@", contentType, charset]; +} + ++(NSString*)urlEncode:(id)value +{ + //make sure param is a string + if ([value isKindOfClass:[NSNumber class]]) { + value = [(NSNumber*)value stringValue]; + } + + NSAssert([value isKindOfClass:[NSString class]], @"request parameters can be only of NSString or NSNumber classes. '%@' is of class %@.", value, [value class]); + + NSString *str = (NSString *)value; + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0 || __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_9 + return [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; + +#else + return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( + NULL, + (__bridge CFStringRef)str, + NULL, + (CFStringRef)@"!*'();:@&=+$,/?%#[]", + kCFStringEncodingUTF8)); +#endif +} + +#pragma mark - networking worker methods ++(void)requestDataFromURL:(NSURL*)url method:(NSString*)method requestBody:(NSData*)bodyData headers:(NSDictionary*)headers handler:(RequestResultBlock)handler +{ + NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: url + cachePolicy: defaultCachePolicy + timeoutInterval: defaultTimeoutInSeconds]; + [request setHTTPMethod:method]; + + if ([requestContentType isEqualToString:kContentTypeAutomatic]) { + //automatic content type + if (bodyData) { + NSString *bodyString = [[NSString alloc] initWithData:bodyData encoding:NSUTF8StringEncoding]; + [request setValue: [self contentTypeForRequestString: bodyString] forHTTPHeaderField:@"Content-type"]; + } + } else { + //user set content type + [request setValue: requestContentType forHTTPHeaderField:@"Content-type"]; + } + + //add all the custom headers defined + for (NSString* key in [requestHeaders allKeys]) { + [request setValue:requestHeaders[key] forHTTPHeaderField:key]; + } + + //add the custom headers + for (NSString* key in [headers allKeys]) { + [request setValue:headers[key] forHTTPHeaderField:key]; + } + + if (bodyData) { + [request setHTTPBody: bodyData]; + [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)bodyData.length] forHTTPHeaderField:@"Content-Length"]; + } + + void (^completionHandler)(NSData *, NSURLResponse *, NSError *) = ^(NSData *data, NSURLResponse *origResponse, NSError *origError) { + NSHTTPURLResponse *response = (NSHTTPURLResponse *)origResponse; + JSONModelError *error = nil; + + //convert an NSError to a JSONModelError + if (origError) { + error = [JSONModelError errorWithDomain:origError.domain code:origError.code userInfo:origError.userInfo]; + } + + //special case for http error code 401 + if (error.code == NSURLErrorUserCancelledAuthentication) { + response = [[NSHTTPURLResponse alloc] initWithURL:url statusCode:401 HTTPVersion:@"HTTP/1.1" headerFields:@{}]; + } + + //if not OK status set the err to a JSONModelError instance + if (!error && (response.statusCode >= 300 || response.statusCode < 200)) { + error = [JSONModelError errorBadResponse]; + } + + //if there was an error, assign the response to the JSONModel instance + if (error) { + error.httpResponse = [response copy]; + } + + //empty respone, return nil instead + if (!data.length) { + data = nil; + } + + handler(data, error); + }; + + //fire the request + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0 || __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_10 + NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:completionHandler]; + [task resume]; +#else + NSOperationQueue *queue = [NSOperationQueue new]; + + [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { + completionHandler(data, response, error); + }]; +#endif +} + ++(void)requestDataFromURL:(NSURL*)url method:(NSString*)method params:(NSDictionary*)params headers:(NSDictionary*)headers handler:(RequestResultBlock)handler +{ + //create the request body + NSMutableString* paramsString = nil; + + if (params) { + //build a simple url encoded param string + paramsString = [NSMutableString stringWithString:@""]; + for (NSString* key in [[params allKeys] sortedArrayUsingSelector:@selector(compare:)]) { + [paramsString appendFormat:@"%@=%@&", key, [self urlEncode:params[key]] ]; + } + if ([paramsString hasSuffix:@"&"]) { + paramsString = [[NSMutableString alloc] initWithString: [paramsString substringToIndex: paramsString.length-1]]; + } + } + + //set the request params + if ([method isEqualToString:kHTTPMethodGET] && params) { + + //add GET params to the query string + url = [NSURL URLWithString:[NSString stringWithFormat: @"%@%@%@", + [url absoluteString], + [url query] ? @"&" : @"?", + paramsString + ]]; + } + + //call the more general synq request method + [self requestDataFromURL: url + method: method + requestBody: [method isEqualToString:kHTTPMethodPOST]?[paramsString dataUsingEncoding:NSUTF8StringEncoding]:nil + headers: headers + handler:handler]; +} + +#pragma mark - Async network request ++(void)JSONFromURLWithString:(NSString*)urlString method:(NSString*)method params:(NSDictionary*)params orBodyString:(NSString*)bodyString completion:(JSONObjectBlock)completeBlock +{ + [self JSONFromURLWithString:urlString + method:method + params:params + orBodyString:bodyString + headers:nil + completion:completeBlock]; +} + ++(void)JSONFromURLWithString:(NSString *)urlString method:(NSString *)method params:(NSDictionary *)params orBodyString:(NSString *)bodyString headers:(NSDictionary *)headers completion:(JSONObjectBlock)completeBlock +{ + [self JSONFromURLWithString:urlString + method:method + params:params + orBodyData:[bodyString dataUsingEncoding:NSUTF8StringEncoding] + headers:headers + completion:completeBlock]; +} + ++(void)JSONFromURLWithString:(NSString*)urlString method:(NSString*)method params:(NSDictionary *)params orBodyData:(NSData*)bodyData headers:(NSDictionary*)headers completion:(JSONObjectBlock)completeBlock +{ + RequestResultBlock handler = ^(NSData *responseData, JSONModelError *error) { + id jsonObject = nil; + + //step 3: if there's no response so far, return a basic error + if (!responseData && !error) { + //check for false response, but no network error + error = [JSONModelError errorBadResponse]; + } + + //step 4: if there's a response at this and no errors, convert to object + if (error==nil) { + // Note: it is possible to have a valid response with empty response data (204 No Content). + // So only create the JSON object if there is some response data. + if(responseData.length > 0) + { + //convert to an object + jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error]; + } + } + //step 4.5: cover an edge case in which meaningful content is return along an error HTTP status code + else if (error && responseData && jsonObject==nil) { + //try to get the JSON object, while preserving the original error object + jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil]; + //keep responseData just in case it contains error information + error.responseData = responseData; + } + + //step 5: invoke the complete block + dispatch_async(dispatch_get_main_queue(), ^{ + if (completeBlock) { + completeBlock(jsonObject, error); + } + }); + }; + + NSURL *url = [NSURL URLWithString:urlString]; + + if (bodyData) { + [self requestDataFromURL:url method:method requestBody:bodyData headers:headers handler:handler]; + } else { + [self requestDataFromURL:url method:method params:params headers:headers handler:handler]; + } +} + +#pragma mark - request aliases ++(void)getJSONFromURLWithString:(NSString*)urlString completion:(JSONObjectBlock)completeBlock +{ + [self JSONFromURLWithString:urlString method:kHTTPMethodGET + params:nil + orBodyString:nil completion:^(id json, JSONModelError* e) { + if (completeBlock) completeBlock(json, e); + }]; +} + ++(void)getJSONFromURLWithString:(NSString*)urlString params:(NSDictionary*)params completion:(JSONObjectBlock)completeBlock +{ + [self JSONFromURLWithString:urlString method:kHTTPMethodGET + params:params + orBodyString:nil completion:^(id json, JSONModelError* e) { + if (completeBlock) completeBlock(json, e); + }]; +} + ++(void)postJSONFromURLWithString:(NSString*)urlString params:(NSDictionary*)params completion:(JSONObjectBlock)completeBlock +{ + [self JSONFromURLWithString:urlString method:kHTTPMethodPOST + params:params + orBodyString:nil completion:^(id json, JSONModelError* e) { + if (completeBlock) completeBlock(json, e); + }]; + +} + ++(void)postJSONFromURLWithString:(NSString*)urlString bodyString:(NSString*)bodyString completion:(JSONObjectBlock)completeBlock +{ + [self JSONFromURLWithString:urlString method:kHTTPMethodPOST + params:nil + orBodyString:bodyString completion:^(id json, JSONModelError* e) { + if (completeBlock) completeBlock(json, e); + }]; +} + ++(void)postJSONFromURLWithString:(NSString*)urlString bodyData:(NSData*)bodyData completion:(JSONObjectBlock)completeBlock +{ + [self JSONFromURLWithString:urlString method:kHTTPMethodPOST + params:nil + orBodyString:[[NSString alloc] initWithData:bodyData encoding:defaultTextEncoding] + completion:^(id json, JSONModelError* e) { + if (completeBlock) completeBlock(json, e); + }]; +} + +@end diff --git a/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONModel+networking.h b/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONModel+networking.h new file mode 100644 index 0000000..444f26d --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONModel+networking.h @@ -0,0 +1,18 @@ +// +// JSONModel+networking.h +// JSONModel +// + +#import "JSONModel.h" +#import "JSONHTTPClient.h" + +typedef void (^JSONModelBlock)(id model, JSONModelError *err) DEPRECATED_ATTRIBUTE; + +@interface JSONModel (Networking) + +@property (assign, nonatomic) BOOL isLoading DEPRECATED_ATTRIBUTE; +- (instancetype)initFromURLWithString:(NSString *)urlString completion:(JSONModelBlock)completeBlock DEPRECATED_ATTRIBUTE; ++ (void)getModelFromURLWithString:(NSString *)urlString completion:(JSONModelBlock)completeBlock DEPRECATED_ATTRIBUTE; ++ (void)postModel:(JSONModel *)post toURLWithString:(NSString *)urlString completion:(JSONModelBlock)completeBlock DEPRECATED_ATTRIBUTE; + +@end diff --git a/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONModel+networking.m b/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONModel+networking.m new file mode 100644 index 0000000..b3e0aa4 --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModelNetworking/JSONModel+networking.m @@ -0,0 +1,101 @@ +// +// JSONModel+networking.m +// JSONModel +// + +#import "JSONModel+networking.h" +#import "JSONHTTPClient.h" + +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#pragma GCC diagnostic ignored "-Wdeprecated-implementations" + +BOOL _isLoading; + +@implementation JSONModel(Networking) + +@dynamic isLoading; + +-(BOOL)isLoading +{ + return _isLoading; +} + +-(void)setIsLoading:(BOOL)isLoading +{ + _isLoading = isLoading; +} + +-(instancetype)initFromURLWithString:(NSString *)urlString completion:(JSONModelBlock)completeBlock +{ + id placeholder = [super init]; + __block id blockSelf = self; + + if (placeholder) { + //initialization + self.isLoading = YES; + + [JSONHTTPClient getJSONFromURLWithString:urlString + completion:^(NSDictionary *json, JSONModelError* e) { + + JSONModelError* initError = nil; + blockSelf = [self initWithDictionary:json error:&initError]; + + if (completeBlock) { + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{ + completeBlock(blockSelf, e?e:initError ); + }); + } + + self.isLoading = NO; + + }]; + } + return placeholder; +} + ++ (void)getModelFromURLWithString:(NSString*)urlString completion:(JSONModelBlock)completeBlock +{ + [JSONHTTPClient getJSONFromURLWithString:urlString + completion:^(NSDictionary* jsonDict, JSONModelError* err) + { + JSONModel* model = nil; + + if(err == nil) + { + model = [[self alloc] initWithDictionary:jsonDict error:&err]; + } + + if(completeBlock != nil) + { + dispatch_async(dispatch_get_main_queue(), ^ + { + completeBlock(model, err); + }); + } + }]; +} + ++ (void)postModel:(JSONModel*)post toURLWithString:(NSString*)urlString completion:(JSONModelBlock)completeBlock +{ + [JSONHTTPClient postJSONFromURLWithString:urlString + bodyString:[post toJSONString] + completion:^(NSDictionary* jsonDict, JSONModelError* err) + { + JSONModel* model = nil; + + if(err == nil) + { + model = [[self alloc] initWithDictionary:jsonDict error:&err]; + } + + if(completeBlock != nil) + { + dispatch_async(dispatch_get_main_queue(), ^ + { + completeBlock(model, err); + }); + } + }]; +} + +@end diff --git a/Pods/JSONModel/JSONModel/JSONModelTransformations/JSONKeyMapper.h b/Pods/JSONModel/JSONModel/JSONModelTransformations/JSONKeyMapper.h new file mode 100644 index 0000000..35e44a8 --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModelTransformations/JSONKeyMapper.h @@ -0,0 +1,96 @@ +// +// JSONKeyMapper.h +// JSONModel +// + +#import + +typedef NSString *(^JSONModelKeyMapBlock)(NSString *keyName); + +/** + * **You won't need to create or store instances of this class yourself.** If you want your model + * to have different property names than the JSON feed keys, look below on how to + * make your model use a key mapper. + * + * For example if you consume JSON from twitter + * you get back underscore_case style key names. For example: + * + *

"profile_sidebar_border_color": "0094C2",
+ * "profile_background_tile": false,
+ * + * To comply with Obj-C accepted camelCase property naming for your classes, + * you need to provide mapping between JSON keys and ObjC property names. + * + * In your model overwrite the + (JSONKeyMapper *)keyMapper method and provide a JSONKeyMapper + * instance to convert the key names for your model. + * + * If you need custom mapping it's as easy as: + *
+ * + (JSONKeyMapper *)keyMapper {
+ *   return [[JSONKeyMapper alloc] initWithDictionary:@{@"crazy_JSON_name":@"myCamelCaseName"}];
+ * }
+ * 
+ * In case you want to handle underscore_case, **use the predefined key mapper**, like so: + *
+ * + (JSONKeyMapper *)keyMapper {
+ *   return [JSONKeyMapper mapperFromUnderscoreCaseToCamelCase];
+ * }
+ * 
+ */ +@interface JSONKeyMapper : NSObject + +// deprecated +@property (readonly, nonatomic) JSONModelKeyMapBlock JSONToModelKeyBlock DEPRECATED_ATTRIBUTE; +- (NSString *)convertValue:(NSString *)value isImportingToModel:(BOOL)importing DEPRECATED_MSG_ATTRIBUTE("use convertValue:"); +- (instancetype)initWithDictionary:(NSDictionary *)map DEPRECATED_MSG_ATTRIBUTE("use initWithModelToJSONDictionary:"); +- (instancetype)initWithJSONToModelBlock:(JSONModelKeyMapBlock)toModel modelToJSONBlock:(JSONModelKeyMapBlock)toJSON DEPRECATED_MSG_ATTRIBUTE("use initWithModelToJSONBlock:"); ++ (instancetype)mapper:(JSONKeyMapper *)baseKeyMapper withExceptions:(NSDictionary *)exceptions DEPRECATED_MSG_ATTRIBUTE("use baseMapper:withModelToJSONExceptions:"); ++ (instancetype)mapperFromUnderscoreCaseToCamelCase DEPRECATED_MSG_ATTRIBUTE("use mapperForSnakeCase:"); ++ (instancetype)mapperFromUpperCaseToLowerCase DEPRECATED_ATTRIBUTE; + +/** @name Name converters */ +/** Block, which takes in a property name and converts it to the corresponding JSON key name */ +@property (readonly, nonatomic) JSONModelKeyMapBlock modelToJSONKeyBlock; + +/** Combined converter method + * @param value the source name + * @return JSONKeyMapper instance + */ +- (NSString *)convertValue:(NSString *)value; + +/** @name Creating a key mapper */ + +/** + * Creates a JSONKeyMapper instance, based on the block you provide this initializer. + * The parameter takes in a JSONModelKeyMapBlock block: + *
NSString *(^JSONModelKeyMapBlock)(NSString *keyName)
+ * The block takes in a string and returns the transformed (if at all) string. + * @param toJSON transforms your model property name to a JSON key + */ +- (instancetype)initWithModelToJSONBlock:(JSONModelKeyMapBlock)toJSON; + +/** + * Creates a JSONKeyMapper instance, based on the mapping you provide. + * Use your JSONModel property names as keys, and the JSON key names as values. + * @param toJSON map dictionary, in the format:
@{@"myCamelCaseName":@"crazy_JSON_name"}
+ * @return JSONKeyMapper instance + */ +- (instancetype)initWithModelToJSONDictionary:(NSDictionary *)toJSON; + +/** + * Given a camelCase model property, this mapper finds JSON keys using the snake_case equivalent. + */ ++ (instancetype)mapperForSnakeCase; + +/** + * Given a camelCase model property, this mapper finds JSON keys using the TitleCase equivalent. + */ ++ (instancetype)mapperForTitleCase; + +/** + * Creates a JSONKeyMapper based on a built-in JSONKeyMapper, with specific exceptions. + * Use your JSONModel property names as keys, and the JSON key names as values. + */ ++ (instancetype)baseMapper:(JSONKeyMapper *)baseKeyMapper withModelToJSONExceptions:(NSDictionary *)toJSON; + +@end diff --git a/Pods/JSONModel/JSONModel/JSONModelTransformations/JSONKeyMapper.m b/Pods/JSONModel/JSONModel/JSONModelTransformations/JSONKeyMapper.m new file mode 100644 index 0000000..e7f01d8 --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModelTransformations/JSONKeyMapper.m @@ -0,0 +1,178 @@ +// +// JSONKeyMapper.m +// JSONModel +// + +#import "JSONKeyMapper.h" +#import + +@interface JSONKeyMapper() +@property (nonatomic, strong) NSMutableDictionary *toJSONMap; +@property (nonatomic, assign) OSSpinLock lock; +@end + +@implementation JSONKeyMapper + +- (instancetype)init +{ + if (!(self = [super init])) + return nil; + + _toJSONMap = [NSMutableDictionary new]; + + return self; +} + +- (instancetype)initWithJSONToModelBlock:(JSONModelKeyMapBlock)toModel modelToJSONBlock:(JSONModelKeyMapBlock)toJSON +{ + return [self initWithModelToJSONBlock:toJSON]; +} + +- (instancetype)initWithModelToJSONBlock:(JSONModelKeyMapBlock)toJSON +{ + if (!(self = [self init])) + return nil; + + __weak JSONKeyMapper *weakSelf = self; + + _modelToJSONKeyBlock = ^NSString *(NSString *keyName) + { + __strong JSONKeyMapper *strongSelf = weakSelf; + + id cached = strongSelf.toJSONMap[keyName]; + + if (cached == [NSNull null]) + return nil; + + if (cached) + return strongSelf.toJSONMap[keyName]; + + NSString *result = toJSON(keyName); + + OSSpinLockLock(&strongSelf->_lock); + strongSelf.toJSONMap[keyName] = result ? result : [NSNull null]; + OSSpinLockUnlock(&strongSelf->_lock); + + return result; + }; + + return self; +} + +- (instancetype)initWithDictionary:(NSDictionary *)map +{ + NSDictionary *toJSON = [JSONKeyMapper swapKeysAndValuesInDictionary:map]; + + return [self initWithModelToJSONDictionary:toJSON]; +} + +- (instancetype)initWithModelToJSONDictionary:(NSDictionary *)toJSON +{ + if (!(self = [super init])) + return nil; + + _modelToJSONKeyBlock = ^NSString *(NSString *keyName) + { + return [toJSON valueForKeyPath:keyName] ?: keyName; + }; + + return self; +} + ++ (NSDictionary *)swapKeysAndValuesInDictionary:(NSDictionary *)dictionary +{ + NSArray *keys = dictionary.allKeys; + NSArray *values = [dictionary objectsForKeys:keys notFoundMarker:[NSNull null]]; + + return [NSDictionary dictionaryWithObjects:keys forKeys:values]; +} + +- (NSString *)convertValue:(NSString *)value isImportingToModel:(BOOL)importing +{ + return [self convertValue:value]; +} + +- (NSString *)convertValue:(NSString *)value +{ + return _modelToJSONKeyBlock(value); +} + ++ (instancetype)mapperFromUnderscoreCaseToCamelCase +{ + return [self mapperForSnakeCase]; +} + ++ (instancetype)mapperForSnakeCase +{ + return [[self alloc] initWithModelToJSONBlock:^NSString *(NSString *keyName) + { + NSMutableString *result = [NSMutableString stringWithString:keyName]; + NSRange range; + + // handle upper case chars + range = [result rangeOfCharacterFromSet:[NSCharacterSet uppercaseLetterCharacterSet]]; + while (range.location != NSNotFound) + { + NSString *lower = [result substringWithRange:range].lowercaseString; + [result replaceCharactersInRange:range withString:[NSString stringWithFormat:@"_%@", lower]]; + range = [result rangeOfCharacterFromSet:[NSCharacterSet uppercaseLetterCharacterSet]]; + } + + // handle numbers + range = [result rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]]; + while (range.location != NSNotFound) + { + NSRange end = [result rangeOfString:@"\\D" options:NSRegularExpressionSearch range:NSMakeRange(range.location, result.length - range.location)]; + + // spans to the end of the key name + if (end.location == NSNotFound) + end = NSMakeRange(result.length, 1); + + NSRange replaceRange = NSMakeRange(range.location, end.location - range.location); + NSString *digits = [result substringWithRange:replaceRange]; + [result replaceCharactersInRange:replaceRange withString:[NSString stringWithFormat:@"_%@", digits]]; + range = [result rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet] options:0 range:NSMakeRange(end.location + 1, result.length - end.location - 1)]; + } + + return result; + }]; +} + ++ (instancetype)mapperForTitleCase +{ + return [[self alloc] initWithModelToJSONBlock:^NSString *(NSString *keyName) + { + return [keyName stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[keyName substringToIndex:1].uppercaseString]; + }]; +} + ++ (instancetype)mapperFromUpperCaseToLowerCase +{ + return [[self alloc] initWithModelToJSONBlock:^NSString *(NSString *keyName) + { + return keyName.uppercaseString; + }]; +} + ++ (instancetype)mapper:(JSONKeyMapper *)baseKeyMapper withExceptions:(NSDictionary *)exceptions +{ + NSDictionary *toJSON = [JSONKeyMapper swapKeysAndValuesInDictionary:exceptions]; + + return [self baseMapper:baseKeyMapper withModelToJSONExceptions:toJSON]; +} + ++ (instancetype)baseMapper:(JSONKeyMapper *)baseKeyMapper withModelToJSONExceptions:(NSDictionary *)toJSON +{ + return [[self alloc] initWithModelToJSONBlock:^NSString *(NSString *keyName) + { + if (!keyName) + return nil; + + if (toJSON[keyName]) + return toJSON[keyName]; + + return baseKeyMapper.modelToJSONKeyBlock(keyName); + }]; +} + +@end diff --git a/Pods/JSONModel/JSONModel/JSONModelTransformations/JSONValueTransformer.h b/Pods/JSONModel/JSONModel/JSONModelTransformations/JSONValueTransformer.h new file mode 100644 index 0000000..7dd585c --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModelTransformations/JSONValueTransformer.h @@ -0,0 +1,209 @@ +// +// JSONValueTransformer.h +// JSONModel +// + +#import + +///////////////////////////////////////////////////////////////////////////////////////////// + +#pragma mark - extern definitions +/** + * Boolean function to check for null values. Handy when you need to both check + * for nil and [NSNUll null] + */ +extern BOOL isNull(id value); + +///////////////////////////////////////////////////////////////////////////////////////////// + +#pragma mark - JSONValueTransformer interface +/** + * **You don't need to call methods of this class manually.** + * + * Class providing methods to transform values from one class to another. + * You are given a number of built-in transformers, but you are encouraged to + * extend this class with your own categories to add further value transformers. + * Just few examples of what can you add to JSONValueTransformer: hex colors in JSON to UIColor, + * hex numbers in JSON to NSNumber model properties, base64 encoded strings in JSON to UIImage properties, and more. + * + * The class is invoked by JSONModel while transforming incoming + * JSON types into your target class property classes, and vice versa. + * One static copy is create and store in the JSONModel class scope. + */ +@interface JSONValueTransformer : NSObject + +@property (strong, nonatomic, readonly) NSDictionary *primitivesNames; + +/** @name Resolving cluster class names */ +/** + * This method returns the umbrella class for any standard class cluster members. + * For example returns NSString when given as input NSString, NSMutableString, __CFString and __CFConstantString + * The method currently looksup a pre-defined list. + * @param sourceClass the class to get the umbrella class for + * @return Class + */ ++ (Class)classByResolvingClusterClasses:(Class)sourceClass; + +#pragma mark - NSMutableString <-> NSString +/** @name Transforming to Mutable copies */ +/** + * Transforms a string value to a mutable string value + * @param string incoming string + * @return mutable string + */ +- (NSMutableString *)NSMutableStringFromNSString:(NSString *)string; + +#pragma mark - NSMutableArray <-> NSArray +/** + * Transforms an array to a mutable array + * @param array incoming array + * @return mutable array + */ +- (NSMutableArray *)NSMutableArrayFromNSArray:(NSArray *)array; + +#pragma mark - NSMutableDictionary <-> NSDictionary +/** + * Transforms a dictionary to a mutable dictionary + * @param dict incoming dictionary + * @return mutable dictionary + */ +- (NSMutableDictionary *)NSMutableDictionaryFromNSDictionary:(NSDictionary *)dict; + +#pragma mark - NSSet <-> NSArray +/** @name Transforming Sets */ +/** + * Transforms an array to a set + * @param array incoming array + * @return set with the array's elements + */ +- (NSSet *)NSSetFromNSArray:(NSArray *)array; + +/** + * Transforms an array to a mutable set + * @param array incoming array + * @return mutable set with the array's elements + */ +- (NSMutableSet *)NSMutableSetFromNSArray:(NSArray *)array; + +/** + * Transforms a set to an array + * @param set incoming set + * @return an array with the set's elements + */ +- (NSArray *)JSONObjectFromNSSet:(NSSet *)set; + +/** + * Transforms a mutable set to an array + * @param set incoming mutable set + * @return an array with the set's elements + */ +- (NSArray *)JSONObjectFromNSMutableSet:(NSMutableSet *)set; + +#pragma mark - BOOL <-> number/string +/** @name Transforming JSON types */ +/** + * Transforms a number object to a bool number object + * @param number the number to convert + * @return the resulting number + */ +- (NSNumber *)BOOLFromNSNumber:(NSNumber *)number; + +/** + * Transforms a number object to a bool number object + * @param string the string value to convert, "0" converts to NO, everything else to YES + * @return the resulting number + */ +- (NSNumber *)BOOLFromNSString:(NSString *)string; + +/** + * Transforms a BOOL value to a bool number object + * @param number an NSNumber value coming from the model + * @return the result number + */ +- (NSNumber *)JSONObjectFromBOOL:(NSNumber *)number; + +#pragma mark - string <-> number +/** + * Transforms a string object to a number object + * @param string the string to convert + * @return the resulting number + */ +- (NSNumber *)NSNumberFromNSString:(NSString *)string; + +/** + * Transforms a number object to a string object + * @param number the number to convert + * @return the resulting string + */ +- (NSString *)NSStringFromNSNumber:(NSNumber *)number; + +/** + * Transforms a string object to a nsdecimalnumber object + * @param string the string to convert + * @return the resulting number + */ +- (NSDecimalNumber *)NSDecimalNumberFromNSString:(NSString *)string; + +/** + * Transforms a nsdecimalnumber object to a string object + * @param number the number to convert + * @return the resulting string + */ +- (NSString *)NSStringFromNSDecimalNumber:(NSDecimalNumber *)number; + + +#pragma mark - string <-> url +/** @name Transforming URLs */ +/** + * Transforms a string object to an NSURL object + * @param string the string to convert + * @return the resulting url object + */ +- (NSURL *)NSURLFromNSString:(NSString *)string; + +/** + * Transforms an NSURL object to a string + * @param url the url object to convert + * @return the resulting string + */ +- (NSString *)JSONObjectFromNSURL:(NSURL *)url; + +#pragma mark - string <-> time zone + +/** @name Transforming NSTimeZone */ +/** + * Transforms a string object to an NSTimeZone object + * @param string the string to convert + * @return the resulting NSTimeZone object + */ +- (NSTimeZone *)NSTimeZoneFromNSString:(NSString *)string; + +/** + * Transforms an NSTimeZone object to a string + * @param timeZone the time zone object to convert + * @return the resulting string + */ +- (NSString *)JSONObjectFromNSTimeZone:(NSTimeZone *)timeZone; + +#pragma mark - string <-> date +/** @name Transforming Dates */ +/** + * The following two methods are not public. This way if there is a category on converting + * dates it'll override them. If there isn't a category the default methods found in the .m + * file will be invoked. If these are public a warning is produced at the point of overriding + * them in a category, so they have to stay hidden here. + */ + +//- (NSDate *)NSDateFromNSString:(NSString *)string; +//- (NSString *)JSONObjectFromNSDate:(NSDate *)date; + +#pragma mark - number <-> date + +/** + * Transforms a number to an NSDate object + * @param number the number to convert + * @return the resulting date + */ +- (NSDate *)NSDateFromNSNumber:(NSNumber *)number; + +@end diff --git a/Pods/JSONModel/JSONModel/JSONModelTransformations/JSONValueTransformer.m b/Pods/JSONModel/JSONModel/JSONModelTransformations/JSONValueTransformer.m new file mode 100644 index 0000000..8ffc00e --- /dev/null +++ b/Pods/JSONModel/JSONModel/JSONModelTransformations/JSONValueTransformer.m @@ -0,0 +1,245 @@ +// +// JSONValueTransformer.m +// JSONModel +// + +#import "JSONValueTransformer.h" + +#pragma mark - functions +extern BOOL isNull(id value) +{ + if (!value) return YES; + if ([value isKindOfClass:[NSNull class]]) return YES; + + return NO; +} + +@implementation JSONValueTransformer + +-(id)init +{ + self = [super init]; + if (self) { + _primitivesNames = @{@"f":@"float", @"i":@"int", @"d":@"double", @"l":@"long", @"c":@"BOOL", @"s":@"short", @"q":@"long", + //and some famous aliases of primitive types + // BOOL is now "B" on iOS __LP64 builds + @"I":@"NSInteger", @"Q":@"NSUInteger", @"B":@"BOOL", + + @"@?":@"Block"}; + } + return self; +} + ++(Class)classByResolvingClusterClasses:(Class)sourceClass +{ + //check for all variations of strings + if ([sourceClass isSubclassOfClass:[NSString class]]) { + return [NSString class]; + } + + //check for all variations of numbers + if ([sourceClass isSubclassOfClass:[NSNumber class]]) { + return [NSNumber class]; + } + + //check for all variations of dictionaries + if ([sourceClass isSubclassOfClass:[NSArray class]]) { + return [NSArray class]; + } + + //check for all variations of arrays + if ([sourceClass isSubclassOfClass:[NSDictionary class]]) { + return [NSDictionary class]; + } + + //check for all variations of dates + if ([sourceClass isSubclassOfClass:[NSDate class]]) { + return [NSDate class]; + } + + //no cluster parent class found + return sourceClass; +} + +#pragma mark - NSMutableString <-> NSString +-(NSMutableString*)NSMutableStringFromNSString:(NSString*)string +{ + return [NSMutableString stringWithString:string]; +} + +#pragma mark - NSMutableArray <-> NSArray +-(NSMutableArray*)NSMutableArrayFromNSArray:(NSArray*)array +{ + return [NSMutableArray arrayWithArray:array]; +} + +#pragma mark - NSMutableDictionary <-> NSDictionary +-(NSMutableDictionary*)NSMutableDictionaryFromNSDictionary:(NSDictionary*)dict +{ + return [NSMutableDictionary dictionaryWithDictionary:dict]; +} + +#pragma mark - NSSet <-> NSArray +-(NSSet*)NSSetFromNSArray:(NSArray*)array +{ + return [NSSet setWithArray:array]; +} + +-(NSMutableSet*)NSMutableSetFromNSArray:(NSArray*)array +{ + return [NSMutableSet setWithArray:array]; +} + +-(id)JSONObjectFromNSSet:(NSSet*)set +{ + return [set allObjects]; +} + +-(id)JSONObjectFromNSMutableSet:(NSMutableSet*)set +{ + return [set allObjects]; +} + +// +// 0 converts to NO, everything else converts to YES +// + +#pragma mark - BOOL <-> number/string +-(NSNumber*)BOOLFromNSNumber:(NSNumber*)number +{ + if (isNull(number)) return [NSNumber numberWithBool:NO]; + return [NSNumber numberWithBool: number.intValue==0?NO:YES]; +} + +-(NSNumber*)BOOLFromNSString:(NSString*)string +{ + if (string != nil && + ([string caseInsensitiveCompare:@"true"] == NSOrderedSame || + [string caseInsensitiveCompare:@"yes"] == NSOrderedSame)) { + return [NSNumber numberWithBool:YES]; + } + return [NSNumber numberWithBool: ([string intValue]==0)?NO:YES]; +} + +-(NSNumber*)JSONObjectFromBOOL:(NSNumber*)number +{ + return [NSNumber numberWithBool: number.intValue==0?NO:YES]; +} + +#pragma mark - string/number <-> float +-(float)floatFromObject:(id)obj +{ + return [obj floatValue]; +} + +-(float)floatFromNSString:(NSString*)string +{ + return [self floatFromObject:string]; +} + +-(float)floatFromNSNumber:(NSNumber*)number +{ + return [self floatFromObject:number]; +} + +-(NSNumber*)NSNumberFromfloat:(float)f +{ + return [NSNumber numberWithFloat:f]; +} + +#pragma mark - string <-> number +-(NSNumber*)NSNumberFromNSString:(NSString*)string +{ + return [NSNumber numberWithDouble:[string doubleValue]]; +} + +-(NSString*)NSStringFromNSNumber:(NSNumber*)number +{ + return [number stringValue]; +} + +-(NSDecimalNumber*)NSDecimalNumberFromNSString:(NSString*)string +{ + return [NSDecimalNumber decimalNumberWithString:string]; +} + +-(NSString*)NSStringFromNSDecimalNumber:(NSDecimalNumber*)number +{ + return [number stringValue]; +} + +#pragma mark - string <-> url +-(NSURL*)NSURLFromNSString:(NSString*)string +{ + // do not change this behavior - there are other ways of overriding it + // see: https://github.com/jsonmodel/jsonmodel/pull/119 + return [NSURL URLWithString:string]; +} + +-(NSString*)JSONObjectFromNSURL:(NSURL*)url +{ + return [url absoluteString]; +} + +#pragma mark - string <-> date +-(NSDateFormatter*)importDateFormatter +{ + static dispatch_once_t onceInput; + static NSDateFormatter* inputDateFormatter; + dispatch_once(&onceInput, ^{ + inputDateFormatter = [[NSDateFormatter alloc] init]; + [inputDateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]]; + [inputDateFormatter setDateFormat:@"yyyy-MM-dd'T'HHmmssZZZ"]; + }); + return inputDateFormatter; +} + +-(NSDate*)__NSDateFromNSString:(NSString*)string +{ + string = [string stringByReplacingOccurrencesOfString:@":" withString:@""]; // this is such an ugly code, is this the only way? + return [self.importDateFormatter dateFromString: string]; +} + +-(NSString*)__JSONObjectFromNSDate:(NSDate*)date +{ + static dispatch_once_t onceOutput; + static NSDateFormatter *outputDateFormatter; + dispatch_once(&onceOutput, ^{ + outputDateFormatter = [[NSDateFormatter alloc] init]; + [outputDateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]]; + [outputDateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"]; + }); + return [outputDateFormatter stringFromDate:date]; +} + +#pragma mark - number <-> date +- (NSDate*)NSDateFromNSNumber:(NSNumber*)number +{ + return [NSDate dateWithTimeIntervalSince1970:number.doubleValue]; +} + +#pragma mark - string <-> NSTimeZone + +- (NSTimeZone *)NSTimeZoneFromNSString:(NSString *)string { + return [NSTimeZone timeZoneWithName:string]; +} + +- (id)JSONObjectFromNSTimeZone:(NSTimeZone *)timeZone { + return [timeZone name]; +} + +#pragma mark - hidden transform for empty dictionaries +//https://github.com/jsonmodel/jsonmodel/issues/163 +-(NSDictionary*)__NSDictionaryFromNSArray:(NSArray*)array +{ + if (array.count==0) return @{}; + return (id)array; +} + +-(NSMutableDictionary*)__NSMutableDictionaryFromNSArray:(NSArray*)array +{ + if (array.count==0) return [[self __NSDictionaryFromNSArray:array] mutableCopy]; + return (id)array; +} + +@end diff --git a/Pods/JSONModel/LICENSE b/Pods/JSONModel/LICENSE new file mode 100644 index 0000000..babea51 --- /dev/null +++ b/Pods/JSONModel/LICENSE @@ -0,0 +1,18 @@ +Copyright (c) 2012-2016 Marin Todorov and JSONModel contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Pods/JSONModel/README.md b/Pods/JSONModel/README.md new file mode 100644 index 0000000..3850165 --- /dev/null +++ b/Pods/JSONModel/README.md @@ -0,0 +1,388 @@ +# JSONModel - Magical Data Modeling Framework for JSON + +JSONModel allows rapid creation of smart data models. You can use it in your +iOS, macOS, watchOS and tvOS apps. Automatic introspection of your model classes +and JSON input drastically reduces the amount of code you have to write. + +See [CHANGELOG.md](CHANGELOG.md) for details on changes. + +## Installation + +### CocoaPods + +```ruby +pod 'JSONModel' +``` + +### Carthage + +```ruby +github "jsonmodel/jsonmodel" +``` + +### Manual + +0. download the JSONModel repository +0. copy the JSONModel sub-folder into your Xcode project +0. link your app to SystemConfiguration.framework + +## Basic Usage + +Consider you have JSON like this: + +```json +{ "id": 10, "country": "Germany", "dialCode": 49, "isInEurope": true } +``` + +- create a JSONModel subclass for your data model +- declare properties in your header file with the name of the JSON keys: + +```objc +@interface CountryModel : JSONModel +@property (nonatomic) NSInteger id; +@property (nonatomic) NSString *country; +@property (nonatomic) NSString *dialCode; +@property (nonatomic) BOOL isInEurope; +@end +``` + +There's no need to do anything in the implementation (`.m`) file. + +- initialize your model with data: + +```objc +NSError *error; +CountryModel *country = [[CountryModel alloc] initWithString:myJson error:&error]; +``` + +If the validation of the JSON passes. you have all the corresponding properties +in your model populated from the JSON. JSONModel will also try to convert as +much data to the types you expect. In the example above it will: + +- convert `id` from string (in the JSON) to an `int` for your class +- copy the `country` value +- convert `dialCode` from a number (in the JSON) to an `NSString` value +- copy the `isInEurope` value + +All you have to do is define the properties and their expected types. + +## Examples + +### Automatic name based mapping + +```json +{ + "id": 123, + "name": "Product name", + "price": 12.95 +} +``` + +```objc +@interface ProductModel : JSONModel +@property (nonatomic) NSInteger id; +@property (nonatomic) NSString *name; +@property (nonatomic) float price; +@end +``` + +### Model cascading (models including other models) + +```json +{ + "orderId": 104, + "totalPrice": 13.45, + "product": { + "id": 123, + "name": "Product name", + "price": 12.95 + } +} +``` + +```objc +@interface ProductModel : JSONModel +@property (nonatomic) NSInteger id; +@property (nonatomic) NSString *name; +@property (nonatomic) float price; +@end + +@interface OrderModel : JSONModel +@property (nonatomic) NSInteger orderId; +@property (nonatomic) float totalPrice; +@property (nonatomic) ProductModel *product; +@end +``` + +### Model collections + +```json +{ + "orderId": 104, + "totalPrice": 103.45, + "products": [ + { + "id": 123, + "name": "Product #1", + "price": 12.95 + }, + { + "id": 137, + "name": "Product #2", + "price": 82.95 + } + ] +} +``` + +```objc +@protocol ProductModel; + +@interface ProductModel : JSONModel +@property (nonatomic) NSInteger id; +@property (nonatomic) NSString *name; +@property (nonatomic) float price; +@end + +@interface OrderModel : JSONModel +@property (nonatomic) NSInteger orderId; +@property (nonatomic) float totalPrice; +@property (nonatomic) NSArray *products; +@end +``` + +Note: the angle brackets after `NSArray` contain a protocol. This is not the +same as the Objective-C generics system. They are not mutually exclusive, but +for JSONModel to work, the protocol must be in place. + +### Nested key mapping + +```json +{ + "orderId": 104, + "orderDetails": [ + { + "name": "Product #1", + "price": { + "usd": 12.95 + } + } + ] +} +``` + +```objc +@interface OrderModel : JSONModel +@property (nonatomic) NSInteger id; +@property (nonatomic) NSString *productName; +@property (nonatomic) float price; +@end + +@implementation OrderModel + ++ (JSONKeyMapper *)keyMapper +{ + return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{ + @"id": @"orderId", + @"productName": @"orderDetails.name", + @"price": @"orderDetails.price.usd" + }]; +} + +@end +``` + +### Map automatically to snake_case + +```json +{ + "order_id": 104, + "order_product": "Product #1", + "order_price": 12.95 +} +``` + +```objc +@interface OrderModel : JSONModel +@property (nonatomic) NSInteger orderId; +@property (nonatomic) NSString *orderProduct; +@property (nonatomic) float orderPrice; +@end + +@implementation OrderModel + ++ (JSONKeyMapper *)keyMapper +{ + return [JSONKeyMapper mapperForSnakeCase]; +} + +@end +``` + +### Optional properties (i.e. can be missing or null) + +```json +{ + "id": 123, + "name": null, + "price": 12.95 +} +``` + +```objc +@interface ProductModel : JSONModel +@property (nonatomic) NSInteger id; +@property (nonatomic) NSString *name; +@property (nonatomic) float price; +@property (nonatomic) NSNumber *uuid; +@end +``` + +### Ignored properties (i.e. JSONModel completely ignores them) + +```json +{ + "id": 123, + "name": null +} +``` + +```objc +@interface ProductModel : JSONModel +@property (nonatomic) NSInteger id; +@property (nonatomic) NSString *customProperty; +@end +``` + +### Making scalar types optional + +```json +{ + "id": null +} +``` + +```objc +@interface ProductModel : JSONModel +@property (nonatomic) NSInteger id; +@end + +@implementation ProductModel + ++ (BOOL)propertyIsOptional:(NSString *)propertyName +{ + if ([propertyName isEqualToString:@"id"]) + return YES; + + return NO; +} + +@end +``` + +### Export model to `NSDictionary` or JSON + +```objc +ProductModel *pm = [ProductModel new]; +pm.name = @"Some Name"; + +// convert to dictionary +NSDictionary *dict = [pm toDictionary]; + +// convert to json +NSString *string = [pm toJSONString]; +``` + +### Custom data transformers + +```objc +@interface JSONValueTransformer (CustomNSDate) +@end + +@implementation JSONValueTransformer (CustomTransformer) + +- (NSDate *)NSDateFromNSString:(NSString *)string +{ + NSDateFormatter *formatter = [NSDateFormatter new]; + formatter.dateFormat = APIDateFormat; + return [formatter dateFromString:string]; +} + +- (NSString *)JSONObjectFromNSDate:(NSDate *)date +{ + NSDateFormatter *formatter = [NSDateFormatter new]; + formatter.dateFormat = APIDateFormat; + return [formatter stringFromDate:date]; +} + +@end +``` + +### Custom getters/setters + +```objc +@interface ProductModel : JSONModel +@property (nonatomic) NSInteger id; +@property (nonatomic) NSString *name; +@property (nonatomic) float price; +@property (nonatomic) NSLocale *locale; +@end + +@implementation ProductModel + +- (void)setLocaleWithNSString:(NSString *)string +{ + self.locale = [NSLocale localeWithLocaleIdentifier:string]; +} + +- (void)setLocaleWithNSDictionary:(NSDictionary *)dictionary +{ + self.locale = [NSLocale localeWithLocaleIdentifier:dictionary[@"identifier"]]; +} + +- (NSString *)JSONObjectForLocale +{ + return self.locale.localeIdentifier; +} + +@end +``` + +### Custom JSON validation + +```objc + +@interface ProductModel : JSONModel +@property (nonatomic) NSInteger id; +@property (nonatomic) NSString *name; +@property (nonatomic) float price; +@property (nonatomic) NSLocale *locale; +@property (nonatomic) NSNumber *minNameLength; +@end + +@implementation ProductModel + +- (BOOL)validate:(NSError **)error +{ + if (![super validate:error]) + return NO; + + if (self.name.length < self.minNameLength.integerValue) + { + *error = [NSError errorWithDomain:@"me.mycompany.com" code:1 userInfo:nil]; + return NO; + } + + return YES; +} + +@end +``` + +## License + +MIT licensed - see [LICENSE](LICENSE) file. + +## Contributing + +We love pull requests! See [CONTRIBUTING.md](CONTRIBUTING.md) for full details. diff --git a/Pods/LKDBHelper/LICENSE b/Pods/LKDBHelper/LICENSE new file mode 100644 index 0000000..feabb4c --- /dev/null +++ b/Pods/LKDBHelper/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012 Jianghuai Li (https://github.com/li6185377) + +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/Pods/LKDBHelper/LKDBHelper/Helper/LKDB+Mapping.h b/Pods/LKDBHelper/LKDBHelper/Helper/LKDB+Mapping.h new file mode 100644 index 0000000..6df4081 --- /dev/null +++ b/Pods/LKDBHelper/LKDBHelper/Helper/LKDB+Mapping.h @@ -0,0 +1,86 @@ +// +// LKDBProperty+KeyMapping.h +// LKDBHelper +// +// Created by LJH on 13-6-17. +// Copyright (c) 2013年 ljh. All rights reserved. +// + +#import "LKDBUtils.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface NSObject (TableMapping) + +/** + * @brief Overwrite in your models if your property names don't match your Table Column names. + also use for set create table columns. + + @{ sql column name : ( model property name ) or LKDBInherit or LKDBUserCalculate} + + */ ++ (nullable NSDictionary *)getTableMapping; + +/*** + simple set a column as "LKSQL_Mapping_UserCalculate" + column name +*/ ++ (void)setUserCalculateForCN:(NSString *)columnName; + +///property type name ++ (void)setUserCalculateForPTN:(NSString *)propertyTypeName; + +///binding columnName to PropertyName ++ (void)setTableColumnName:(NSString *)columnName bindingPropertyName:(NSString *)propertyName; + +///remove unwanted binding property ++ (void)removePropertyWithColumnName:(NSString *)columnName; ++ (void)removePropertyWithColumnNameArray:(NSArray *)columnNameArray; + +@end + +@interface LKDBProperty : NSObject + +///保存的方式 +@property (nonatomic, copy, readonly) NSString *type; + +///保存到数据的 列名 +@property (nonatomic, copy, readonly) NSString *sqlColumnName; +///保存到数据的类型 +@property (nonatomic, copy, readonly) NSString *sqlColumnType; + +///属性名 +@property (nonatomic, copy, readonly) NSString *propertyName; +///属性的类型 +@property (nonatomic, copy, readonly) NSString *propertyType; + +///属性的Protocol +//@property(readonly,copy,nonatomic)NSString *propertyProtocol; + +///creating table's column +@property (nonatomic, assign) BOOL isUnique; +@property (nonatomic, assign) BOOL isNotNull; +@property (nullable, nonatomic, copy) NSString *defaultValue; +@property (nullable, nonatomic, copy) NSString *checkValue; +@property (nonatomic, assign) NSInteger length; + +- (BOOL)isUserCalculate; +@end + +@interface LKModelInfos : NSObject + +- (id)initWithKeyMapping:(nullable NSDictionary *)keyMapping + propertyNames:(NSArray *)propertyNames + propertyType:(NSArray *)propertyType + primaryKeys:(nullable NSArray *)primaryKeys; + +@property (nonatomic, readonly) NSUInteger count; +@property (nullable, nonatomic, readonly) NSArray *primaryKeys; + +- (nullable LKDBProperty *)objectWithIndex:(NSInteger)index; +- (nullable LKDBProperty *)objectWithPropertyName:(NSString *)propertyName; +- (nullable LKDBProperty *)objectWithSqlColumnName:(NSString *)columnName; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/LKDBHelper/LKDBHelper/Helper/LKDB+Mapping.m b/Pods/LKDBHelper/LKDBHelper/Helper/LKDB+Mapping.m new file mode 100644 index 0000000..faa4144 --- /dev/null +++ b/Pods/LKDBHelper/LKDBHelper/Helper/LKDB+Mapping.m @@ -0,0 +1,277 @@ +// +// LKDBProperty+KeyMapping.m +// LKDBHelper +// +// Created by LJH on 13-6-17. +// Copyright (c) 2013年 ljh. All rights reserved. +// + +#import "LKDB+Mapping.h" +#import "NSObject+LKModel.h" + +@interface LKModelInfos () { + __strong NSMutableDictionary *_proNameDic; + __strong NSMutableDictionary *_sqlNameDic; + __strong NSArray *_primaryKeys; +} +- (void)removeWithColumnName:(NSString *)columnName; +- (void)addDBPropertyWithType:(NSString *)type cname:(NSString *)column_name ctype:(NSString *)ctype pname:(NSString *)pname ptype:(NSString *)ptype; + +- (void)updateProperty:(LKDBProperty *)property sqlColumnName:(NSString *)columnName; +- (void)updateProperty:(LKDBProperty *)property propertyName:(NSString *)propertyName; +@end + +#pragma mark - 声明属性 +@interface LKDBProperty () +@property (nonatomic, copy) NSString *type; + +@property (nonatomic, copy) NSString *sqlColumnName; +@property (nonatomic, copy) NSString *sqlColumnType; + +@property (nonatomic, copy) NSString *propertyName; +@property (nonatomic, copy) NSString *propertyType; + +- (id)initWithType:(NSString *)type cname:(NSString *)cname ctype:(NSString *)ctype pname:(NSString *)pname ptype:(NSString *)ptype; +@end +#pragma mark - LKDBProperty +@implementation LKDBProperty + +- (id)initWithType:(NSString *)type cname:(NSString *)cname ctype:(NSString *)ctype pname:(NSString *)pname ptype:(NSString *)ptype +{ + self = [super init]; + if (self) { + _type = [type copy]; + _sqlColumnName = [cname copy]; + _sqlColumnType = [ctype copy]; + _propertyName = [pname copy]; + _propertyType = [ptype copy]; + } + return self; +} +- (void)enableUserCalculate +{ + _type = LKSQL_Mapping_UserCalculate; +} +- (BOOL)isUserCalculate +{ + return ([_type isEqualToString:LKSQL_Mapping_UserCalculate] || _propertyName == nil || [_propertyName isEqualToString:LKSQL_Mapping_UserCalculate]); +} +@end +#pragma mark - NSObject - TableMapping +@implementation NSObject (TableMapping) ++ (NSDictionary *)getTableMapping +{ + return nil; +} ++ (void)setUserCalculateForCN:(NSString *)columnName +{ + if ([LKDBUtils checkStringIsEmpty:columnName]) { + LKErrorLog(@"columnName is null"); + return; + } + + LKModelInfos *infos = [self getModelInfos]; + LKDBProperty *property = [infos objectWithSqlColumnName:columnName]; + if (property) { + [property enableUserCalculate]; + } else { + [infos addDBPropertyWithType:LKSQL_Mapping_UserCalculate cname:columnName ctype:LKSQL_Type_Text pname:columnName ptype:@"NSString"]; + } +} ++ (void)setUserCalculateForPTN:(NSString *)propertyTypeName +{ + if ([LKDBUtils checkStringIsEmpty:propertyTypeName]) { + LKErrorLog(@"propertyTypeName is null"); + return; + } + + Class clazz = NSClassFromString(propertyTypeName); + LKModelInfos *infos = [self getModelInfos]; + for (NSInteger i = 0; i < infos.count; i++) { + LKDBProperty *property = [infos objectWithIndex:i]; + + Class p_cls = NSClassFromString(property.propertyType); + BOOL isSubClass = ((p_cls && clazz) && [p_cls isSubclassOfClass:clazz]); + BOOL isNameEqual = [property.propertyType isEqualToString:propertyTypeName]; + if (isSubClass || isNameEqual) { + [property enableUserCalculate]; + } + } +} ++ (void)setTableColumnName:(NSString *)columnName bindingPropertyName:(NSString *)propertyName +{ + if ([LKDBUtils checkStringIsEmpty:columnName] || [LKDBUtils checkStringIsEmpty:propertyName]) + return; + + LKModelInfos *infos = [self getModelInfos]; + + LKDBProperty *property = [infos objectWithPropertyName:propertyName]; + if (property == nil) { + return; + } + + LKDBProperty *column = [infos objectWithSqlColumnName:columnName]; + if (column) { + [infos updateProperty:column propertyName:propertyName]; + column.propertyType = property.propertyType; + } else if ([property.sqlColumnName isEqualToString:property.propertyName]) { + [infos updateProperty:property sqlColumnName:columnName]; + } else { + [infos addDBPropertyWithType:LKSQL_Mapping_Binding cname:columnName ctype:LKSQL_Type_Text pname:propertyName ptype:property.propertyType]; + } +} ++ (void)removePropertyWithColumnNameArray:(NSArray *)columnNameArray +{ + LKModelInfos *infos = [self getModelInfos]; + for (NSString *columnName in columnNameArray) { + [infos removeWithColumnName:columnName]; + } +} ++ (void)removePropertyWithColumnName:(NSString *)columnName +{ + [[self getModelInfos] removeWithColumnName:columnName]; +} +@end + +#pragma mark - LKModelInfos + +@implementation LKModelInfos +- (id)initWithKeyMapping:(NSDictionary *)keyMapping propertyNames:(NSArray *)propertyNames propertyType:(NSArray *)propertyType primaryKeys:(NSArray *)primaryKeys +{ + self = [super init]; + if (self) { + + _primaryKeys = [NSArray arrayWithArray:primaryKeys]; + + _proNameDic = [[NSMutableDictionary alloc] init]; + _sqlNameDic = [[NSMutableDictionary alloc] init]; + + NSString *type, *column_name, *column_type, *property_name, *property_type; + if (keyMapping.count > 0) { + NSArray *sql_names = keyMapping.allKeys; + + for (NSInteger i = 0; i < sql_names.count; i++) { + + type = column_name = column_type = property_name = property_type = nil; + + column_name = [sql_names objectAtIndex:i]; + NSString *mappingValue = [keyMapping objectForKey:column_name]; + + //如果 设置的 属性名 是空白的 自动转成 使用ColumnName + if ([LKDBUtils checkStringIsEmpty:mappingValue]) { + NSLog(@"#ERROR sql column name %@ mapping value is empty,automatically converted LKDBInherit", column_name); + mappingValue = LKSQL_Mapping_Inherit; + } + + if ([mappingValue isEqualToString:LKSQL_Mapping_UserCalculate]) { + type = LKSQL_Mapping_UserCalculate; + column_type = LKSQL_Type_Text; + } else { + + if ([mappingValue isEqualToString:LKSQL_Mapping_Inherit] || [mappingValue isEqualToString:LKSQL_Mapping_Binding]) { + type = LKSQL_Mapping_Inherit; + property_name = column_name; + } else { + type = LKSQL_Mapping_Binding; + property_name = mappingValue; + } + + NSUInteger index = [propertyNames indexOfObject:property_name]; + + NSAssert(index != NSNotFound, @"#ERROR TableMapping SQL column name %@ not fount %@ property name", column_name, property_name); + + property_type = [propertyType objectAtIndex:index]; + column_type = LKSQLTypeFromObjcType(property_type); + } + + [self addDBPropertyWithType:type cname:column_name ctype:column_type pname:property_name ptype:property_type]; + } + } else { + for (NSInteger i = 0; i < propertyNames.count; i++) { + + type = LKSQL_Mapping_Inherit; + + property_name = [propertyNames objectAtIndex:i]; + column_name = property_name; + + property_type = [propertyType objectAtIndex:i]; + column_type = LKSQLTypeFromObjcType(property_type); + + [self addDBPropertyWithType:type cname:column_name ctype:column_type pname:property_name ptype:property_type]; + } + } + + if (_primaryKeys.count == 0) { + _primaryKeys = [NSArray arrayWithObject:@"rowid"]; + } + + for (NSString *pkname in _primaryKeys) { + if ([pkname.lowercaseString isEqualToString:@"rowid"]) { + if ([self objectWithSqlColumnName:pkname] == nil) { + [self addDBPropertyWithType:LKSQL_Mapping_Inherit cname:pkname ctype:LKSQL_Type_Int pname:pkname ptype:@"int"]; + } + } + } + } + return self; +} +- (void)addDBPropertyWithType:(NSString *)type cname:(NSString *)column_name ctype:(NSString *)ctype pname:(NSString *)pname ptype:(NSString *)ptype +{ + LKDBProperty *db_property = [[LKDBProperty alloc] initWithType:type cname:column_name ctype:ctype pname:pname ptype:ptype]; + + if (db_property.propertyName) { + _proNameDic[db_property.propertyName] = db_property; + } + if (db_property.sqlColumnName) { + _sqlNameDic[db_property.sqlColumnName] = db_property; + } +} +- (NSArray *)primaryKeys +{ + return _primaryKeys; +} +- (NSUInteger)count +{ + return _sqlNameDic.count; +} +- (LKDBProperty *)objectWithIndex:(NSInteger)index +{ + if (index < _sqlNameDic.count) { + id key = [_sqlNameDic.allKeys objectAtIndex:index]; + return [_sqlNameDic objectForKey:key]; + } + return nil; +} +- (LKDBProperty *)objectWithPropertyName:(NSString *)propertyName +{ + return [_proNameDic objectForKey:propertyName]; +} +- (LKDBProperty *)objectWithSqlColumnName:(NSString *)columnName +{ + return [_sqlNameDic objectForKey:columnName]; +} + +- (void)updateProperty:(LKDBProperty *)property propertyName:(NSString *)propertyName +{ + [_proNameDic removeObjectForKey:property.propertyName]; + property.propertyName = propertyName; + _proNameDic[propertyName] = property; +} +- (void)updateProperty:(LKDBProperty *)property sqlColumnName:(NSString *)columnName +{ + [_sqlNameDic removeObjectForKey:property.sqlColumnName]; + property.sqlColumnName = columnName; + _sqlNameDic[columnName] = property; +} +- (void)removeWithColumnName:(NSString *)columnName +{ + if ([LKDBUtils checkStringIsEmpty:columnName]) + return; + + LKDBProperty *property = [_sqlNameDic objectForKey:columnName]; + if (property.propertyName) { + [_proNameDic removeObjectForKey:property.propertyName]; + } + [_sqlNameDic removeObjectForKey:columnName]; +} +@end diff --git a/Pods/LKDBHelper/LKDBHelper/Helper/LKDBHelper.h b/Pods/LKDBHelper/LKDBHelper/Helper/LKDBHelper.h new file mode 100644 index 0000000..bc8f233 --- /dev/null +++ b/Pods/LKDBHelper/LKDBHelper/Helper/LKDBHelper.h @@ -0,0 +1,292 @@ +// +// LKDBHelper.h +// LJH +// +// Created by LJH on 12-12-6. +// Copyright (c) 2012年 LJH. All rights reserved. +// + +#import "LKDB+Mapping.h" +#import "LKDBUtils.h" +#import "NSObject+LKDBHelper.h" +#import "NSObject+LKModel.h" +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface LKDBHelper : NSObject + +/** + * @brief Log error message, Default: NO + */ ++ (void)setLogError:(BOOL)logError; + +/** + * @brief null is '' , Default: NO + */ ++ (void)setNullToEmpty:(BOOL)empty; + +/** + * @brief filepath the use of : "documents/db/" + fileName + ".db" + * add to global cache with instance created + * refer: FMDatabase.h + (instancetype)databaseWithPath:(NSString *)inPath; + */ +- (instancetype)initWithDBName:(NSString *)dbname; +- (void)setDBName:(NSString *)fileName; + +/** + * @brief path of database file + * refer: FMDatabase.h + (instancetype)databaseWithPath:(NSString *)inPath; + */ +- (instancetype)initWithDBPath:(NSString *)filePath; +- (void)setDBPath:(NSString *)filePath; + +/** + * @brief closing a database connection and remove instance for global cache + */ +- (void)closeDB; + +/** + * @brief 当数据库无操作 多少秒后 自动关闭数据库连接, 区间 [10 ~ int_max] 默认:20秒 + */ +- (void)setAutoCloseDBTime:(NSInteger)time; + +/** + * @brief current encryption key. + */ +@property (nullable, nonatomic, copy, readonly) NSString *encryptionKey; + +/** + * @brief Set encryption key + refer: FMDatabase.h - (BOOL)setKey:(NSString *)key; + * invoking after the `LKDBHelper initialize` in YourModelClass.m `getUsingLKDBHelper` function + */ +- (BOOL)setKey:(NSString *)key; + +/// Reset encryption key +- (BOOL)rekey:(NSString *)key; + +/** + * @brief execute database operations synchronously,not afraid of recursive deadlock + + 同步执行数据库操作 可递归调用 + */ +- (void)executeDB:(void (^)(FMDatabase *db))block; + +- (BOOL)executeSQL:(NSString *)sql arguments:(nullable NSArray *)args; +- (nullable NSString *)executeScalarWithSQL:(NSString *)sql arguments:(nullable NSArray *)args; + +/** + * @brief execute database operations synchronously in a transaction + block return the YES commit transaction returns the NO rollback transaction + + 同步执行数据库操作 在事务内部 + block 返回 YES commit 事务 返回 NO rollback 事务 + */ +- (void)executeForTransaction:(BOOL (^)(LKDBHelper *helper))block; + +@end + +@interface LKDBHelper (DatabaseManager) + +///get table has created +- (BOOL)getTableCreatedWithClass:(Class)model; +- (BOOL)getTableCreatedWithTableName:(NSString *)tableName; + +///drop all table +- (void)dropAllTable; + +///drop table with entity class +- (BOOL)dropTableWithClass:(Class)modelClass; +- (BOOL)dropTableWithTableName:(NSString *)tableName; + +@end + +@interface LKDBHelper (DatabaseExecute) +/** + * @brief The number of rows query table + * + * @param modelClass entity class + * @param where can use NSString or NSDictionary or nil + * + * @return rows number + */ +- (NSInteger)rowCount:(Class)modelClass where:(nullable id)where; +- (void)rowCount:(Class)modelClass where:(nullable id)where callback:(void (^)(NSInteger rowCount))callback; +- (NSInteger)rowCountWithTableName:(NSString *)tableName where:(nullable id)where; + +/** + * @brief query table + * + * @param params query condition + */ +- (nullable NSMutableArray *)searchWithParams:(LKDBQueryParams *)params; + +/** + * @brief query table + * + * @param modelClass entity class + * @param where can use NSString or NSDictionary or nil + + * @param orderBy The Sort: Ascending "name asc",Descending "name desc" + For example: @"rowid desc"x or @"rowid asc" + + * @param offset Skip how many rows + * @param count Limit the number + * + * @return query finished result is an array(model instance collection) + */ +- (nullable NSMutableArray *)search:(Class)modelClass + where:(nullable id)where + orderBy:(nullable NSString *)orderBy + offset:(NSInteger)offset + count:(NSInteger)count; + +/** + * query sql, query finished result is an array(model instance collection) + * you can use the "@t" replace Model TableName + * query sql use lowercase string + * 查询的sql语句 请使用小写 ,否则会不能自动获取 rowid + * example: + NSMutableArray *array = [[LKDBHelper getUsingLKDBHelper] searchWithSQL:@"select * from @t where blah blah.." toClass:[ModelClass class]]; + * + */ +- (nullable NSMutableArray *)searchWithSQL:(NSString *)sql toClass:(nullable Class)modelClass; + +/** + * @brief don't do any operations of the sql + */ +- (nullable NSMutableArray *)searchWithRAWSQL:(NSString *)sql toClass:(nullable Class)modelClass; + +/** + * query sql, query finished result is an array(model instance collection) + * you can use the "@t" replace Model TableName and replace all ? placeholders with the va_list + * example: + NSMutableArray *array = [[LKDBHelper getUsingLKDBHelper] searc:[ModelClass class] withSQL:@"select rowid from name_table where name = ?", @"Swift"]; + * + */ +- (nullable NSMutableArray *)search:(Class)modelClass withSQL:(NSString *)sql, ...; + +/** + columns may NSArray or NSString if query column count == 1 return single column string array + other return models entity array + */ +- (nullable NSMutableArray *)search:(Class)modelClass + column:(nullable id)columns + where:(nullable id)where + orderBy:(nullable NSString *)orderBy + offset:(NSInteger)offset + count:(NSInteger)count; + +/** + * @brief async search + */ +- (void)search:(Class)modelClass + where:(nullable id)where + orderBy:(nullable NSString *)orderBy + offset:(NSInteger)offset + count:(NSInteger)count + callback:(void (^)(NSMutableArray *_Nullable array))block; + +///return first model or nil +- (nullable id)searchSingle:(Class)modelClass where:(nullable id)where orderBy:(nullable NSString *)orderBy; + +/** + * @brief insert table + * + * @param model you want to insert the entity + * + * @return the inserted was successful + */ +- (BOOL)insertToDB:(NSObject *)model; +- (void)insertToDB:(NSObject *)model callback:(void (^)(BOOL result))block; + +/** + * @brief insert when the entity primary key does not exist + * + * @param model you want to insert the entity + * + * @return the inserted was successful + */ +- (BOOL)insertWhenNotExists:(NSObject *)model; +- (void)insertWhenNotExists:(NSObject *)model callback:(void (^)(BOOL result))block; + +/** + * @brief update table + * + * @param model you want to update the entity + * @param where can use NSString or NSDictionary or nil + when "where" is nil : update the value based on rowid column or primary key column + * + * @return the updated was successful + */ +- (BOOL)updateToDB:(NSObject *)model where:(nullable id)where; +- (void)updateToDB:(NSObject *)model where:(nullable id)where callback:(void (^)(BOOL result))block; +- (BOOL)updateToDB:(Class)modelClass set:(NSString *)sets where:(nullable id)where; +- (BOOL)updateToDBWithTableName:(NSString *)tableName set:(NSString *)sets where:(nullable id)where; + +/** + * @brief delete table + * + * @param model you want to delete entity + when entity property "rowid" == 0 based on the primary key to delete + * + * @return the deleted was successful + */ +- (BOOL)deleteToDB:(NSObject *)model; +- (void)deleteToDB:(NSObject *)model callback:(void (^)(BOOL result))block; + +/** + * @brief delete table with "where" constraint + * + * @param modelClass entity class + * @param where can use NSString or NSDictionary, can not is nil + * + * @return the deleted was successful + */ +- (BOOL)deleteWithClass:(Class)modelClass where:(nullable id)where; +- (void)deleteWithClass:(Class)modelClass where:(nullable id)where callback:(void (^)(BOOL result))block; +- (BOOL)deleteWithTableName:(NSString *)tableName where:(nullable id)where; + +/** + * @brief entity exists? + * for primary key column + (if rowid > 0 would certainly exist so we do not rowid judgment) + * @param model entity + * + * @return YES: entity presence , NO: entity not exist + */ +- (BOOL)isExistsModel:(NSObject *)model; +- (BOOL)isExistsClass:(Class)modelClass where:(nullable id)where; +- (BOOL)isExistsWithTableName:(NSString *)tableName where:(nullable id)where; + +/** + * @brief Clear data based on the entity class + * + * @param modelClass entity class + */ ++ (void)clearTableData:(Class)modelClass; + +/** + * @brief Clear Unused Data File + if you property has UIImage or NSData, will save their data in the (documents dir) + * + * @param modelClass entity class + * @param columns UIImage or NSData Column Name + */ ++ (void)clearNoneImage:(Class)modelClass columns:(NSArray *)columns; ++ (void)clearNoneData:(Class)modelClass columns:(NSArray *)columns; + +@end + +@interface LKDBHelper (Deprecated_Nonfunctional) +/// you can use [LKDBHelper getUsingLKDBHelper] +#pragma mark - deprecated ++ (LKDBHelper *)sharedDBHelper __deprecated_msg("Method deprecated. Use `[Model getUsingLKDBHelper]`"); +- (BOOL)createTableWithModelClass:(Class)modelClass __deprecated_msg("Now you can not call it. Will automatically determine whether you need to create"); +- (void)setEncryptionKey:(NSString *)encryptionKey __deprecated_msg("Method deprecated. Use `setKey: OR resetKey:` invoking after the `LKDBHelper initialize` in YourModelClass.m `getUsingLKDBHelper` function"); +#pragma mark - +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/LKDBHelper/LKDBHelper/Helper/LKDBHelper.m b/Pods/LKDBHelper/LKDBHelper/Helper/LKDBHelper.m new file mode 100644 index 0000000..9f96afa --- /dev/null +++ b/Pods/LKDBHelper/LKDBHelper/Helper/LKDBHelper.m @@ -0,0 +1,1721 @@ +// +// LKDBHelper.m +// LJH +// +// Created by LJH on 12-12-6. +// Copyright (c) 2012年 LJH. All rights reserved. +// + +#import "LKDBHelper.h" +#import + +#ifndef SQLITE_OPEN_FILEPROTECTION_NONE +#define SQLITE_OPEN_FILEPROTECTION_NONE 0x00400000 +#endif + +#define LKDBOpenFlags (SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_PRIVATECACHE | SQLITE_OPEN_FILEPROTECTION_NONE) + +#define LKDBCheck_tableNameIsInvalid(tableName) \ + if ([LKDBUtils checkStringIsEmpty:tableName]) { \ + LKErrorLog(@" \n Fail!Fail!Fail!Fail! \n with TableName is nil"); \ + return NO; \ + } + +#define LKDBCode_Async_Begin \ + __weak LKDBHelper *wself = self; \ + [self asyncBlock :^{__strong LKDBHelper *sself = wself; \ + if (sself) { + +#define LKDBCode_Async_End \ + } \ + }]; + +#define LKDBCheck_modelIsInvalid(model) \ + if (model == nil) { \ + LKErrorLog(@"model is nil"); \ + return NO; \ + } \ + if ([model.class getModelInfos].count == 0) { \ + LKErrorLog(@"class: %@ property count is 0!!", NSStringFromClass(model.class)); \ + return NO; \ + } \ + NSString *_model_tableName = model.db_tableName ?: [model.class getTableName]; \ + if ([LKDBUtils checkStringIsEmpty:_model_tableName]) { \ + LKErrorLog(@"model class name %@ table name is invalid!", NSStringFromClass(model.class)); \ + return NO; \ + } + +@interface NSObject (LKTabelStructure_Private) +- (void)setDb_inserting:(BOOL)db_inserting; +@end + +@interface LKDBWeakObject : NSObject +@property (nonatomic, weak) LKDBHelper *obj; +@end + +@interface LKDBHelper () +@property (nonatomic, weak) FMDatabase *usingdb; +@property (nonatomic, strong) FMDatabaseQueue *bindingQueue; +@property (nonatomic, copy) NSString *dbPath; +@property (nonatomic, strong) NSMutableArray *createdTableNames; +@property (nonatomic, strong) NSRecursiveLock *threadLock; + +@property (nonatomic, assign) NSInteger lastExecuteDBTime; +@property (nonatomic, assign) BOOL runingAutoCloseTimer; +@property (nonatomic, assign) NSInteger autoCloseDBDelayTime; + +@end + +@implementation LKDBHelper +@synthesize encryptionKey = _encryptionKey; + +static BOOL LKDBLogErrorEnable = NO; ++ (void)setLogError:(BOOL)logError +{ + if (LKDBLogErrorEnable == logError) { + return; + } +#ifdef DEBUG + LKDBLogErrorEnable = logError; + NSMutableArray *dbArray = [self dbHelperSingleArray]; + @synchronized(dbArray) { + [dbArray enumerateObjectsUsingBlock:^(LKDBWeakObject *weakObj, NSUInteger idx, BOOL *stop) { + [weakObj.obj executeDB:^(FMDatabase *db) { + db.logsErrors = LKDBLogErrorEnable; + }]; + }]; + } +#endif +} +static BOOL LKDBNullIsEmptyString = NO; ++ (void)setNullToEmpty:(BOOL)empty +{ + LKDBNullIsEmptyString = empty; +} ++ (BOOL)nullIsEmpty +{ + return LKDBNullIsEmptyString; +} + ++ (NSMutableArray *)dbHelperSingleArray +{ + static NSMutableArray *dbArray; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + dbArray = [NSMutableArray array]; + }); + return dbArray; +} + ++ (LKDBHelper *)dbHelperWithPath:(NSString *)dbFilePath save:(LKDBHelper *)helper +{ + LKDBHelper *instance = nil; + dbFilePath = dbFilePath.lowercaseString; + + NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet]; + BOOL hasCached = NO; + + NSMutableArray *dbArray = [self dbHelperSingleArray]; + @synchronized(dbArray) { + for (NSInteger i = 0; i < dbArray.count; i++) { + LKDBWeakObject *weakObj = [dbArray objectAtIndex:i]; + if ([weakObj.obj.dbPath.lowercaseString isEqualToString:dbFilePath]) { + if (helper) { + hasCached = YES; + } else { + instance = weakObj.obj; + } + } else if (!weakObj.obj){ + [indexSet addIndex:i]; + } + } + [dbArray removeObjectsAtIndexes:indexSet]; + + if (!hasCached && helper) { + LKDBWeakObject *weakObj = [[LKDBWeakObject alloc] init]; + weakObj.obj = helper; + [dbArray addObject:weakObj]; + } + } + + return instance; +} + +- (instancetype)init +{ + return [self initWithDBName:@"LKDB"]; +} + +- (instancetype)initWithDBName:(NSString *)dbname +{ + return [self initWithDBPath:[LKDBHelper getDBPathWithDBName:dbname]]; +} + +- (instancetype)initWithDBPath:(NSString *)filePath +{ + if ([LKDBUtils checkStringIsEmpty:filePath]) { + ///release self + self = nil; + return nil; + } + @synchronized([LKDBHelper class]) { + LKDBHelper *helper = [LKDBHelper dbHelperWithPath:filePath save:nil]; + if (helper) { + self = helper; + } else { + self = [super init]; + if (self) { + self.threadLock = [[NSRecursiveLock alloc] init]; + self.createdTableNames = [NSMutableArray array]; + self.lastExecuteDBTime = [[NSDate date] timeIntervalSince1970]; + self.autoCloseDBDelayTime = 15; + + [self setDBPath:filePath]; + [LKDBHelper dbHelperWithPath:nil save:self]; + } + } + } + return self; +} + +#pragma mark - init FMDB ++ (NSString *)getDBPathWithDBName:(NSString *)dbName +{ + NSString *fileName = nil; + + if ([dbName hasSuffix:@".db"] == NO) { + fileName = [NSString stringWithFormat:@"%@.db", dbName]; + } else { + fileName = dbName; + } + + NSString *filePath = [LKDBUtils getPathForDocuments:fileName inDir:@"db"]; + return filePath; +} + +- (void)setDBName:(NSString *)dbName +{ + [self setDBPath:[LKDBHelper getDBPathWithDBName:dbName]]; +} + +- (void)setDBPath:(NSString *)filePath +{ + [self.threadLock lock]; + if (self.bindingQueue && [self.dbPath isEqualToString:filePath]) { + LKErrorLog(@"current dbPath isEqual filePath :%@", filePath); + } else { + // reset encryptionKey + _encryptionKey = nil; + // set db path + self.dbPath = filePath; + [self openDB]; + } + [self.threadLock unlock]; +} + +- (void)openDB { + /// 重置所有配置 + [self.bindingQueue close]; + [self.createdTableNames removeAllObjects]; + + NSString *filePath = self.dbPath; + BOOL hasCreated = [LKDBUtils createDirectoryWithFilePath:filePath]; + if (!hasCreated) { + /// 数据库目录创建失败 + return; + } + + self.bindingQueue = [[FMDatabaseQueue alloc] initWithPath:filePath + flags:LKDBOpenFlags]; + [self.bindingQueue inDatabase:^(FMDatabase *db) { + db.logsErrors = LKDBLogErrorEnable; + }]; + +#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED + NSFileManager *fileManager = [NSFileManager defaultManager]; + if ([fileManager fileExistsAtPath:filePath]) { + [fileManager setAttributes:@{ NSFileProtectionKey: NSFileProtectionNone } ofItemAtPath:filePath error:nil]; + } +#endif +} + +- (void)closeDB { + [self.threadLock lock]; + [self.bindingQueue close]; + self.bindingQueue = nil; + [self.threadLock unlock]; +} + +#pragma mark - core +- (void)executeDB:(void (^)(FMDatabase *db))block +{ + if (!block) { + NSAssert(NO, @"block is nil!"); + return; + } + [self.threadLock lock]; + + if (self.usingdb != nil) { + block(self.usingdb); + } else { + if (self.bindingQueue == nil) { + [self openDB]; + if (_encryptionKey.length > 0) { + [self.bindingQueue inDatabase:^(FMDatabase *db) { + [db setKey:_encryptionKey]; + }]; + } + } + [self.bindingQueue inDatabase:^(FMDatabase *db) { + self.usingdb = db; + block(db); + self.usingdb = nil; + }]; + } + + self.lastExecuteDBTime = [[NSDate date] timeIntervalSince1970]; + + if (self.autoCloseDBDelayTime > 0) { + [self startAutoCloseTimer]; + } + + [self.threadLock unlock]; +} + +- (void)setAutoCloseDBTime:(NSInteger)time { + if (time < 0) { + time = 0; + } + self.autoCloseDBDelayTime = time; + if (time > 0) { + [self startAutoCloseTimer]; + } +} + +- (void)startAutoCloseTimer { + if (self.runingAutoCloseTimer) { + return; + } + self.runingAutoCloseTimer = YES; + __weak LKDBHelper *wself = self; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.autoCloseDBDelayTime * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{ + __strong LKDBHelper *self = wself; + [self.threadLock lock]; + self.runingAutoCloseTimer = NO; + BOOL hasClosed = [self autoCloseDBConnection]; + if (!hasClosed && self.autoCloseDBDelayTime > 0) { + [self startAutoCloseTimer]; + } + [self.threadLock unlock]; + }); +} + +- (BOOL)autoCloseDBConnection { + NSInteger now = [[NSDate date] timeIntervalSince1970]; + /// 如果10秒没有操作 则关闭数据库链接 + if (now - self.lastExecuteDBTime > 10) { + [self closeDB]; + return YES; + } + return NO; +} + +- (BOOL)executeSQL:(NSString *)sql arguments:(NSArray *)args +{ + __block BOOL execute = NO; + + [self executeDB:^(FMDatabase *db) { + if (args.count > 0) { + execute = [db executeUpdate:sql withArgumentsInArray:args]; + } else { + execute = [db executeUpdate:sql]; + } + + if (db.hadError) { + LKErrorLog(@" sql:%@ \n args:%@ \n sqlite error :%@ \n", sql, args, db.lastErrorMessage); + } + }]; + return execute; +} + +- (NSString *)executeScalarWithSQL:(NSString *)sql arguments:(NSArray *)args +{ + __block NSString *scalar = nil; + + [self executeDB:^(FMDatabase *db) { + FMResultSet *set = nil; + + if (args.count > 0) { + set = [db executeQuery:sql withArgumentsInArray:args]; + } else { + set = [db executeQuery:sql]; + } + + if (db.hadError) { + LKErrorLog(@" sql:%@ \n args:%@ \n sqlite error :%@ \n", sql, args, db.lastErrorMessage); + } + + if (([set columnCount] > 0) && [set next]) { + scalar = [set stringForColumnIndex:0]; + } + + [set close]; + }]; + return scalar; +} + +- (void)executeForTransaction:(BOOL (^)(LKDBHelper *))block +{ + LKDBHelper *helper = self; + + [self executeDB:^(FMDatabase *db) { + BOOL inTransacttion = db.isInTransaction; + + if (!inTransacttion) { + [db beginTransaction]; + } + + BOOL isCommit = NO; + + if (block) { + isCommit = block(helper); + } + + if (!inTransacttion) { + if (isCommit) { + [db commit]; + } else { + [db rollback]; + } + } + }]; +} + +// splice 'where' 拼接where语句 +- (NSMutableArray *)extractQuery:(NSMutableString *)query where:(id)where +{ + NSMutableArray *values = nil; + + if ([where isKindOfClass:[NSString class]] && ([LKDBUtils checkStringIsEmpty:where] == NO)) { + [query appendFormat:@" where %@", where]; + } else if ([where isKindOfClass:[NSDictionary class]]) { + NSDictionary *dicWhere = where; + + if (dicWhere.count > 0) { + values = [NSMutableArray arrayWithCapacity:dicWhere.count]; + NSString *wherekey = [self dictionaryToSqlWhere:where andValues:values]; + [query appendFormat:@" where %@", wherekey]; + } + } + + return values; +} + +// dic where parse +- (NSString *)dictionaryToSqlWhere:(NSDictionary *)dic andValues:(NSMutableArray *)values +{ + if (dic.count == 0) { + return @""; + } + NSMutableString *wherekey = [NSMutableString stringWithCapacity:0]; + [dic enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) { + if ([obj isKindOfClass:[NSArray class]]) { + NSArray *vlist = obj; + if (vlist.count == 0) { + return; + } + if (wherekey.length > 0) { + [wherekey appendString:@" and"]; + } + [wherekey appendFormat:@" %@ in(", key]; + [vlist enumerateObjectsUsingBlock:^(id vlist_obj, NSUInteger idx, BOOL *stop) { + if (idx > 0) { + [wherekey appendString:@","]; + } + [wherekey appendString:@"?"]; + [values addObject:vlist_obj]; + }]; + [wherekey appendString:@")"]; + } else { + if (wherekey.length > 0) { + [wherekey appendFormat:@" and %@=?", key]; + } else { + [wherekey appendFormat:@" %@=?", key]; + } + [values addObject:obj]; + } + }]; + return [wherekey copy]; +} + +// where sql statements about model primary keys +- (NSMutableString *)primaryKeyWhereSQLWithModel:(NSObject *)model addPValues:(NSMutableArray *)addPValues +{ + LKModelInfos *infos = [model.class getModelInfos]; + NSArray *primaryKeys = infos.primaryKeys; + NSMutableString *pwhere = [NSMutableString string]; + + if (primaryKeys.count > 0) { + for (NSInteger i = 0; i < primaryKeys.count; i++) { + NSString *pk = [primaryKeys objectAtIndex:i]; + + if ([LKDBUtils checkStringIsEmpty:pk] == NO) { + LKDBProperty *property = [infos objectWithSqlColumnName:pk]; + id pvalue = nil; + + if (property && [property.type isEqualToString:LKSQL_Mapping_UserCalculate]) { + pvalue = [model userGetValueForModel:property]; + } else if (pk && property) { + pvalue = [model modelGetValue:property]; + } + + if (pvalue) { + if (pwhere.length > 0) { + [pwhere appendString:@"and"]; + } + + if (addPValues) { + [pwhere appendFormat:@" %@=? ", pk]; + [addPValues addObject:pvalue]; + } else { + [pwhere appendFormat:@" %@='%@' ", pk, pvalue]; + } + } + } + } + } + + return pwhere; +} + +#pragma mark - set key +- (BOOL)setKey:(NSString *)key +{ + [self.threadLock lock]; + _encryptionKey = [key copy]; + __block BOOL success = NO; + if (self.bindingQueue && _encryptionKey.length > 0) { + [self executeDB:^(FMDatabase *db) { + success = [db setKey:_encryptionKey]; + }]; + } + [self.threadLock unlock]; + return success; +} +- (BOOL)rekey:(NSString *)key +{ + [self.threadLock lock]; + _encryptionKey = [key copy]; + __block BOOL success = NO; + if (self.bindingQueue && _encryptionKey.length > 0) { + [self executeDB:^(FMDatabase *db) { + success = [db rekey:_encryptionKey]; + }]; + } + [self.threadLock unlock]; + return success; +} +- (NSString *)encryptionKey +{ + [self.threadLock lock]; + NSString *key = _encryptionKey; + [self.threadLock unlock]; + return key; +} +#pragma mark - dealloc +- (void)dealloc +{ + NSMutableArray *dbArray = [LKDBHelper dbHelperSingleArray]; + @synchronized(dbArray) { + NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet]; + for (NSInteger i = 0; i < dbArray.count; i++) { + LKDBWeakObject *weakObj = [dbArray objectAtIndex:i]; + if (weakObj.obj == self){ + weakObj.obj = nil; + [indexSet addIndex:i]; + } + } + [dbArray removeObjectsAtIndexes:indexSet]; + } + + [self.bindingQueue close]; + self.usingdb = nil; + self.bindingQueue = nil; + self.dbPath = nil; + self.threadLock = nil; +} + +@end +@implementation LKDBHelper (DatabaseManager) + +- (void)dropAllTable +{ + [self executeDB:^(FMDatabase *db) { + FMResultSet *set = [db executeQuery:@"select name from sqlite_master where type='table'"]; + NSMutableArray *dropTables = [NSMutableArray arrayWithCapacity:0]; + + while ([set next]) { + NSString *tableName = [set stringForColumnIndex:0]; + if (tableName) { + [dropTables addObject:tableName]; + } + } + + [set close]; + + for (NSString *tableName in dropTables) { + if ([tableName hasPrefix:@"sqlite_"] == NO) { + NSString *dropTable = [NSString stringWithFormat:@"drop table %@", tableName]; + [db executeUpdate:dropTable]; + } + } + + [self.createdTableNames removeAllObjects]; + }]; +} + +- (BOOL)dropTableWithClass:(Class)modelClass +{ + return [self dropTableWithTableName:[modelClass getTableName]]; +} + +- (BOOL)dropTableWithTableName:(NSString *)tableName +{ + LKDBCheck_tableNameIsInvalid(tableName); + + // 检测是否创建过表 + if ([self getTableCreatedWithTableName:tableName] == NO) { + return YES; + } + + NSString *dropTable = [NSString stringWithFormat:@"drop table %@", tableName]; + + BOOL isDrop = [self executeSQL:dropTable arguments:nil]; + + [self.threadLock lock]; + [self.createdTableNames removeObject:tableName]; + [self.threadLock unlock]; + + return isDrop; +} + +- (void)fixSqlColumnsWithClass:(Class)clazz tableName:(NSString *)tableName +{ + [self executeDB:^(FMDatabase *db) { + LKModelInfos *infos = [clazz getModelInfos]; + + NSString *select = [NSString stringWithFormat:@"select * from %@ limit 0", tableName]; + FMResultSet *set = [db executeQuery:select]; + NSArray *columnArray = set.columnNameToIndexMap.allKeys; + [set close]; + + NSMutableArray *alterAddColumns = [NSMutableArray array]; + + for (NSInteger i = 0; i < infos.count; i++) { + LKDBProperty *property = [infos objectWithIndex:i]; + + if ([property.sqlColumnName.lowercaseString isEqualToString:@"rowid"]) { + continue; + } + + ///数据库中不存在 需要alter add + if ([columnArray containsObject:property.sqlColumnName.lowercaseString] == NO) { + NSMutableString *addColumePars = [NSMutableString stringWithFormat:@"%@ %@", property.sqlColumnName, property.sqlColumnType]; + [clazz columnAttributeWithProperty:property]; + + if ((property.length > 0) && [property.sqlColumnType isEqualToString:LKSQL_Type_Text]) { + [addColumePars appendFormat:@"(%ld)", (long)property.length]; + } + + if (property.isNotNull) { + [addColumePars appendFormat:@" %@", LKSQL_Attribute_NotNull]; + } + + if (property.checkValue) { + [addColumePars appendFormat:@" %@(%@)", LKSQL_Attribute_Check, property.checkValue]; + } + + if (property.defaultValue) { + [addColumePars appendFormat:@" %@ %@", LKSQL_Attribute_Default, property.defaultValue]; + } + NSString *alertSQL = [NSString stringWithFormat:@"alter table %@ add column %@", tableName, addColumePars]; + NSString *defaultValue = property.defaultValue ?: @"0"; + if ([property.sqlColumnType isEqualToString:LKSQL_Type_Text]) { + if (LKDBNullIsEmptyString) { + defaultValue = @"''"; + } else { + defaultValue = @"null"; + } + } + NSString *initColumnValue = [NSString stringWithFormat:@"update %@ set %@=%@", tableName, property.sqlColumnName, defaultValue]; + BOOL success = [db executeUpdate:alertSQL]; + if (success) { + [db executeUpdate:initColumnValue]; + [alterAddColumns addObject:property]; + } + } + } + + if (alterAddColumns.count > 0) { + [clazz dbDidAlterTable:self tableName:tableName addColumns:alterAddColumns]; + } + }]; +} + +- (BOOL)_createTableWithModelClass:(Class)modelClass tableName:(NSString *)tableName +{ + if (!tableName.length) { + NSAssert(NO, @"none table name"); + return NO; + } + if ([self getTableCreatedWithTableName:tableName]) { + // 已创建表 就跳过 + [self.threadLock lock]; + if ([self.createdTableNames containsObject:tableName] == NO) { + [self.createdTableNames addObject:tableName]; + } + [self.threadLock unlock]; + + [self fixSqlColumnsWithClass:modelClass tableName:tableName]; + return YES; + } + + LKModelInfos *infos = [modelClass getModelInfos]; + + if (infos.count == 0) { + LKErrorLog(@"Class: %@ 0属性 不需要创建表", NSStringFromClass(modelClass)); + return NO; + } + + NSArray *primaryKeys = infos.primaryKeys; + NSString *rowidAliasName = [modelClass db_rowidAliasName]; + + NSMutableString *table_pars = [NSMutableString string]; + + for (NSInteger i = 0; i < infos.count; i++) { + if (i > 0) { + [table_pars appendString:@","]; + } + + LKDBProperty *property = [infos objectWithIndex:i]; + [modelClass columnAttributeWithProperty:property]; + + NSString *columnType = property.sqlColumnType; + + [table_pars appendFormat:@"%@ %@", property.sqlColumnName, columnType]; + + if ([property.sqlColumnType isEqualToString:LKSQL_Type_Text]) { + if (property.length > 0) { + [table_pars appendFormat:@"(%ld)", (long)property.length]; + } + } + + if (property.isNotNull) { + [table_pars appendFormat:@" %@", LKSQL_Attribute_NotNull]; + } + + if (property.isUnique) { + [table_pars appendFormat:@" %@", LKSQL_Attribute_Unique]; + } + + if (property.checkValue) { + [table_pars appendFormat:@" %@(%@)", LKSQL_Attribute_Check, property.checkValue]; + } + + if (property.defaultValue) { + [table_pars appendFormat:@" %@ %@", LKSQL_Attribute_Default, property.defaultValue]; + } + + if (rowidAliasName.length > 0) { + if ([property.sqlColumnName isEqualToString:rowidAliasName]) { + [table_pars appendString:@" primary key autoincrement"]; + } + } + } + + NSMutableString *pksb = [NSMutableString string]; + + ///联合主键 + if (rowidAliasName.length == 0) { + if (primaryKeys.count > 0) { + pksb = [NSMutableString string]; + + for (NSInteger i = 0; i < primaryKeys.count; i++) { + NSString *pk = [primaryKeys objectAtIndex:i]; + + if (pksb.length > 0) { + [pksb appendString:@","]; + } + + [pksb appendString:pk]; + } + + if (pksb.length > 0) { + [pksb insertString:@",primary key(" atIndex:0]; + [pksb appendString:@")"]; + } + } + } + + NSString *createTableSQL = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@(%@%@)", tableName, table_pars, pksb]; + + BOOL isCreated = [self executeSQL:createTableSQL arguments:nil]; + + [self.threadLock lock]; + if (isCreated) { + [self.createdTableNames addObject:tableName]; + [modelClass dbDidCreateTable:self tableName:tableName]; + } + [self.threadLock unlock]; + + return isCreated; +} + +- (BOOL)getTableCreatedWithClass:(Class)modelClass +{ + return [self getTableCreatedWithTableName:[modelClass getTableName]]; +} + +- (BOOL)getTableCreatedWithTableName:(NSString *)tableName +{ + __block BOOL isTableCreated = NO; + + [self executeDB:^(FMDatabase *db) { + FMResultSet *set = [db executeQuery:@"select count(name) from sqlite_master where type='table' and name=?", tableName]; + if ([set next]) { + if ([set intForColumnIndex:0] > 0) { + isTableCreated = YES; + } + } + [set close]; + }]; + return isTableCreated; +} + +@end + +@implementation LKDBHelper (DatabaseExecute) + +- (id)modelValueWithProperty:(LKDBProperty *)property model:(NSObject *)model +{ + id value = nil; + + if (property.isUserCalculate) { + value = [model userGetValueForModel:property]; + } else { + value = [model modelGetValue:property]; + } + + if (value == nil) { + if (LKDBNullIsEmptyString) { + value = @""; + } else { + value = [NSNull null]; + } + } + + return value; +} + +- (void)asyncBlock:(void (^)(void))block +{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block); +} + +#pragma mark - row count operation +- (NSInteger)rowCount:(Class)modelClass where:(id)where +{ + return [self _rowCountWithTableName:nil where:where modelClass:modelClass]; +} + +- (void)rowCount:(Class)modelClass where:(id)where callback:(void (^)(NSInteger))callback +{ + if (!callback) { + return; + } + LKDBCode_Async_Begin; + NSInteger result = [sself _rowCountWithTableName:nil where:where modelClass:modelClass]; + callback(result); + LKDBCode_Async_End; +} + +- (NSInteger)rowCountWithTableName:(NSString *)tableName where:(id)where +{ + return [self _rowCountWithTableName:tableName where:where modelClass:nil]; +} + +- (NSInteger)_rowCountWithTableName:(NSString *)tableName where:(id)where modelClass:(Class)modelClass +{ + if (!tableName) { + tableName = [modelClass getTableName]; + } + + LKDBCheck_tableNameIsInvalid(tableName); + + if (modelClass) { + // 检测是否创建过表 + [self.threadLock lock]; + if ([self.createdTableNames containsObject:tableName] == NO) { + [self _createTableWithModelClass:modelClass tableName:tableName]; + } + [self.threadLock unlock]; + } + + NSMutableString *rowCountSql = [NSMutableString stringWithFormat:@"select count(rowid) from %@", tableName]; + + NSMutableArray *valuesarray = [self extractQuery:rowCountSql where:where]; + NSInteger result = [[self executeScalarWithSQL:rowCountSql arguments:valuesarray] integerValue]; + + return result; +} + +#pragma mark - search operation +- (NSMutableArray *)search:(Class)modelClass where:(id)where orderBy:(NSString *)orderBy offset:(NSInteger)offset count:(NSInteger)count +{ + return [self searchBase:modelClass columns:nil where:where orderBy:orderBy offset:offset count:count]; +} + +- (NSMutableArray *)search:(Class)modelClass column:(id)columns where:(id)where orderBy:(NSString *)orderBy offset:(NSInteger)offset count:(NSInteger)count +{ + return [self searchBase:modelClass columns:columns where:where orderBy:orderBy offset:offset count:count]; +} + +- (id)searchSingle:(Class)modelClass where:(id)where orderBy:(NSString *)orderBy +{ + NSMutableArray *array = [self searchBase:modelClass columns:nil where:where orderBy:orderBy offset:0 count:1]; + + if (array.count > 0) { + return [array objectAtIndex:0]; + } + + return nil; +} + +- (void)search:(Class)modelClass where:(id)where orderBy:(NSString *)orderBy offset:(NSInteger)offset count:(NSInteger)count callback:(void (^)(NSMutableArray *))block +{ + if (!block) { + return; + } + LKDBCode_Async_Begin; + LKDBQueryParams *params = [[LKDBQueryParams alloc] init]; + params.toClass = modelClass; + + if ([where isKindOfClass:[NSDictionary class]]) { + params.whereDic = where; + } else if ([where isKindOfClass:[NSString class]]) { + params.where = where; + } + + params.orderBy = orderBy; + params.offset = offset; + params.count = count; + + NSMutableArray *array = [sself searchBaseWithParams:params]; + block(array); + LKDBCode_Async_End; +} + +- (NSMutableArray *)searchBaseWithParams:(LKDBQueryParams *)params +{ + if (params.toClass == nil) { + LKErrorLog(@"you search pars:%@! \n toClass is nil", params.getAllPropertysString); + return nil; + } + + NSString *db_tableName = params.tableName; + + if ([LKDBUtils checkStringIsEmpty:db_tableName]) { + db_tableName = [params.toClass getTableName]; + } + + if ([LKDBUtils checkStringIsEmpty:db_tableName]) { + LKErrorLog(@"you search pars:%@! \n tableName is empty", params.getAllPropertysString); + return nil; + } + + // 检测是否创建过表 + [self.threadLock lock]; + if ([self.createdTableNames containsObject:db_tableName] == NO) { + [self _createTableWithModelClass:params.toClass tableName:db_tableName]; + } + [self.threadLock unlock]; + + NSString *columnsString = nil; + NSUInteger columnCount = 0; + + if (params.columnArray.count > 0) { + columnCount = params.columnArray.count; + columnsString = [params.columnArray componentsJoinedByString:@","]; + } else if ([LKDBUtils checkStringIsEmpty:params.columns] == NO) { + columnsString = params.columns; + NSArray *array = [params.columns componentsSeparatedByString:@","]; + columnCount = array.count; + } else { + columnsString = @"*"; + } + + NSMutableString *query = [NSMutableString stringWithFormat:@"select %@,rowid from @t", columnsString]; + NSMutableArray *whereValues = nil; + + if (params.whereDic.count > 0) { + whereValues = [NSMutableArray arrayWithCapacity:params.whereDic.count]; + NSString *wherekey = [self dictionaryToSqlWhere:params.whereDic andValues:whereValues]; + [query appendFormat:@" where %@", wherekey]; + } else if ([LKDBUtils checkStringIsEmpty:params.where] == NO) { + [query appendFormat:@" where %@", params.where]; + } + + [self sqlString:query groupBy:params.groupBy orderBy:params.orderBy offset:params.offset count:params.count]; + + // replace @t to model table name + NSString *replaceTableName = [NSString stringWithFormat:@" %@ ", db_tableName]; + + if ([query hasSuffix:@" @t"]) { + [query appendString:@" "]; + } + + [query replaceOccurrencesOfString:@" @t " withString:replaceTableName options:NSCaseInsensitiveSearch range:NSMakeRange(0, query.length)]; + + __block NSMutableArray *results = nil; + [self executeDB:^(FMDatabase *db) { + FMResultSet *set = nil; + + if (whereValues.count == 0) { + set = [db executeQuery:query]; + } else { + set = [db executeQuery:query withArgumentsInArray:whereValues]; + } + + if (columnCount == 1) { + results = [self executeOneColumnResult:set]; + } else { + results = [self executeResult:set Class:params.toClass tableName:db_tableName]; + } + + [set close]; + }]; + return results; +} + +- (NSMutableArray *)searchWithParams:(LKDBQueryParams *)params +{ + if (params.callback) { + LKDBCode_Async_Begin; + NSMutableArray *array = [sself searchBaseWithParams:params]; + params.callback(array); + LKDBCode_Async_End; + return nil; + } else { + return [self searchBaseWithParams:params]; + } +} + +- (NSMutableArray *)searchBase:(Class)modelClass columns:(id)columns where:(id)where orderBy:(NSString *)orderBy offset:(NSInteger)offset count:(NSInteger)count +{ + LKDBQueryParams *params = [[LKDBQueryParams alloc] init]; + + params.toClass = modelClass; + + if ([columns isKindOfClass:[NSArray class]]) { + params.columnArray = columns; + } else if ([columns isKindOfClass:[NSString class]]) { + params.columns = columns; + } + + if ([where isKindOfClass:[NSDictionary class]]) { + params.whereDic = where; + } else if ([where isKindOfClass:[NSString class]]) { + params.where = where; + } + + params.orderBy = orderBy; + params.offset = offset; + params.count = count; + + return [self searchBaseWithParams:params]; +} + +- (NSString *)replaceTableNameIfNeeded:(NSString *)sql withModelClass:(Class)modelClass +{ + if (!modelClass) { + return sql; + } + + NSString *tableName = [modelClass getTableName]; + if (!tableName) { + return sql; + } + + if (modelClass) { + // 检测是否创建过表 + [self.threadLock lock]; + if ([self.createdTableNames containsObject:tableName] == NO) { + [self _createTableWithModelClass:modelClass tableName:tableName]; + } + [self.threadLock unlock]; + } + + // replace @t to model table name + NSString *replaceString = [tableName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; + if ([sql hasSuffix:@" @t"]) { + sql = [sql stringByAppendingString:@" "]; + } + if ([sql componentsSeparatedByString:@" from "].count == 2 && [sql rangeOfString:@" join "].length == 0) { + sql = [sql stringByReplacingOccurrencesOfString:@" from " withString:[NSString stringWithFormat:@",%@.rowid from ", replaceString]]; + } + + sql = [sql stringByReplacingOccurrencesOfString:@" @t " + withString: + [NSString stringWithFormat:@" %@ ", replaceString]]; + sql = [sql stringByReplacingOccurrencesOfString:@" @t," + withString: + [NSString stringWithFormat:@" %@,", replaceString]]; + sql = [sql stringByReplacingOccurrencesOfString:@",@t " + withString: + [NSString stringWithFormat:@",%@ ", replaceString]]; + + return sql; +} + +- (NSMutableArray *)searchWithSQL:(NSString *)sql toClass:(Class)modelClass +{ + sql = [self replaceTableNameIfNeeded:sql withModelClass:modelClass]; + return [self searchWithRAWSQL:sql toClass:modelClass]; +} + +- (NSMutableArray *)searchWithRAWSQL:(NSString *)sql toClass:(Class)modelClass +{ + __block NSMutableArray *results = nil; + [self executeDB:^(FMDatabase *db) { + FMResultSet *set = [db executeQuery:sql]; + results = [self executeResult:set Class:modelClass tableName:nil]; + [set close]; + }]; + return results; +} + +- (NSMutableArray *)search:(Class)modelClass withSQL:(NSString *)sql, ... +{ + va_list args; + va_start(args, sql); + + sql = [self replaceTableNameIfNeeded:sql withModelClass:modelClass]; + + va_list *argsPoint = &args; + __block NSMutableArray *results = nil; + [self executeDB:^(FMDatabase *db) { + FMResultSet *set = [db executeQuery:sql withVAList:*argsPoint]; + results = [self executeResult:set Class:modelClass tableName:nil]; + [set close]; + }]; + + va_end(args); + return results; +} + +- (void)sqlString:(NSMutableString *)sql groupBy:(NSString *)groupBy orderBy:(NSString *)orderby offset:(NSInteger)offset count:(NSInteger)count +{ + if ([LKDBUtils checkStringIsEmpty:groupBy] == NO) { + [sql appendFormat:@" group by %@", groupBy]; + } + + if ([LKDBUtils checkStringIsEmpty:orderby] == NO) { + [sql appendFormat:@" order by %@", orderby]; + } + + if (count > 0) { + [sql appendFormat:@" limit %ld offset %ld", (long)count, (long)offset]; + } else if (offset > 0) { + [sql appendFormat:@" limit %d offset %ld", INT_MAX, (long)offset]; + } +} + +- (NSMutableArray *)executeOneColumnResult:(FMResultSet *)set +{ + NSMutableArray *array = [NSMutableArray arrayWithCapacity:0]; + + while ([set next]) { + NSString *string = [set stringForColumnIndex:0]; + + if (string) { + [array addObject:string]; + } else { + NSData *data = [set dataForColumnIndex:0]; + + if (data) { + [array addObject:data]; + } + } + } + + return array; +} + +- (NSMutableArray *)executeResult:(FMResultSet *)set Class:(Class)modelClass tableName:(NSString *)tableName +{ + NSMutableArray *array = [NSMutableArray arrayWithCapacity:0]; + if (!modelClass) { + while ([set next]) { + NSDictionary *dict = [set resultDictionary]; + if (dict) { + [array addObject:dict]; + } + } + } else { + LKModelInfos *infos = [modelClass getModelInfos]; + NSInteger columnCount = [set columnCount]; + + ///当主键是int类型时 会替换掉rowid + NSString *rowidAliasName = [modelClass db_rowidAliasName]; + + while ([set next]) { + NSObject *bindingModel = [[modelClass alloc] init]; + if (bindingModel == nil) { + continue; + } + for (int i = 0; i < columnCount; i++) { + NSString *sqlName = [set columnNameForIndex:i]; + LKDBProperty *property = [infos objectWithSqlColumnName:sqlName]; + + BOOL isRowid = [[sqlName lowercaseString] isEqualToString:@"rowid"]; + + if ((isRowid == NO) && (property == nil)) { + continue; + } + + if (isRowid && ((property == nil) || [property.sqlColumnType isEqualToString:LKSQL_Type_Int])) { + bindingModel.rowid = [set longForColumnIndex:i]; + } else { + BOOL isUserCalculate = [property.type isEqualToString:LKSQL_Mapping_UserCalculate]; + + if (property.propertyName && (isUserCalculate == NO)) { + NSString *sqlValue = [set stringForColumnIndex:i]; + [bindingModel modelSetValue:property value:sqlValue]; + + if ([rowidAliasName isEqualToString:sqlName]) { + bindingModel.rowid = [set longForColumnIndex:i]; + } + } else { + NSData *sqlData = [set dataForColumnIndex:i]; + NSString *sqlValue = nil; + if (sqlData) { + sqlValue = [[NSString alloc] initWithData:sqlData encoding:NSUTF8StringEncoding]; + } + [bindingModel userSetValueForModel:property value:sqlValue ?: sqlData]; + } + } + } + bindingModel.db_tableName = tableName; + [modelClass dbDidSeleted:bindingModel]; + [array addObject:bindingModel]; + } + } + return array; +} + +#pragma mark - insert operation +- (BOOL)insertToDB:(NSObject *)model +{ + return [self insertBase:model]; +} + +- (void)insertToDB:(NSObject *)model callback:(void (^)(BOOL))block +{ + LKDBCode_Async_Begin; + BOOL result = [sself insertBase:model]; + if (block) { + block(result); + } + LKDBCode_Async_End; +} + +- (BOOL)insertWhenNotExists:(NSObject *)model +{ + if ([self isExistsModel:model] == NO) { + return [self insertToDB:model]; + } + return NO; +} + +- (void)insertWhenNotExists:(NSObject *)model callback:(void (^)(BOOL))block +{ + LKDBCode_Async_Begin; + BOOL result = [sself insertWhenNotExists:model]; + if (block) { + block(result); + } + LKDBCode_Async_End; +} + +- (BOOL)insertBase:(NSObject *)model +{ + LKDBCheck_modelIsInvalid(model); + + Class modelClass = model.class; + + // callback + if ([modelClass dbWillInsert:model] == NO) { + LKErrorLog(@"your cancel %@ insert", model); + return NO; + } + + [model setDb_inserting:YES]; + + NSString *db_tableName = model.db_tableName ?: [modelClass getTableName]; + + // 检测是否创建过表 + [self.threadLock lock]; + if ([self.createdTableNames containsObject:db_tableName] == NO) { + [self _createTableWithModelClass:modelClass tableName:db_tableName]; + } + [self.threadLock unlock]; + + // -- + LKModelInfos *infos = [modelClass getModelInfos]; + + NSMutableString *insertKey = [NSMutableString stringWithCapacity:0]; + NSMutableString *insertValuesString = [NSMutableString stringWithCapacity:0]; + NSMutableArray *insertValues = [NSMutableArray arrayWithCapacity:infos.count]; + + LKDBProperty *primaryProperty = [model singlePrimaryKeyProperty]; + + for (NSInteger i = 0; i < infos.count; i++) { + LKDBProperty *property = [infos objectWithIndex:i]; + + if ([LKDBUtils checkStringIsEmpty:property.sqlColumnName]) { + continue; + } + + if ([property isEqual:primaryProperty]) { + if ([property.sqlColumnType isEqualToString:LKSQL_Type_Int] && [model singlePrimaryKeyValueIsEmpty]) { + continue; + } + } + + id value = [self modelValueWithProperty:property model:model]; + if (value == nil) { + continue; + } + ///跳过 rowid = 0 的属性 + if ([property.sqlColumnName isEqualToString:@"rowid"] && ([value intValue] == 0)) { + continue; + } + + if (insertKey.length > 0) { + [insertKey appendString:@","]; + [insertValuesString appendString:@","]; + } + + [insertKey appendString:property.sqlColumnName]; + [insertValuesString appendString:@"?"]; + + [insertValues addObject:value]; + } + + // 拼接insertSQL 语句 采用 replace 插入 + NSString *insertSQL = [NSString stringWithFormat:@"replace into %@(%@) values(%@)", db_tableName, insertKey, insertValuesString]; + + __block BOOL execute = NO; + __block sqlite_int64 lastInsertRowId = 0; + + [self executeDB:^(FMDatabase *db) { + execute = [db executeUpdate:insertSQL withArgumentsInArray:insertValues]; + lastInsertRowId = db.lastInsertRowId; + + if (db.hadError) { + LKErrorLog(@" sql:%@ \n args:%@ \n sqlite error :%@ \n", insertSQL, insertValues, db.lastErrorMessage); + } + }]; + + model.rowid = (NSInteger)lastInsertRowId; + + [model setDb_inserting:NO]; + + // callback + [modelClass dbDidInserted:model result:execute]; + return execute; +} + +#pragma mark - update operation +- (BOOL)updateToDB:(NSObject *)model where:(id)where +{ + return [self updateToDBBase:model where:where]; +} + +- (void)updateToDB:(NSObject *)model where:(id)where callback:(void (^)(BOOL))block +{ + LKDBCode_Async_Begin; + BOOL result = [sself updateToDBBase:model where:where]; + if (block) { + block(result); + } + LKDBCode_Async_End; +} + +- (BOOL)updateToDBBase:(NSObject *)model where:(id)where +{ + LKDBCheck_modelIsInvalid(model); + + Class modelClass = model.class; + + // callback + if ([modelClass dbWillUpdate:model] == NO) { + LKErrorLog(@"you cancel %@ update.", model); + return NO; + } + + NSString *db_tableName = model.db_tableName ?: [modelClass getTableName]; + + // 检测是否创建过表 + [self.threadLock lock]; + if ([self.createdTableNames containsObject:db_tableName] == NO) { + [self _createTableWithModelClass:modelClass tableName:db_tableName]; + } + [self.threadLock unlock]; + + LKModelInfos *infos = [modelClass getModelInfos]; + + NSMutableString *updateKey = [NSMutableString string]; + NSMutableArray *updateValues = [NSMutableArray arrayWithCapacity:infos.count]; + + for (NSInteger i = 0; i < infos.count; i++) { + LKDBProperty *property = [infos objectWithIndex:i]; + if ([LKDBUtils checkStringIsEmpty:property.sqlColumnName]) { + continue; + } + id value = [self modelValueWithProperty:property model:model]; + if (value == nil) { + continue; + } + ///跳过 rowid = 0 的属性 + if ([property.sqlColumnName isEqualToString:@"rowid"]) { + int rowid = [value intValue]; + if (rowid > 0) { + ///如果rowid 已经存在就不修改 + NSString *rowidWhere = [NSString stringWithFormat:@"rowid=%d", rowid]; + NSInteger rowCount = [self rowCountWithTableName:db_tableName where:rowidWhere]; + if (rowCount > 0) { + continue; + } + } else { + continue; + } + } + if (updateKey.length > 0) { + [updateKey appendString:@","]; + } + [updateKey appendFormat:@"%@=?", property.sqlColumnName]; + [updateValues addObject:value]; + } + + NSMutableString *updateSQL = [NSMutableString stringWithFormat:@"update %@ set %@ where ", db_tableName, updateKey]; + // 添加where 语句 + if ([where isKindOfClass:[NSString class]] && ([LKDBUtils checkStringIsEmpty:where] == NO)) { + [updateSQL appendString:where]; + } else if ([where isKindOfClass:[NSDictionary class]] && ([(NSDictionary *)where count] > 0)) { + NSMutableArray *valuearray = [NSMutableArray array]; + NSString *sqlwhere = [self dictionaryToSqlWhere:where andValues:valuearray]; + + [updateSQL appendString:sqlwhere]; + [updateValues addObjectsFromArray:valuearray]; + } else if (model.rowid > 0) { + [updateSQL appendFormat:@" rowid=%ld", (long)model.rowid]; + } else { + // 如果不通过 rowid 来 更新数据 那 primarykey 一定要有值 + NSString *pwhere = [self primaryKeyWhereSQLWithModel:model addPValues:updateValues]; + + if (pwhere.length == 0) { + LKErrorLog(@"database update fail : %@ no find primary key!", NSStringFromClass(modelClass)); + return NO; + } + + [updateSQL appendString:pwhere]; + } + + BOOL execute = [self executeSQL:updateSQL arguments:updateValues]; + // callback + [modelClass dbDidUpdated:model result:execute]; + + return execute; +} + +- (BOOL)updateToDB:(Class)modelClass set:(NSString *)sets where:(id)where +{ + return [self _updateToDBWithTableName:nil set:sets where:where modelClass:modelClass]; +} + +- (BOOL)updateToDBWithTableName:(NSString *)tableName set:(NSString *)sets where:(id)where +{ + return [self _updateToDBWithTableName:tableName set:sets where:where modelClass:nil]; +} + +- (BOOL)_updateToDBWithTableName:(NSString *)tableName set:(NSString *)sets where:(id)where modelClass:(Class)modelClass +{ + if (!tableName) { + tableName = [modelClass getTableName]; + } + + LKDBCheck_tableNameIsInvalid(tableName); + + if (modelClass) { + // 检测是否创建过表 + [self.threadLock lock]; + if ([self.createdTableNames containsObject:tableName] == NO) { + [self _createTableWithModelClass:modelClass tableName:tableName]; + } + [self.threadLock unlock]; + } + + NSMutableString *updateSQL = [NSMutableString stringWithFormat:@"update %@ set %@ ", tableName, sets]; + NSMutableArray *updateValues = [self extractQuery:updateSQL where:where]; + + BOOL execute = [self executeSQL:updateSQL arguments:updateValues]; + + return execute; +} + +#pragma mark - delete operation +- (BOOL)deleteToDB:(NSObject *)model +{ + return [self deleteToDBBase:model]; +} + +- (void)deleteToDB:(NSObject *)model callback:(void (^)(BOOL))block +{ + LKDBCode_Async_Begin; + BOOL isDeleted = [sself deleteToDBBase:model]; + if (block) { + block(isDeleted); + } + LKDBCode_Async_End; +} + +- (BOOL)deleteToDBBase:(NSObject *)model +{ + LKDBCheck_modelIsInvalid(model); + + Class modelClass = model.class; + + // callback + if ([modelClass dbWillDelete:model] == NO) { + LKErrorLog(@"you cancel %@ delete", model); + return NO; + } + + NSString *db_tableName = model.db_tableName ?: [modelClass getTableName]; + + // 检测是否创建过表 + [self.threadLock lock]; + if ([self.createdTableNames containsObject:db_tableName] == NO) { + [self _createTableWithModelClass:modelClass tableName:db_tableName]; + } + [self.threadLock unlock]; + + NSMutableString *deleteSQL = [NSMutableString stringWithFormat:@"delete from %@ where ", db_tableName]; + NSMutableArray *parsArray = [NSMutableArray array]; + + if (model.rowid > 0) { + [deleteSQL appendFormat:@"rowid = %ld", (long)model.rowid]; + } else { + NSString *pwhere = [self primaryKeyWhereSQLWithModel:model addPValues:parsArray]; + + if (pwhere.length == 0) { + LKErrorLog(@"delete fail : %@ primary value is nil", NSStringFromClass(modelClass)); + return NO; + } + + [deleteSQL appendString:pwhere]; + } + + if (parsArray.count == 0) { + parsArray = nil; + } + + BOOL execute = [self executeSQL:deleteSQL arguments:parsArray]; + + // callback + [modelClass dbDidDeleted:model result:execute]; + + return execute; +} + +- (BOOL)deleteWithClass:(Class)modelClass where:(id)where +{ + return [self _deleteWithTableName:nil where:where modelClass:modelClass]; +} + +- (void)deleteWithClass:(Class)modelClass where:(id)where callback:(void (^)(BOOL))block +{ + LKDBCode_Async_Begin; + BOOL isDeleted = [sself _deleteWithTableName:nil where:where modelClass:modelClass]; + if (block) { + block(isDeleted); + } + LKDBCode_Async_End; +} + +- (BOOL)deleteWithTableName:(NSString *)tableName where:(id)where +{ + return [self _deleteWithTableName:tableName where:where modelClass:nil]; +} + +- (BOOL)_deleteWithTableName:(NSString *)tableName where:(id)where modelClass:(Class)modelClass +{ + if (!tableName) { + tableName = [modelClass getTableName]; + } + + LKDBCheck_tableNameIsInvalid(tableName); + + if (modelClass) { + // 检测是否创建过表 + [self.threadLock lock]; + if ([self.createdTableNames containsObject:tableName] == NO) { + [self _createTableWithModelClass:modelClass tableName:tableName]; + } + [self.threadLock unlock]; + } + + NSMutableString *deleteSQL = [NSMutableString stringWithFormat:@"delete from %@", tableName]; + NSMutableArray *values = [self extractQuery:deleteSQL where:where]; + + BOOL result = [self executeSQL:deleteSQL arguments:values]; + return result; +} + +#pragma mark - other operation +- (BOOL)isExistsModel:(NSObject *)model +{ + LKDBCheck_modelIsInvalid(model); + NSString *pwhere = nil; + + if (model.rowid > 0) { + pwhere = [NSString stringWithFormat:@"rowid=%ld", (long)model.rowid]; + } else { + pwhere = [self primaryKeyWhereSQLWithModel:model addPValues:nil]; + } + + if (pwhere.length == 0) { + LKErrorLog(@"exists model fail: primary key is nil or invalid"); + return NO; + } + + return [self isExistsClass:model.class where:pwhere]; +} + +- (BOOL)isExistsClass:(Class)modelClass where:(id)where +{ + return [self isExistsWithTableName:[modelClass getTableName] where:where]; +} + +- (BOOL)isExistsWithTableName:(NSString *)tableName where:(id)where +{ + return [self rowCountWithTableName:tableName where:where] > 0; +} + +#pragma mark - clear operation + ++ (void)clearTableData:(Class)modelClass +{ + [[modelClass getUsingLKDBHelper] deleteWithClass:modelClass where:nil]; +} + ++ (void)clearNoneImage:(Class)modelClass columns:(NSArray *)columns +{ + [self clearFileWithTable:modelClass columns:columns type:1]; +} + ++ (void)clearNoneData:(Class)modelClass columns:(NSArray *)columns +{ + [self clearFileWithTable:modelClass columns:columns type:2]; +} + +#define LKTestDirFilename @"LKTestDirFilename111" ++ (void)clearFileWithTable:(Class)modelClass columns:(NSArray *)columns type:(NSInteger)type +{ + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{ + NSString *testpath = nil; + switch (type) { + case 1: { + testpath = [modelClass getDBImagePathWithName:LKTestDirFilename]; + } break; + case 2: { + testpath = [modelClass getDBDataPathWithName:LKTestDirFilename]; + } break; + } + + if ([LKDBUtils checkStringIsEmpty:testpath]) { + return; + } + + NSString *dir = [testpath stringByReplacingOccurrencesOfString:LKTestDirFilename withString:@""]; + + NSUInteger count = columns.count; + + // 获取该目录下所有文件名 + NSArray *files = [LKDBUtils getFilenamesWithDir:dir]; + + NSString *seleteColumn = [columns componentsJoinedByString:@","]; + NSMutableString *whereStr = [NSMutableString string]; + + for (NSInteger i = 0; i < count; i++) { + [whereStr appendFormat:@" %@ != '' ", [columns objectAtIndex:i]]; + + if (i < count - 1) { + [whereStr appendString:@" or "]; + } + } + + NSString *querySql = [NSString stringWithFormat:@"select %@ from %@ where %@", seleteColumn, [modelClass getTableName], whereStr]; + __block NSArray *dbfiles; + [[modelClass getUsingLKDBHelper] executeDB:^(FMDatabase *db) { + NSMutableArray *tempfiles = [NSMutableArray arrayWithCapacity:6]; + FMResultSet *set = [db executeQuery:querySql]; + + while ([set next]) { + for (int j = 0; j < count; j++) { + NSString *str = [set stringForColumnIndex:j]; + + if ([LKDBUtils checkStringIsEmpty:str] == NO) { + [tempfiles addObject:str]; + } + } + } + + [set close]; + dbfiles = tempfiles; + }]; + + // 遍历 当不再数据库记录中 就删除 + for (NSString *deletefile in files) { + if ([dbfiles indexOfObject:deletefile] == NSNotFound) { + [LKDBUtils deleteWithFilepath:[dir stringByAppendingPathComponent:deletefile]]; + } + } + }); +} + +@end + +@implementation LKDBHelper (Deprecated_Nonfunctional) +- (void)setEncryptionKey:(NSString *)encryptionKey +{ + [self setKey:encryptionKey]; +} ++ (LKDBHelper *)sharedDBHelper +{ + return [LKDBHelper getUsingLKDBHelper]; +} +- (BOOL)createTableWithModelClass:(Class)modelClass +{ + return [self _createTableWithModelClass:modelClass tableName:[modelClass getTableName]]; +} ++ (LKDBHelper *)getUsingLKDBHelper +{ + return [[LKDBHelper alloc] init]; +} +@end + +@implementation LKDBWeakObject + +@end diff --git a/Pods/LKDBHelper/LKDBHelper/Helper/LKDBUtils.h b/Pods/LKDBHelper/LKDBHelper/Helper/LKDBUtils.h new file mode 100644 index 0000000..52334d3 --- /dev/null +++ b/Pods/LKDBHelper/LKDBHelper/Helper/LKDBUtils.h @@ -0,0 +1,117 @@ +// +// NSObject+LKUtils.h +// LKDBHelper +// +// Created by LJH on 13-4-15. +// Copyright (c) 2013年 ljh. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface LKDBUtils : NSObject + +// 创建文件路径所需要的文件夹 ++ (BOOL)createDirectoryWithFilePath:(NSString *)filePath; + +///返回根目录路径 "document" ++ (NSString *)getDocumentPath; +///返回 "document/dir/" 文件夹路径 ++ (NSString *)getDirectoryForDocuments:(NSString *)dir; +///返回 "document/filename" 路径 ++ (NSString *)getPathForDocuments:(NSString *)filename; +///返回 "document/dir/filename" 路径 ++ (NSString *)getPathForDocuments:(NSString *)filename inDir:(NSString *)dir; +///文件是否存在 ++ (BOOL)isFileExists:(NSString *)filepath; +///删除文件 ++ (BOOL)deleteWithFilepath:(NSString *)filepath; +///返回该文件目录下 所有文件名 ++ (nullable NSArray *)getFilenamesWithDir:(NSString *)dir; + +///检测字符串是否为空 ++ (BOOL)checkStringIsEmpty:(NSString *)string; ++ (nullable NSString *)getTrimStringWithString:(nullable NSString *)string; + +///把Date 转换成String ++ (NSString *)stringWithDate:(NSDate *)date; +///把String 转换成Date ++ (NSDate *)dateWithString:(NSString *)str; +///单例formatter ++ (NSNumberFormatter *)numberFormatter; + +@end + +#ifdef DEBUG +#ifdef NSLog +#define LKErrorLog(fmt, ...) NSLog(@"#LKDBHelper ERROR:\n" fmt, ##__VA_ARGS__); +#else +#define LKErrorLog(fmt, ...) NSLog(@"\n#LKDBHelper ERROR: %s [Line %d] \n" fmt, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); +#endif +#else +#define LKErrorLog(...) +#endif + +static NSString *const LKSQL_Type_Text = @"text"; +static NSString *const LKSQL_Type_Int = @"integer"; +static NSString *const LKSQL_Type_Double = @"double"; +static NSString *const LKSQL_Type_Blob = @"blob"; + +static NSString *const LKSQL_Attribute_NotNull = @"NOT NULL"; +static NSString *const LKSQL_Attribute_PrimaryKey = @"PRIMARY KEY"; +static NSString *const LKSQL_Attribute_Default = @"DEFAULT"; +static NSString *const LKSQL_Attribute_Unique = @"UNIQUE"; +static NSString *const LKSQL_Attribute_Check = @"CHECK"; +static NSString *const LKSQL_Attribute_ForeignKey = @"FOREIGN KEY"; + +static NSString *const LKSQL_Convert_FloatType = @"float_double_decimal"; +static NSString *const LKSQL_Convert_IntType = @"int_char_short_long"; +static NSString *const LKSQL_Convert_BlobType = @""; + +static NSString *const LKSQL_Mapping_Inherit = @"LKDBInherit"; +static NSString *const LKSQL_Mapping_Binding = @"LKDBBinding"; +static NSString *const LKSQL_Mapping_UserCalculate = @"LKDBUserCalculate"; + +static NSString *const LKDB_TypeKey = @"DB_Type"; + +static NSString *const LKDB_TypeKey_Model = @"DB_Type_Model"; +static NSString *const LKDB_TypeKey_JSON = @"DB_Type_JSON"; +static NSString *const LKDB_TypeKey_Combo = @"DB_Type_Combo"; +static NSString *const LKDB_TypeKey_Date = @"DB_Type_Date"; + +static NSString *const LKDB_ValueKey = @"DB_Value"; + +static NSString *const LKDB_TableNameKey = @"DB_TableName"; +static NSString *const LKDB_ClassKey = @"DB_Class"; +static NSString *const LKDB_RowIdKey = @"DB_RowId"; +static NSString *const LKDB_PValueKey = @"DB_PKeyValue"; + +///Object-c type converted to SQLite type 把Object-c 类型 转换为sqlite 类型 +extern NSString *LKSQLTypeFromObjcType(NSString *objcType); + +@interface LKDBQueryParams : NSObject + +///columns or array +@property (nullable, nonatomic, copy) NSString *columns; +@property (nullable, nonatomic, copy) NSArray *columnArray; + +@property (nullable, nonatomic, copy) NSString *tableName; + +///where or dic +@property (nullable, nonatomic, copy) NSString *where; +@property (nullable, nonatomic, copy) NSDictionary *whereDic; + +@property (nullable, nonatomic, copy) NSString *groupBy; +@property (nullable, nonatomic, copy) NSString *orderBy; + +@property (nonatomic, assign) NSInteger offset; +@property (nonatomic, assign) NSInteger count; + +@property (nullable, nonatomic, assign) Class toClass; + +@property (nullable, nonatomic, copy) void (^callback)(NSMutableArray *_Nullable results); + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/LKDBHelper/LKDBHelper/Helper/LKDBUtils.m b/Pods/LKDBHelper/LKDBHelper/Helper/LKDBUtils.m new file mode 100644 index 0000000..0c088bb --- /dev/null +++ b/Pods/LKDBHelper/LKDBHelper/Helper/LKDBUtils.m @@ -0,0 +1,241 @@ +// +// NSObject+LKUtils.m +// LKDBHelper +// +// Created by LJH on 13-4-15. +// Copyright (c) 2013年 ljh. All rights reserved. +// + +#import "LKDBUtils.h" + +@interface LKDateFormatter : NSDateFormatter +@property (nonatomic, strong) NSRecursiveLock *lock; +@end + +@implementation LKDateFormatter +- (id)init +{ + self = [super init]; + if (self) { + self.lock = [[NSRecursiveLock alloc] init]; + self.generatesCalendarDates = YES; + self.dateStyle = NSDateFormatterNoStyle; + self.timeStyle = NSDateFormatterNoStyle; + self.AMSymbol = nil; + self.PMSymbol = nil; + NSLocale *locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; + if (locale) { + [self setLocale:locale]; + } + } + return self; +} +//防止在IOS5下 多线程 格式化时间时 崩溃 +- (NSDate *)dateFromString:(NSString *)string +{ + [_lock lock]; + NSDate *date = [super dateFromString:string]; + [_lock unlock]; + return date; +} +- (NSString *)stringFromDate:(NSDate *)date +{ + [_lock lock]; + NSString *string = [super stringFromDate:date]; + [_lock unlock]; + return string; +} +@end + +@interface LKNumberFormatter : NSNumberFormatter + +@end + +@implementation LKNumberFormatter +- (NSString *)stringFromNumber:(NSNumber *)number +{ + NSString *string = [number stringValue]; + if (!string) { + string = [NSString stringWithFormat:@"%lf", [number doubleValue]]; + } + return string; +} +- (NSNumber *)numberFromString:(NSString *)string +{ + NSNumber *number = [super numberFromString:string]; + if (!number) { + number = @(string.doubleValue); + } + return number; +} +@end + +@implementation LKDBUtils + ++ (BOOL)createDirectoryWithFilePath:(NSString *)filePath +{ + NSString *dirPath = filePath.stringByDeletingLastPathComponent; + if (!dirPath) { + return NO; + } + + NSFileManager *fileManager = [NSFileManager defaultManager]; + + BOOL isDir = NO; + BOOL isCreated = [fileManager fileExistsAtPath:dirPath isDirectory:&isDir]; + +#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED + NSDictionary *attributes = @{NSFileProtectionKey: NSFileProtectionNone}; +#else + NSDictionary *attributes = nil; +#endif + + if (!isCreated || !isDir) { + NSError *error = nil; + BOOL success = [fileManager createDirectoryAtPath:dirPath + withIntermediateDirectories:YES + attributes:attributes + error:&error]; + if (!success) { + LKErrorLog(@"create dir error: %@", error.debugDescription); + /// 下个主线程继续尝试次 + dispatch_async(dispatch_get_main_queue(), ^{ + [fileManager createDirectoryAtPath:dirPath + withIntermediateDirectories:YES + attributes:attributes + error:nil]; + }); + } + return success; + } else { + /** + * @brief Disk I/O error when device is locked + * https://github.com/ccgus/fmdb/issues/262 + */ +#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED + [fileManager setAttributes:attributes + ofItemAtPath:dirPath + error:nil]; +#endif + return YES; + } +} + ++ (NSString *)getDocumentPath +{ +#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsDirectory = [paths objectAtIndex:0]; + return documentsDirectory; +#else + NSString *homePath = [[NSBundle mainBundle] resourcePath]; + return homePath; +#endif +} ++ (NSString *)getDirectoryForDocuments:(NSString *)dir +{ + NSString *dirPath = [[self getDocumentPath] stringByAppendingPathComponent:dir]; + BOOL isDir = NO; + BOOL isCreated = [[NSFileManager defaultManager] fileExistsAtPath:dirPath isDirectory:&isDir]; + if (isCreated == NO || isDir == NO) { + NSError *error = nil; + BOOL success = [[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error]; + if (success == NO) + NSLog(@"create dir error: %@", error.debugDescription); + } + return dirPath; +} ++ (NSString *)getPathForDocuments:(NSString *)filename +{ + return [[self getDocumentPath] stringByAppendingPathComponent:filename]; +} ++ (NSString *)getPathForDocuments:(NSString *)filename inDir:(NSString *)dir +{ + return [[self getDirectoryForDocuments:dir] stringByAppendingPathComponent:filename]; +} ++ (BOOL)isFileExists:(NSString *)filepath +{ + return [[NSFileManager defaultManager] fileExistsAtPath:filepath]; +} ++ (BOOL)deleteWithFilepath:(NSString *)filepath +{ + return [[NSFileManager defaultManager] removeItemAtPath:filepath error:nil]; +} ++ (NSArray *)getFilenamesWithDir:(NSString *)dir +{ + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSArray *fileList = [fileManager contentsOfDirectoryAtPath:dir error:nil]; + return fileList; +} ++ (BOOL)checkStringIsEmpty:(NSString *)string +{ + if (string == nil) { + return YES; + } + if ([string isKindOfClass:[NSString class]] == NO) { + return YES; + } + if (string.length == 0) { + return YES; + } + return [[self getTrimStringWithString:string] isEqualToString:@""]; +} ++ (NSString *)getTrimStringWithString:(NSString *)string +{ + return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; +} + ++ (NSDateFormatter *)getDBDateFormat +{ + static NSDateFormatter *format; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + format = [[LKDateFormatter alloc] init]; + format.dateFormat = @"yyyy-MM-dd HH:mm:ss"; + }); + return format; +} ++ (NSString *)stringWithDate:(NSDate *)date +{ + NSDateFormatter *formatter = [self getDBDateFormat]; + NSString *datestr = [formatter stringFromDate:date]; + if (datestr.length > 19) { + datestr = [datestr substringToIndex:19]; + } + return datestr; +} ++ (NSDate *)dateWithString:(NSString *)str +{ + NSDateFormatter *formatter = [self getDBDateFormat]; + NSDate *date = [formatter dateFromString:str]; + return date; +} ++ (NSNumberFormatter *)numberFormatter +{ + static NSNumberFormatter *numberFormatter = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + numberFormatter = [[LKNumberFormatter alloc] init]; + }); + return numberFormatter; +} +@end + +inline NSString *LKSQLTypeFromObjcType(NSString *objcType) +{ + if ([LKSQL_Convert_IntType rangeOfString:objcType].length > 0) { + return LKSQL_Type_Int; + } + if ([LKSQL_Convert_FloatType rangeOfString:objcType].length > 0) { + return LKSQL_Type_Double; + } + if ([LKSQL_Convert_BlobType rangeOfString:objcType].length > 0) { + return LKSQL_Type_Blob; + } + + return LKSQL_Type_Text; +} + +@implementation LKDBQueryParams + +@end diff --git a/Pods/LKDBHelper/LKDBHelper/Helper/NSObject+LKDBHelper.h b/Pods/LKDBHelper/LKDBHelper/Helper/NSObject+LKDBHelper.h new file mode 100644 index 0000000..7e0f6b5 --- /dev/null +++ b/Pods/LKDBHelper/LKDBHelper/Helper/NSObject+LKDBHelper.h @@ -0,0 +1,110 @@ +// +// NSObject+LKDBHelper.h +// LKDBHelper +// +// Created by LJH on 13-6-8. +// Copyright (c) 2013年 ljh. All rights reserved. +// + +#import "LKDBHelper.h" +#import + +NS_ASSUME_NONNULL_BEGIN + +@class LKDBHelper; + +@interface NSObject (LKDBHelper_Delegate) + ++ (void)dbDidCreateTable:(LKDBHelper *)helper tableName:(NSString *)tableName; ++ (void)dbDidAlterTable:(LKDBHelper *)helper tableName:(NSString *)tableName addColumns:(NSArray *)columns; + ++ (BOOL)dbWillInsert:(NSObject *)entity; ++ (void)dbDidInserted:(NSObject *)entity result:(BOOL)result; + ++ (BOOL)dbWillUpdate:(NSObject *)entity; ++ (void)dbDidUpdated:(NSObject *)entity result:(BOOL)result; + ++ (BOOL)dbWillDelete:(NSObject *)entity; ++ (void)dbDidDeleted:(NSObject *)entity result:(BOOL)result; + +///data read finish ++ (void)dbDidSeleted:(NSObject *)entity; + +@end + +//only simplify synchronous function +@interface NSObject (LKDBHelper_Execute) + +/** + * 返回行数 + * + * @param where type can NSDictionary or NSString + * + * @return row count + */ ++ (NSInteger)rowCountWithWhere:(nullable id)where, ...; ++ (NSInteger)rowCountWithWhereFormat:(nullable id)where, ...; + +/** + * 搜索 + * + * @param columns type can NSArray or NSString(Search for a specific column. Search only one, only to return the contents of the column collection) + + * @param where where type can NSDictionary or NSString + * @param orderBy + * @param offset + * @param count + * + * @return model collection or contents of the columns collection + */ ++ (nullable NSMutableArray *)searchColumn:(nullable id)columns + where:(nullable id)where + orderBy:(nullable NSString *)orderBy + offset:(NSInteger)offset + count:(NSInteger)count; + ++ (nullable NSMutableArray *)searchWithWhere:(nullable id)where + orderBy:(nullable NSString *)orderBy + offset:(NSInteger)offset + count:(NSInteger)count; + ++ (nullable NSMutableArray *)searchWithWhere:(nullable id)where; + ++ (nullable NSMutableArray *)searchWithSQL:(NSString *)sql; + ++ (nullable id)searchSingleWithWhere:(nullable id)where + orderBy:(nullable NSString *)orderBy; + ++ (BOOL)insertToDB:(NSObject *)model; ++ (BOOL)insertWhenNotExists:(NSObject *)model; + ++ (BOOL)updateToDB:(NSObject *)model + where:(nullable id)where, ...; ++ (BOOL)updateToDBWithSet:(NSString *)sets + where:(nullable id)where, ...; + ++ (BOOL)deleteToDB:(NSObject *)model; ++ (BOOL)deleteWithWhere:(nullable id)where, ...; + ++ (BOOL)isExistsWithModel:(NSObject *)model; + +- (BOOL)updateToDB; +- (BOOL)saveToDB; +- (BOOL)deleteToDB; +- (BOOL)isExistsFromDB; + +///异步插入数据 async insert array , completed 也是在子线程直接回调的 ++ (void)insertArrayByAsyncToDB:(NSArray *)models; ++ (void)insertArrayByAsyncToDB:(NSArray *)models completed:(void (^_Nullable)(BOOL allInserted))completedBlock; + +///begin translate for insert models 开始事务插入数组 ++ (void)insertToDBWithArray:(NSArray *)models + filter:(void (^_Nullable)(id model, BOOL inserted, BOOL *_Nullable rollback))filter; + ++ (void)insertToDBWithArray:(NSArray *)models + filter:(void (^_Nullable)(id model, BOOL inserted, BOOL *_Nullable rollback))filter + completed:(void (^_Nullable)(BOOL allInserted))completedBlock; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/LKDBHelper/LKDBHelper/Helper/NSObject+LKDBHelper.m b/Pods/LKDBHelper/LKDBHelper/Helper/NSObject+LKDBHelper.m new file mode 100644 index 0000000..dc05b11 --- /dev/null +++ b/Pods/LKDBHelper/LKDBHelper/Helper/NSObject+LKDBHelper.m @@ -0,0 +1,234 @@ +// +// NSObject+LKDBHelper.m +// LKDBHelper +// +// Created by LJH on 13-6-8. +// Copyright (c) 2013年 ljh. All rights reserved. +// + +#import "NSObject+LKDBHelper.h" + +@implementation NSObject (LKDBHelper_Delegate) + ++ (void)dbDidCreateTable:(LKDBHelper *)helper tableName:(NSString *)tableName {} ++ (void)dbDidAlterTable:(LKDBHelper *)helper tableName:(NSString *)tableName addColumns:(NSArray *)columns {} + ++ (void)dbDidInserted:(NSObject *)entity result:(BOOL)result {} ++ (void)dbDidDeleted:(NSObject *)entity result:(BOOL)result {} ++ (void)dbDidUpdated:(NSObject *)entity result:(BOOL)result {} ++ (void)dbDidSeleted:(NSObject *)entity {} + ++ (BOOL)dbWillDelete:(NSObject *)entity +{ + return YES; +} + ++ (BOOL)dbWillInsert:(NSObject *)entity +{ + return YES; +} + ++ (BOOL)dbWillUpdate:(NSObject *)entity +{ + return YES; +} + +@end + +@implementation NSObject (LKDBHelper) + +#pragma mark - simplify synchronous function ++ (BOOL)checkModelClass:(NSObject *)model +{ + if ([model isMemberOfClass:self]) + return YES; + + NSLog(@"%@ can not use %@", NSStringFromClass(self), NSStringFromClass(model.class)); + return NO; +} + ++ (NSInteger)rowCountWithWhereFormat:(id)where, ... +{ + if ([where isKindOfClass:[NSString class]]) { + va_list list; + va_start(list, where); + where = [[NSString alloc] initWithFormat:where arguments:list]; + va_end(list); + } + return [[self getUsingLKDBHelper] rowCount:self where:where]; +} + ++ (NSInteger)rowCountWithWhere:(id)where, ... +{ + if ([where isKindOfClass:[NSString class]]) { + va_list list; + va_start(list, where); + where = [[NSString alloc] initWithFormat:where arguments:list]; + va_end(list); + } + return [[self getUsingLKDBHelper] rowCount:self where:where]; +} + ++ (NSMutableArray *)searchColumn:(id)columns where:(id)where orderBy:(NSString *)orderBy offset:(NSInteger)offset count:(NSInteger)count +{ + return [[self getUsingLKDBHelper] search:self column:columns where:where orderBy:orderBy offset:offset count:count]; +} + ++ (NSMutableArray *)searchWithWhere:(id)where orderBy:(NSString *)orderBy offset:(NSInteger)offset count:(NSInteger)count +{ + return [[self getUsingLKDBHelper] search:self where:where orderBy:orderBy offset:offset count:count]; +} + ++ (NSMutableArray *)searchWithWhere:(id)where +{ + return [[self getUsingLKDBHelper] search:self where:where orderBy:nil offset:0 count:0]; +} + ++ (NSMutableArray *)searchWithSQL:(NSString *)sql +{ + return [[self getUsingLKDBHelper] searchWithSQL:sql toClass:self]; +} + ++ (id)searchSingleWithWhere:(id)where orderBy:(NSString *)orderBy +{ + return [[self getUsingLKDBHelper] searchSingle:self where:where orderBy:orderBy]; +} + ++ (BOOL)insertToDB:(NSObject *)model +{ + + if ([self checkModelClass:model]) { + return [[self getUsingLKDBHelper] insertToDB:model]; + } + return NO; +} + ++ (BOOL)insertWhenNotExists:(NSObject *)model +{ + if ([self checkModelClass:model]) { + return [[self getUsingLKDBHelper] insertWhenNotExists:model]; + } + return NO; +} + ++ (BOOL)updateToDB:(NSObject *)model where:(id)where, ... +{ + if ([self checkModelClass:model]) { + if ([where isKindOfClass:[NSString class]]) { + va_list list; + va_start(list, where); + where = [[NSString alloc] initWithFormat:where arguments:list]; + va_end(list); + } + return [[self getUsingLKDBHelper] updateToDB:model where:where]; + } + return NO; +} + ++ (BOOL)updateToDBWithSet:(NSString *)sets where:(id)where, ... +{ + if ([where isKindOfClass:[NSString class]]) { + va_list list; + va_start(list, where); + where = [[NSString alloc] initWithFormat:where arguments:list]; + va_end(list); + } + return [[self getUsingLKDBHelper] updateToDB:self set:sets where:where]; +} + ++ (BOOL)deleteToDB:(NSObject *)model +{ + if ([self checkModelClass:model]) { + return [[self getUsingLKDBHelper] deleteToDB:model]; + } + return NO; +} + ++ (BOOL)deleteWithWhere:(id)where, ... +{ + if ([where isKindOfClass:[NSString class]]) { + va_list list; + va_start(list, where); + where = [[NSString alloc] initWithFormat:where arguments:list]; + va_end(list); + } + return [[self getUsingLKDBHelper] deleteWithClass:self where:where]; +} + ++ (BOOL)isExistsWithModel:(NSObject *)model +{ + if ([self checkModelClass:model]) { + return [[self getUsingLKDBHelper] isExistsModel:model]; + } + return NO; +} + +- (BOOL)updateToDB +{ + if (self.rowid > 0) { + return [self.class updateToDB:self where:nil]; + } else { + return [self saveToDB]; + } +} + +- (BOOL)saveToDB +{ + return [self.class insertToDB:self]; +} + +- (BOOL)deleteToDB +{ + return [self.class deleteToDB:self]; +} + +- (BOOL)isExistsFromDB +{ + return [self.class isExistsWithModel:self]; +} + ++ (void)insertArrayByAsyncToDB:(NSArray *)models +{ + [self insertArrayByAsyncToDB:models completed:nil]; +} + ++ (void)insertArrayByAsyncToDB:(NSArray *)models completed:(void (^_Nullable)(BOOL))completedBlock +{ + if (models.count > 0) { + dispatch_async(dispatch_get_global_queue(0, 0), ^{ + [self insertToDBWithArray:models filter:nil completed:completedBlock]; + }); + } +} + ++ (void)insertToDBWithArray:(NSArray *)models filter:(void (^)(id model, BOOL inserted, BOOL *rollback))filter +{ + [self insertToDBWithArray:models filter:filter completed:nil]; +} + ++ (void)insertToDBWithArray:(NSArray *)models filter:(void (^)(id model, BOOL inserted, BOOL *rollback))filter completed:(void (^)(BOOL))completedBlock +{ + __block BOOL allInserted = YES; + [[self getUsingLKDBHelper] executeForTransaction:^BOOL(LKDBHelper *helper) { + BOOL isRollback = NO; + for (int i = 0; i < models.count; i++) { + id obj = [models objectAtIndex:i]; + BOOL inserted = [helper insertToDB:obj]; + allInserted &= inserted; + if (filter) { + filter(obj, inserted, &isRollback); + } + if (isRollback) { + allInserted = NO; + break; + } + } + return (isRollback == NO); + }]; + + if (completedBlock) { + completedBlock(allInserted); + } +} + +@end diff --git a/Pods/LKDBHelper/LKDBHelper/Helper/NSObject+LKModel.h b/Pods/LKDBHelper/LKDBHelper/Helper/NSObject+LKModel.h new file mode 100644 index 0000000..4d9df9a --- /dev/null +++ b/Pods/LKDBHelper/LKDBHelper/Helper/NSObject+LKModel.h @@ -0,0 +1,146 @@ +// +// NSObject+LKModel.h +// LKDBHelper +// +// Created by LJH on 13-4-15. +// Copyright (c) 2013年 ljh. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class LKDBProperty; +@class LKModelInfos; +@class LKDBHelper; + +#pragma mark - 表结构 +@interface NSObject (LKTabelStructure) + +/** + * overwrite in your models(option) + * + * @return # table name # + */ ++ (NSString *)getTableName; + +/** + * if you set it will use it as a table name + */ +@property (nullable, nonatomic, copy) NSString *db_tableName; + +/** + * the model is inserting .. + */ +@property (nonatomic, readonly) BOOL db_inserting; + +/** + * sqlite comes with rowid + */ +@property (nonatomic, assign) NSInteger rowid; + +/** + * overwrite in your models, if your table has primary key + + * 主键列名 如果rowid<0 则跟据此名称update 和delete + + * @return # column name # + */ ++ (nullable NSString *)getPrimaryKey; + +/** + * multi primary key + * 联合主键 + * @return + */ ++ (nullable NSArray *)getPrimaryKeyUnionArray; + +/** + * overwrite in your models set column attribute + * + * @param property infos + */ ++ (void)columnAttributeWithProperty:(LKDBProperty *)property; + +/** + * @brief get saved pictures and data file path,can overwirte + + 获取保存的 图片和数据的文件路径 + */ ++ (NSString *)getDBImagePathWithName:(NSString *)filename; ++ (NSString *)getDBDataPathWithName:(NSString *)filename; + +@end + +#pragma mark - 表数据操作 +@interface NSObject (LKTableData) + +/*** + * @brief overwrite in your models,return insert sqlite table data + * + * + * @return property the data after conversion + */ +- (nullable id)userGetValueForModel:(LKDBProperty *)property; + +/*** + * @brief overwrite in your models,return insert sqlite table data + * + * @param property will set property + * @param value sqlite value (NSString(NSData UTF8 Coding) or NSData) + */ +- (void)userSetValueForModel:(LKDBProperty *)property value:(nullable id)value; + +///overwrite ++ (NSDateFormatter *)getModelDateFormatter; + +//lkdbhelper use +- (nullable id)modelGetValue:(LKDBProperty *)property; +- (void)modelSetValue:(LKDBProperty *)property value:(nullable NSString *)value; + +- (nullable id)singlePrimaryKeyValue; +- (BOOL)singlePrimaryKeyValueIsEmpty; +- (nullable LKDBProperty *)singlePrimaryKeyProperty; ++ (nullable NSString *)db_rowidAliasName; + +@end + +@interface NSObject (LKModel) + +/** + * return model use LKDBHelper , default return global LKDBHelper; + * + * @return LKDBHelper + */ ++ (LKDBHelper *)getUsingLKDBHelper; + +/** + * class attributes + * + * @return LKModelInfos + */ ++ (LKModelInfos *)getModelInfos; + +/** + * @brief Containing the super class attributes 设置是否包含 父类 的属性 + */ ++ (BOOL)isContainParent; + +/** + * 当前表中的列是否包含自身的属性。 + * + * @return BOOL + */ ++ (BOOL)isContainSelf; + +/** + * @brief log all property 打印所有的属性名称和数据 + */ +- (NSString *)printAllPropertys; +- (NSString *)printAllPropertysIsContainParent:(BOOL)containParent; + +- (NSMutableString *)getAllPropertysString; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/LKDBHelper/LKDBHelper/Helper/NSObject+LKModel.m b/Pods/LKDBHelper/LKDBHelper/Helper/NSObject+LKModel.m new file mode 100644 index 0000000..5aabaa5 --- /dev/null +++ b/Pods/LKDBHelper/LKDBHelper/Helper/NSObject+LKModel.m @@ -0,0 +1,922 @@ +// +// NSObject+LKModel.m +// LKDBHelper +// +// Created by LJH on 13-4-15. +// Copyright (c) 2013年 ljh. All rights reserved. +// + +#import "LKDBHelper.h" +#import "NSObject+LKModel.h" +#import + +#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED +#import +#define LKDBImage UIImage +#define LKDBColor UIColor +#else +#import +#define LKDBImage NSImage +#define LKDBColor NSColor +#endif + +static char LKModelBase_Key_RowID; +static char LKModelBase_Key_TableName; +static char LKModelBase_Key_Inserting; + +@interface LKDBHelper (LKDBHelper_LKModel) ++ (BOOL)nullIsEmpty; +@end + +@implementation NSObject (LKModel) + ++ (LKDBHelper *)getUsingLKDBHelper +{ + ///ios8 能获取系统类的属性了 所以没有办法判断属性数量来区分自定义类和系统类 + ///可能系统类的存取会不正确 + static LKDBHelper *helper; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + helper = [[LKDBHelper alloc] init]; + }); + return helper; +} +#pragma mark Tabel Structure Function 表结构 ++ (NSString *)getTableName +{ + return NSStringFromClass(self); +} + ++ (NSString *)getPrimaryKey +{ + return @"rowid"; +} + ++ (NSArray *)getPrimaryKeyUnionArray +{ + return nil; +} + ++ (void)columnAttributeWithProperty:(LKDBProperty *)property +{ + //overwrite +} +#pragma 属性 +- (void)setRowid:(NSInteger)rowid +{ + objc_setAssociatedObject(self, &LKModelBase_Key_RowID, [NSNumber numberWithInteger:rowid], OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} +- (NSInteger)rowid +{ + return [objc_getAssociatedObject(self, &LKModelBase_Key_RowID) integerValue]; +} + +- (void)setDb_tableName:(NSString *)db_tableName +{ + objc_setAssociatedObject(self, &LKModelBase_Key_TableName, db_tableName, OBJC_ASSOCIATION_COPY_NONATOMIC); +} +- (NSString *)db_tableName +{ + NSString *tableName = objc_getAssociatedObject(self, &LKModelBase_Key_TableName); + if (tableName.length == 0) { + tableName = [self.class getTableName]; + } + return tableName; +} +- (BOOL)db_inserting +{ + return [objc_getAssociatedObject(self, &LKModelBase_Key_Inserting) boolValue]; +} +- (void)setDb_inserting:(BOOL)db_inserting +{ + NSNumber *number = nil; + if (db_inserting) { + number = [NSNumber numberWithBool:YES]; + } + objc_setAssociatedObject(self, &LKModelBase_Key_Inserting, number, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} +#pragma 无关紧要的 ++ (NSString *)getDBImagePathWithName:(NSString *)filename +{ + NSString *dir = [NSString stringWithFormat:@"dbimg/%@", NSStringFromClass(self)]; + return [LKDBUtils getPathForDocuments:filename inDir:dir]; +} ++ (NSString *)getDBDataPathWithName:(NSString *)filename +{ + NSString *dir = [NSString stringWithFormat:@"dbdata/%@", NSStringFromClass(self)]; + return [LKDBUtils getPathForDocuments:filename inDir:dir]; +} ++ (NSDictionary *)getTableMapping +{ + return nil; +} +#pragma mark - Table Data Function 表数据 ++ (NSDateFormatter *)getModelDateFormatter +{ + return nil; +} + +///get +- (id)modelGetValue:(LKDBProperty *)property +{ + id value = [self valueForKey:property.propertyName]; + id returnValue = value; + if (value == nil) { + return nil; + } else if ([value isKindOfClass:[NSString class]]) { + returnValue = [value copy]; + } else if ([value isKindOfClass:[NSNumber class]]) { + returnValue = [[LKDBUtils numberFormatter] stringFromNumber:value]; + } else if ([value isKindOfClass:[NSDate class]]) { + NSDateFormatter *formatter = [self.class getModelDateFormatter]; + if (formatter) { + returnValue = [formatter stringFromDate:value]; + } else { + returnValue = [LKDBUtils stringWithDate:value]; + } + returnValue = [returnValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; + } else if ([value isKindOfClass:[LKDBColor class]]) { + LKDBColor *color = value; + CGFloat r, g, b, a; + [color getRed:&r green:&g blue:&b alpha:&a]; + returnValue = [NSString stringWithFormat:@"%.3f,%.3f,%.3f,%.3f", r, g, b, a]; + } else if ([value isKindOfClass:[NSValue class]]) { + NSString *columnType = property.propertyType; +#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED + if ([columnType isEqualToString:@"CGRect"]) { + returnValue = NSStringFromCGRect([value CGRectValue]); + } else if ([columnType isEqualToString:@"CGPoint"]) { + returnValue = NSStringFromCGPoint([value CGPointValue]); + } else if ([columnType isEqualToString:@"CGSize"]) { + returnValue = NSStringFromCGSize([value CGSizeValue]); + } else if ([columnType isEqualToString:@"_NSRange"]) { + returnValue = NSStringFromRange([value rangeValue]); + } +#else + if ([columnType hasSuffix:@"Rect"]) { + returnValue = NSStringFromRect([value rectValue]); + } else if ([columnType hasSuffix:@"Point"]) { + returnValue = NSStringFromPoint([value pointValue]); + } else if ([columnType hasSuffix:@"Size"]) { + returnValue = NSStringFromSize([value sizeValue]); + } else if ([columnType hasSuffix:@"Range"]) { + returnValue = NSStringFromRange([value rangeValue]); + } +#endif + } else if ([value isKindOfClass:[LKDBImage class]]) { + long random = arc4random(); + long date = [[NSDate date] timeIntervalSince1970]; + NSString *filename = [NSString stringWithFormat:@"img%ld%ld", date & 0xFFFFF, random & 0xFFF]; + +#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED + NSData *datas = UIImageJPEGRepresentation(value, 1); +#else + [value lockFocus]; + NSBitmapImageRep *srcImageRep = [NSBitmapImageRep imageRepWithData:[value TIFFRepresentation]]; + NSData *datas = [srcImageRep representationUsingType:NSJPEGFileType properties:@{}]; + [value unlockFocus]; +#endif + [datas writeToFile:[self.class getDBImagePathWithName:filename] + atomically:YES]; + + returnValue = filename; + } else if ([value isKindOfClass:[NSData class]]) { + long random = arc4random(); + long date = [[NSDate date] timeIntervalSince1970]; + NSString *filename = [NSString stringWithFormat:@"data%ld%ld", date & 0xFFFFF, random & 0xFFF]; + + [value writeToFile:[self.class getDBDataPathWithName:filename] atomically:YES]; + + returnValue = filename; + } else if ([value isKindOfClass:[NSURL class]]) { + returnValue = [value absoluteString]; + } else { + if ([value isKindOfClass:[NSArray class]]) { + returnValue = [self db_jsonObjectFromArray:value]; + } else if ([value isKindOfClass:[NSDictionary class]]) { + returnValue = [self db_jsonObjectFromDictionary:value]; + } else { + returnValue = [self db_jsonObjectFromModel:value]; + } + returnValue = [self db_jsonStringFromObject:returnValue]; + } + + return returnValue; +} + +///set +- (void)modelSetValue:(LKDBProperty *)property value:(NSString *)value +{ + ///参试获取属性的Class + Class columnClass = NSClassFromString(property.propertyType); + + id modelValue = nil; + + if (columnClass == nil) { + ///当找不到 class 时,就是 基础类型 int,float CGRect 之类的 + NSString *columnType = property.propertyType; + if ([LKSQL_Convert_FloatType rangeOfString:columnType].location != NSNotFound) { + if (value) { + modelValue = [[LKDBUtils numberFormatter] numberFromString:value]; + } + } else if ([LKSQL_Convert_IntType rangeOfString:columnType].location != NSNotFound) { + if (value) { + modelValue = [[LKDBUtils numberFormatter] numberFromString:value]; + } + } +#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED + else if ([columnType isEqualToString:@"CGRect"]) { + if (value) { + CGRect rect = CGRectFromString(value); + modelValue = [NSValue valueWithCGRect:rect]; + } else { + modelValue = [NSValue valueWithCGRect:CGRectZero]; + } + } else if ([columnType isEqualToString:@"CGPoint"]) { + if (value) { + CGPoint point = CGPointFromString(value); + modelValue = [NSValue valueWithCGPoint:point]; + } else { + modelValue = [NSValue valueWithCGPoint:CGPointZero]; + } + } else if ([columnType isEqualToString:@"CGSize"]) { + if (value) { + CGSize size = CGSizeFromString(value); + modelValue = [NSValue valueWithCGSize:size]; + } else { + modelValue = [NSValue valueWithCGSize:CGSizeZero]; + } + } else if ([columnType isEqualToString:@"_NSRange"]) { + if (value) { + NSRange range = NSRangeFromString(value); + modelValue = [NSValue valueWithRange:range]; + } else { + modelValue = [NSValue valueWithRange:NSMakeRange(0, 0)]; + } + } +#else + else if ([columnType hasSuffix:@"Rect"]) { + if (value) { + NSRect rect = NSRectFromString(value); + modelValue = [NSValue valueWithRect:rect]; + } else { + modelValue = [NSValue valueWithRect:NSZeroRect]; + } + } else if ([columnType hasSuffix:@"Point"]) { + if (value) { + NSPoint point = NSPointFromString(value); + modelValue = [NSValue valueWithPoint:point]; + } else { + modelValue = [NSValue valueWithPoint:NSZeroPoint]; + } + } else if ([columnType hasSuffix:@"Size"]) { + if (value) { + NSSize size = NSSizeFromString(value); + modelValue = [NSValue valueWithSize:size]; + } else { + modelValue = [NSValue valueWithSize:NSZeroSize]; + } + } else if ([columnType hasSuffix:@"Range"]) { + if (value) { + NSRange range = NSRangeFromString(value); + modelValue = [NSValue valueWithRange:range]; + } else { + modelValue = [NSValue valueWithRange:NSMakeRange(0, 0)]; + } + } +#endif + ///如果都没有值 默认给个0 + if (modelValue == nil) { + modelValue = @0; + } + } else if (!value || ![value isKindOfClass:[NSString class]]) { + //不继续遍历 + } else if ([columnClass isSubclassOfClass:[NSString class]]) { + if (![LKDBHelper nullIsEmpty] || value.length > 0) { + modelValue = [columnClass stringWithString:value]; + } + } else if ([columnClass isSubclassOfClass:[NSNumber class]]) { + modelValue = [[LKDBUtils numberFormatter] numberFromString:value]; + } else if ([columnClass isSubclassOfClass:[NSDate class]]) { + NSString *datestr = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; + NSDateFormatter *formatter = [self.class getModelDateFormatter]; + if (formatter) { + modelValue = [formatter dateFromString:datestr]; + } else { + modelValue = [LKDBUtils dateWithString:datestr]; + } + } else if ([columnClass isSubclassOfClass:[LKDBColor class]]) { + NSString *colorString = value; + NSArray *array = [colorString componentsSeparatedByString:@","]; + float r, g, b, a; + r = [[array objectAtIndex:0] floatValue]; + g = [[array objectAtIndex:1] floatValue]; + b = [[array objectAtIndex:2] floatValue]; + a = [[array objectAtIndex:3] floatValue]; + + modelValue = [LKDBColor colorWithRed:r green:g blue:b alpha:a]; + } else if ([columnClass isSubclassOfClass:[LKDBImage class]]) { + NSString *filename = value; + NSString *filepath = [self.class getDBImagePathWithName:filename]; + if ([LKDBUtils isFileExists:filepath]) { + modelValue = [[LKDBImage alloc] initWithContentsOfFile:filepath]; + } + } else if ([columnClass isSubclassOfClass:[NSData class]]) { + NSString *filename = value; + NSString *filepath = [self.class getDBDataPathWithName:filename]; + if ([LKDBUtils isFileExists:filepath]) { + modelValue = [NSData dataWithContentsOfFile:filepath]; + } + } else if ([columnClass isSubclassOfClass:[NSURL class]]) { + NSString *urlString = value; + modelValue = [NSURL URLWithString:urlString]; + } else { + modelValue = [self db_modelWithJsonValue:value]; + BOOL isValid = NO; + if ([modelValue isKindOfClass:[NSArray class]] && [columnClass isSubclassOfClass:[NSArray class]]) { + isValid = YES; + modelValue = [columnClass arrayWithArray:modelValue]; + } else if ([modelValue isKindOfClass:[NSDictionary class]] && [columnClass isSubclassOfClass:[NSDictionary class]]) { + isValid = YES; + modelValue = [columnClass dictionaryWithDictionary:modelValue]; + } else if ([modelValue isKindOfClass:columnClass]) { + isValid = YES; + } + ///如果类型不对 则设置为空 + if (!isValid) { + modelValue = nil; + } + } + + [self setValue:modelValue forKey:property.propertyName]; +} +#pragma mark - 对 model NSArray NSDictionary 进行支持 +- (id)db_jsonObjectFromDictionary:(NSDictionary *)dic +{ + if ([NSJSONSerialization isValidJSONObject:dic]) { + NSDictionary *bomb = @{LKDB_TypeKey: LKDB_TypeKey_JSON, LKDB_ValueKey: dic}; + return bomb; + } else { + NSMutableDictionary *toDic = [NSMutableDictionary dictionary]; + [dic enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL *_Nonnull stop) { + id jsonObject = [self db_jsonObjectWithObject:obj]; + if (jsonObject) { + toDic[key] = jsonObject; + } + }]; + if (toDic.count) { + NSDictionary *bomb = @{LKDB_TypeKey: LKDB_TypeKey_Combo, LKDB_ValueKey: toDic}; + return bomb; + } + } + return nil; +} +- (id)db_jsonObjectFromArray:(NSArray *)array +{ + if ([NSJSONSerialization isValidJSONObject:array]) { + NSDictionary *bomb = @{LKDB_TypeKey: LKDB_TypeKey_JSON, LKDB_ValueKey: array}; + return bomb; + } else { + NSMutableArray *toArray = [NSMutableArray array]; + NSInteger count = array.count; + for (NSInteger i = 0; i < count; i++) { + id obj = [array objectAtIndex:i]; + id jsonObject = [self db_jsonObjectWithObject:obj]; + if (jsonObject) { + [toArray addObject:jsonObject]; + } + } + + if (toArray.count) { + NSDictionary *bomb = @{LKDB_TypeKey: LKDB_TypeKey_Combo, LKDB_ValueKey: toArray}; + return bomb; + } + } + return nil; +} +///目前只支持 model、NSString、NSNumber 简单类型 +- (id)db_jsonObjectWithObject:(id)obj +{ + id jsonObject = nil; + if ([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[NSNumber class]]) { + jsonObject = obj; + } else if ([obj isKindOfClass:[NSDate class]]) { + NSString *dateString = nil; + NSDateFormatter *formatter = [self.class getModelDateFormatter]; + if (formatter) { + dateString = [formatter stringFromDate:obj]; + } else { + dateString = [LKDBUtils stringWithDate:obj]; + } + dateString = [dateString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; + if (dateString.length > 0) { + jsonObject = @{LKDB_TypeKey: LKDB_TypeKey_Date, LKDB_ValueKey: dateString}; + } + } else if ([obj isKindOfClass:[NSArray class]]) { + jsonObject = [self db_jsonObjectFromArray:obj]; + } else if ([obj isKindOfClass:[NSDictionary class]]) { + jsonObject = [self db_jsonObjectFromDictionary:obj]; + } else { + jsonObject = [self db_jsonObjectFromModel:obj]; + } + + if (jsonObject == nil) { + jsonObject = [obj description]; + } + return jsonObject; +} + +- (id)db_jsonObjectFromModel:(NSObject *)model +{ + Class clazz = model.class; + NSDictionary *jsonObject = nil; + if (model.rowid > 0) { + [model updateToDB]; + jsonObject = [self db_readInfoWithModel:model class:clazz]; + } else { + if (model.db_inserting == NO && [clazz getModelInfos].count > 0) { + BOOL success = [model saveToDB]; + if (success) { + jsonObject = [self db_readInfoWithModel:model class:clazz]; + } + } else { + NSAssert(NO, @"目前LKDB 还不支持 循环引用。 比如 A 持有 B, B 持有 A,这种的存储"); + } + } + return jsonObject; +} +- (NSDictionary *)db_readInfoWithModel:(NSObject *)model class:(Class)clazz +{ + NSMutableDictionary *jsonObject = [NSMutableDictionary dictionary]; + if (!model.db_tableName) { + NSAssert(NO, @"none table name"); + return nil; + } + if (!NSStringFromClass(clazz)) { + NSAssert(NO, @"none class"); + return nil; + } + + jsonObject[LKDB_TypeKey] = LKDB_TypeKey_Model; + jsonObject[LKDB_TableNameKey] = model.db_tableName; + jsonObject[LKDB_ClassKey] = NSStringFromClass(clazz); + jsonObject[LKDB_RowIdKey] = @(model.rowid); + + NSDictionary *dic = [model db_getPrimaryKeysValues]; + if (dic.count > 0 && [NSJSONSerialization isValidJSONObject:dic]) { + jsonObject[LKDB_PValueKey] = dic; + } + return jsonObject; +} + + - (NSString *)db_jsonStringFromObject : (NSObject *)jsonObject +{ + if (jsonObject && [NSJSONSerialization isValidJSONObject:jsonObject]) { + NSData *data = [NSJSONSerialization dataWithJSONObject:jsonObject options:0 error:nil]; + if (data.length > 0) { + NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + return jsonString; + } + } + return nil; +} +- (id)db_modelWithJsonValue:(id)value +{ + NSData *jsonData = nil; + if ([value isKindOfClass:[NSString class]]) { + jsonData = [value dataUsingEncoding:NSUTF8StringEncoding]; + } else if ([value isKindOfClass:[NSData class]]) { + jsonData = value; + } + + if (jsonData.length > 0) { + NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil]; + return [self db_objectWithDictionary:jsonDic]; + } + return nil; +} +- (id)db_objectWithArray:(NSArray *)array +{ + NSMutableArray *toArray = nil; + + NSInteger count = array.count; + for (NSInteger i = 0; i < count; i++) { + id value = [array objectAtIndex:i]; + if ([value isKindOfClass:[NSDictionary class]]) { + value = [self db_objectWithDictionary:value]; + } else if ([value isKindOfClass:[NSArray class]]) { + value = [self db_objectWithArray:value]; + } + + if (value) { + if (toArray == nil) { + toArray = [NSMutableArray array]; + } + [toArray addObject:value]; + } + } + + return toArray; +} +- (id)db_objectWithDictionary:(NSDictionary *)dic +{ + if (dic.count == 0) { + return nil; + } + NSString *type = [dic objectForKey:LKDB_TypeKey]; + if (type) { + if ([type isEqualToString:LKDB_TypeKey_Model]) { + Class clazz = NSClassFromString([dic objectForKey:LKDB_ClassKey]); + NSInteger rowid = [[dic objectForKey:LKDB_RowIdKey] integerValue]; + NSString *tableName = [dic objectForKey:LKDB_TableNameKey]; + + NSString *where = nil; + + NSString *rowCountWhere = [NSString stringWithFormat:@"select count(rowid) from %@ where rowid=%ld limit 1", tableName, (long)rowid]; + NSInteger result = [[[clazz getUsingLKDBHelper] executeScalarWithSQL:rowCountWhere arguments:nil] integerValue]; + if (result > 0) { + where = [NSString stringWithFormat:@"select rowid,* from %@ where rowid=%ld limit 1", tableName, (long)rowid]; + } else { + NSDictionary *pv = [dic objectForKey:LKDB_PValueKey]; + if (pv.count > 0) { + BOOL isNeedAddDot = NO; + NSMutableString *sb = [NSMutableString stringWithFormat:@"select rowid,* from %@ where", tableName]; + + NSArray *allKeys = pv.allKeys; + for (NSString *key in allKeys) { + id obj = [pv objectForKey:key]; + if (isNeedAddDot) { + [sb appendString:@" and"]; + } + [sb appendFormat:@" %@ = '%@'", key, obj]; + + isNeedAddDot = YES; + } + + [sb appendString:@" limit 1"]; + + where = [NSString stringWithString:sb]; + } + } + + if (where) { + NSArray *array = [[clazz getUsingLKDBHelper] searchWithSQL:where toClass:clazz]; + if (array.count > 0) { + NSObject *result = [array objectAtIndex:0]; + result.db_tableName = tableName; + return result; + } + } + } else if ([type isEqualToString:LKDB_TypeKey_JSON]) { + id value = [dic objectForKey:LKDB_ValueKey]; + return value; + } else if ([type isEqualToString:LKDB_TypeKey_Combo]) { + id value = [dic objectForKey:LKDB_ValueKey]; + if ([value isKindOfClass:[NSArray class]]) { + return [self db_objectWithArray:value]; + } else if ([value isKindOfClass:[NSDictionary class]]) { + return [self db_objectWithDictionary:value]; + } else { + return value; + } + } else if ([type isEqualToString:LKDB_TypeKey_Date]) { + NSString *datestr = [dic objectForKey:LKDB_ValueKey]; + NSDateFormatter *formatter = [self.class getModelDateFormatter]; + if (formatter) { + return [formatter dateFromString:datestr]; + } else { + return [LKDBUtils dateWithString:datestr]; + } + } + } else { + + NSMutableDictionary *toDic = [NSMutableDictionary dictionary]; + [dic enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull value, BOOL *_Nonnull stop) { + id saveObj = value; + if ([value isKindOfClass:[NSArray class]]) { + saveObj = [self db_objectWithArray:value]; + } else if ([value isKindOfClass:[NSDictionary class]]) { + saveObj = [self db_objectWithDictionary:value]; + } + + if (saveObj) { + toDic[key] = saveObj; + } + }]; + return toDic; + } + return nil; +} +#pragma mark - your can overwrite +- (void)setNilValueForKey:(NSString *)key +{ + NSLog(@"nil 这种设置到了 int 等基础类型中"); +} +- (id)valueForUndefinedKey:(NSString *)key +{ + NSLog(@"你有get方法没实现,key:%@", key); + return nil; +} +- (void)setValue:(id)value forUndefinedKey:(NSString *)key +{ + NSLog(@"你有set方法没实现,key:%@", key); +} + +#pragma mark - +- (void)userSetValueForModel:(LKDBProperty *)property value:(id)value +{ +} +- (id)userGetValueForModel:(LKDBProperty *)property +{ + return nil; +} + +- (NSDictionary *)db_getPrimaryKeysValues +{ + LKModelInfos *infos = [self.class getModelInfos]; + NSArray *array = infos.primaryKeys; + NSMutableDictionary *dic = [NSMutableDictionary dictionary]; + [array enumerateObjectsUsingBlock:^(NSString *pname, NSUInteger idx, BOOL *_Nonnull stop) { + LKDBProperty *property = [infos objectWithSqlColumnName:pname]; + id value = nil; + if ([property.type isEqualToString:LKSQL_Mapping_UserCalculate]) { + value = [self userGetValueForModel:property]; + } else { + value = [self modelGetValue:property]; + } + if (value) { + dic[property.sqlColumnName] = value; + } + + }]; + return dic; +} +//主键值 是否为空 +- (BOOL)singlePrimaryKeyValueIsEmpty +{ + LKDBProperty *property = [self singlePrimaryKeyProperty]; + if (property) { + id pkvalue = [self singlePrimaryKeyValue]; + if ([property.sqlColumnType isEqualToString:LKSQL_Type_Int]) { + if ([pkvalue isKindOfClass:[NSString class]]) { + if ([LKDBUtils checkStringIsEmpty:pkvalue]) + return YES; + + if ([pkvalue integerValue] == 0) + return YES; + + return NO; + } + if ([pkvalue isKindOfClass:[NSNumber class]]) { + if ([pkvalue integerValue] == 0) + return YES; + else + return NO; + } + return YES; + } else { + return (pkvalue == nil); + } + } + return NO; +} +- (LKDBProperty *)singlePrimaryKeyProperty +{ + LKModelInfos *infos = [self.class getModelInfos]; + if (infos.primaryKeys.count == 1) { + NSString *name = [infos.primaryKeys objectAtIndex:0]; + return [infos objectWithSqlColumnName:name]; + } + return nil; +} +- (id)singlePrimaryKeyValue +{ + LKDBProperty *property = [self singlePrimaryKeyProperty]; + if (property) { + if ([property.type isEqualToString:LKSQL_Mapping_UserCalculate]) { + return [self userGetValueForModel:property]; + } else { + return [self modelGetValue:property]; + } + } + return nil; +} ++ (NSString *)db_rowidAliasName +{ + LKModelInfos *infos = [self getModelInfos]; + if (infos.primaryKeys.count == 1) { + NSString *primaryType = [infos objectWithSqlColumnName:[infos.primaryKeys lastObject]].sqlColumnType; + if ([primaryType isEqualToString:LKSQL_Type_Int]) { + return [infos.primaryKeys lastObject]; + } + } + return nil; +} + +#pragma mark - get model property info ++ (LKModelInfos *)getModelInfos +{ + static __strong NSMutableDictionary *oncePropertyDic; + static __strong NSRecursiveLock *lock; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + lock = [[NSRecursiveLock alloc] init]; + oncePropertyDic = [[NSMutableDictionary alloc] initWithCapacity:8]; + }); + + LKModelInfos *infos; + [lock lock]; + NSString *className = NSStringFromClass(self); + infos = [oncePropertyDic objectForKey:className]; + if (infos == nil) { + NSMutableArray *pronames = [NSMutableArray array]; + NSMutableArray *protypes = [NSMutableArray array]; + NSDictionary *keymapping = [self getTableMapping]; + + if ([self isContainSelf] && self != [NSObject class]) { + [self getSelfPropertys:pronames protypes:protypes]; + } + + NSArray *pkArray = [self getPrimaryKeyUnionArray]; + if (pkArray.count == 0) { + pkArray = nil; + NSString *pk = [self getPrimaryKey]; + if ([LKDBUtils checkStringIsEmpty:pk] == NO) { + pkArray = [NSArray arrayWithObject:pk]; + } + } + if ([self isContainParent] && [self superclass] != [NSObject class]) { + LKModelInfos *superInfos = [[self superclass] getModelInfos]; + for (NSInteger i = 0; i < superInfos.count; i++) { + LKDBProperty *db_p = [superInfos objectWithIndex:i]; + if (db_p.propertyName && db_p.propertyType && [db_p.propertyName isEqualToString:@"rowid"] == NO) { + [pronames addObject:db_p.propertyName]; + [protypes addObject:db_p.propertyType]; + } + } + } + if (pronames.count > 0) { + infos = [[LKModelInfos alloc] initWithKeyMapping:keymapping propertyNames:pronames propertyType:protypes primaryKeys:pkArray]; + } else { + infos = [[LKModelInfos alloc] init]; + } + oncePropertyDic[className] = infos; + } + + [lock unlock]; + return infos; +} + ++ (BOOL)isContainParent +{ + return NO; +} + ++ (BOOL)isContainSelf +{ + return YES; +} + +/** + * @brief 获取自身的属性 + * + * @param pronames 保存属性名称 + * @param protypes 保存属性类型 + */ ++ (void)getSelfPropertys:(NSMutableArray *)pronames protypes:(NSMutableArray *)protypes +{ + unsigned int outCount = 0, i = 0; + objc_property_t *properties = class_copyPropertyList(self, &outCount); + + for (i = 0; i < outCount; i++) { + objc_property_t property = properties[i]; + NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding]; + + //取消rowid 的插入 //子类 已重载的属性 取消插入 + if (propertyName.length == 0 || [propertyName isEqualToString:@"rowid"] || + [pronames indexOfObject:propertyName] != NSNotFound) { + continue; + } + NSString *propertyType = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding]; + + ///过滤只读属性 + if ([propertyType rangeOfString:@",R,"].length > 0 || [propertyType hasSuffix:@",R"]) { + NSString *firstWord = [[propertyName substringToIndex:1] uppercaseString]; + NSString *otherWord = [propertyName substringFromIndex:1]; + NSString *setMethodString = [NSString stringWithFormat:@"set%@%@:", firstWord, otherWord]; + SEL setSEL = NSSelectorFromString(setMethodString); + ///有set方法就不过滤了 + if ([self instancesRespondToSelector:setSEL] == NO) { + continue; + } + } + + /* + c char + i int + l long + s short + d double + f float + @ id //指针 对象 + ... BOOL 获取到的表示 方式是 char + .... ^i 表示 int * 一般都不会用到 + */ + + NSString *propertyClassName = nil; + if ([propertyType hasPrefix:@"T@"]) { + + NSRange range = [propertyType rangeOfString:@","]; + if (range.location > 4 && range.location <= propertyType.length) { + range = NSMakeRange(3, range.location - 4); + propertyClassName = [propertyType substringWithRange:range]; + if ([propertyClassName hasSuffix:@">"]) { + NSRange categoryRange = [propertyClassName rangeOfString:@"<"]; + if (categoryRange.length > 0) { + propertyClassName = [propertyClassName substringToIndex:categoryRange.location]; + } + } + } + } else if ([propertyType hasPrefix:@"T{"]) { + NSRange range = [propertyType rangeOfString:@"="]; + if (range.location > 2 && range.location <= propertyType.length) { + range = NSMakeRange(2, range.location - 2); + propertyClassName = [propertyType substringWithRange:range]; + } + } else { + propertyType = [propertyType lowercaseString]; + if ([propertyType hasPrefix:@"ti"] || [propertyType hasPrefix:@"tb"]) { + propertyClassName = @"int"; + } else if ([propertyType hasPrefix:@"tf"]) { + propertyClassName = @"float"; + } else if ([propertyType hasPrefix:@"td"]) { + propertyClassName = @"double"; + } else if ([propertyType hasPrefix:@"tl"] || [propertyType hasPrefix:@"tq"]) { + propertyClassName = @"long"; + } else if ([propertyType hasPrefix:@"tc"]) { + propertyClassName = @"char"; + } else if ([propertyType hasPrefix:@"ts"]) { + propertyClassName = @"short"; + } + } + + if ([LKDBUtils checkStringIsEmpty:propertyClassName]) { + ///没找到具体的属性就放弃 + continue; + } + ///添加属性 + [pronames addObject:propertyName]; + [protypes addObject:propertyClassName]; + } + free(properties); + if ([self isContainParent] && [self superclass] != [NSObject class]) { + [[self superclass] getSelfPropertys:pronames protypes:protypes]; + } +} + +#pragma mark - log all property +- (NSMutableString *)getAllPropertysString +{ + Class clazz = [self class]; + NSMutableString *sb = [NSMutableString stringWithFormat:@"\n <%@> :\n", NSStringFromClass(clazz)]; + [sb appendFormat:@"rowid : %ld\n", (long)self.rowid]; + [self mutableString:sb appendPropertyStringWithClass:clazz containParent:YES]; + return sb; +} +- (NSString *)printAllPropertys +{ + return [self printAllPropertysIsContainParent:NO]; +} +- (NSString *)printAllPropertysIsContainParent:(BOOL)containParent +{ +#ifdef DEBUG + Class clazz = [self class]; + NSMutableString *sb = [NSMutableString stringWithFormat:@"\n <%@> :\n", NSStringFromClass(clazz)]; + [sb appendFormat:@"rowid : %ld\n", (long)self.rowid]; + [self mutableString:sb appendPropertyStringWithClass:clazz containParent:containParent]; + NSLog(@"%@", sb); + return sb; +#else + return @""; +#endif +} +- (void)mutableString:(NSMutableString *)sb appendPropertyStringWithClass:(Class)clazz containParent:(BOOL)containParent +{ + if (clazz == [NSObject class]) { + return; + } + unsigned int outCount = 0, i = 0; + objc_property_t *properties = class_copyPropertyList(clazz, &outCount); + for (i = 0; i < outCount; i++) { + objc_property_t property = properties[i]; + NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding]; + [sb appendFormat:@" %@ : %@ \n", propertyName, [self valueForKey:propertyName]]; + } + free(properties); + if (containParent) { + [self mutableString:sb appendPropertyStringWithClass:clazz.superclass containParent:containParent]; + } +} + +@end diff --git a/Pods/LKDBHelper/README.md b/Pods/LKDBHelper/README.md new file mode 100644 index 0000000..7317ef7 --- /dev/null +++ b/Pods/LKDBHelper/README.md @@ -0,0 +1,277 @@ + +LKDBHelper +==================================== +this is sqlite ORM (an automatic database operation)
+thread-safe and not afraid of recursive deadlock + +QQ群号 113767274 有什么问题或者改进的地方大家一起讨论 + +简书:不定时更新 [http://www.jianshu.com/users/376b950a20ec](http://www.jianshu.com/users/376b950a20ec/latest_articles) + +# Big Upgrade 2.0 + +Supported __NSArray__,__NSDictionary__, __ModelClass__, __NSNumber__, __NSString__, __NSDate__, __NSData__, __UIColor__, __UIImage__, __CGRect__, __CGPoint__, __CGSize__, __NSRange__, __int__,__char__,__float__, __double__, __long__.. attribute to insert and select automation. + +全面支持 __NSArray__,__NSDictionary__, __ModelClass__, __NSNumber__, __NSString__, __NSDate__, __NSData__, __UIColor__, __UIImage__, __CGRect__, __CGPoint__, __CGSize__, __NSRange__, __int__,__char__,__float__, __double__, __long__.. 等属性的自动化操作(插入和查询) + +------------------------------------ + +Requirements +==================================== + +* iOS 4.3+ +* ARC only +* FMDB(https://github.com/ccgus/fmdb) + +## Adding to your project + +If you are using CocoaPods, then, just add this line to your PodFile
+ +```objective-c +pod 'LKDBHelper' +``` + +If you are using Encryption, Order can not be wrong
+ +```objective-c +pod 'FMDB/SQLCipher' +pod 'LKDBHelper' +``` + +@property(strong,nonatomic)NSString* encryptionKey; + +## Basic usage + +1. Create a new Objective-C class for your data model + +```objective-c +@interface LKTest : NSObject +@property(copy,nonatomic)NSString* name; +@property NSUInteger age; +@property BOOL isGirl; + +@property(strong,nonatomic)LKTestForeign* address; +@property(strong,nonatomic)NSArray* blah; +@property(strong,nonatomic)NSDictionary* hoho; + +@property char like; +... +``` +2. in the *.m file, overwirte getTableName function (option) + +```objective-c ++(NSString *)getTableName +{ + return @"LKTestTable"; +} +``` +3. in the *.m file, overwirte callback function (option) + +```objective-c +@interface NSObject(LKDBHelper_Delegate) + ++(void)dbDidCreateTable:(LKDBHelper*)helper tableName:(NSString*)tableName; ++(void)dbDidAlterTable:(LKDBHelper*)helper tableName:(NSString*)tableName addColumns:(NSArray*)columns; + ++(BOOL)dbWillInsert:(NSObject*)entity; ++(void)dbDidInserted:(NSObject*)entity result:(BOOL)result; + ++(BOOL)dbWillUpdate:(NSObject*)entity; ++(void)dbDidUpdated:(NSObject*)entity result:(BOOL)result; + ++(BOOL)dbWillDelete:(NSObject*)entity; ++(void)dbDidDeleted:(NSObject*)entity result:(BOOL)result; + +///data read finish ++(void)dbDidSeleted:(NSObject*)entity; + +@end + +``` +4. Initialize your model with data and insert to database + +```objective-c + LKTestForeign* foreign = [[LKTestForeign alloc]init]; + foreign.address = @":asdasdasdsadasdsdas"; + foreign.postcode = 123341; + foreign.addid = 213214; + + //插入数据 insert table row + LKTest* test = [[LKTest alloc]init]; + test.name = @"zhan san"; + test.age = 16; + + //外键 foreign key + test.address = foreign; + test.blah = @[@"1",@"2",@"3"]; + test.blah = @[@"0",@[@1],@{@"2":@2},foreign]; + test.hoho = @{@"array":test.blah,@"foreign":foreign,@"normal":@123456,@"date":[NSDate date]}; + + //同步 插入第一条 数据 Insert the first + [test saveToDB]; + //or + //[globalHelper insertToDB:test]; + +``` +5. select 、 delete 、 update 、 isExists 、 rowCount ... + +```objective-c + select: + + NSMutableArray* array = [LKTest searchWithWhere:nil orderBy:nil offset:0 count:100]; + for (id obj in arraySync) { + addText(@"%@",[obj printAllPropertys]); + } + + delete: + + [LKTest deleteToDB:test]; + + update: + + test.name = "rename"; + [LKTest updateToDB:test where:nil]; + + isExists: + + [LKTest isExistsWithModel:test]; + + rowCount: + + [LKTest rowCountWithWhere:nil]; + + +``` +6. Description of parameters "where" + +```objective-c + For example: + single: @"rowid = 1" or @{@"rowid":@1} + + more: @"rowid = 1 and sex = 0" or @{@"rowid":@1,@"sex":@0} + + when where is "or" type , such as @"rowid = 1 or sex = 0" + you only use NSString + + array: @"rowid in (1,2,3)" or @{@"rowid":@[@1,@2,@3]} + + composite: @"rowid in (1,2,3) and sex=0 " or @{@"rowid":@[@1,@2,@3],@"sex":@0} + + If you want to be judged , only use NSString + For example: @"date >= '2013-04-01 00:00:00'" +``` + +## table mapping + +overwirte getTableMapping Function (option) + +```objective-c ++(NSDictionary *)getTableMapping +{ + //return nil + return @{@"name":LKSQLInherit, + @"MyAge":@"age", + @"img":LKSQLInherit, + @"MyDate":@"date", + @"color":LKSQLInherit, + @"address":LKSQLUserCalculate}; +} +``` + +## table update (option) + +```objective-c ++(void)dbDidAlterTable:(LKDBHelper *)helper tableName:(NSString *)tableName addColumns:(NSArray *)columns +{ + for (int i=0; i '2000-01-01 00:00:00'"; + property.length = 30; + } +} +``` + +## demo screenshot +![demo screenshot](https://github.com/li6185377/LKDBHelper-SQLite-ORM/raw/master/screenshot/Snip20130620_8.png) +
table test data
+![](https://github.com/li6185377/LKDBHelper-SQLite-ORM/raw/master/screenshot/Snip20130620_6.png) +
foreign key data
+![](https://github.com/li6185377/LKDBHelper-SQLite-ORM/raw/master/screenshot/Snip20130620_7.png) + +---------- +# Use in swift + +Remember to override the class function `getTableName` for model. + +Change-log +========== + +**Version 1.1** @ 2012-6-20 + +- automatic table mapping +- support optional columns +- support column attribute settings +- you can return column content + +**Version 1.0** @ 2013-5-19 + +- overwrite and rename LKDBHelper +- property type support: UIColor,NSDate,UIImage,NSData,CGRect,CGSize,CGPoint,int,float,double,NSString,short,char,bool,NSInterger.. +- fix a recursive deadlock. +- rewrite the asynchronous operation - +- thread-safe +- various bug modified optimize cache to improve performance +- test and demos +- bug fixes, speed improvements + +**Version 0.0.1** @ 2012-10-1 + +- Initial release with LKDAOBase + + +------- + +License +======= + +This code is distributed under the terms and conditions of the MIT license. + +------- + +Contribution guidelines +======= + +* if you are fixing a bug you discovered, please add also a unit test so I know how exactly to reproduce the bug before merging + +------- + +Contributors +======= + +Author: Jianghuai Li + +Contributors: waiting for you to join + diff --git a/Pods/MBProgressHUD/LICENSE b/Pods/MBProgressHUD/LICENSE new file mode 100644 index 0000000..0e357d1 --- /dev/null +++ b/Pods/MBProgressHUD/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2009-2015 Matej Bukovinski + +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/Pods/MBProgressHUD/MBProgressHUD.h b/Pods/MBProgressHUD/MBProgressHUD.h new file mode 100644 index 0000000..40e71a9 --- /dev/null +++ b/Pods/MBProgressHUD/MBProgressHUD.h @@ -0,0 +1,521 @@ +// +// MBProgressHUD.h +// Version 0.9.2 +// Created by Matej Bukovinski on 2.4.09. +// + +// This code is distributed under the terms and conditions of the MIT license. + +// Copyright (c) 2009-2015 Matej Bukovinski +// +// 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 +#import +#import + +@protocol MBProgressHUDDelegate; + + +typedef NS_ENUM(NSInteger, MBProgressHUDMode) { + /** Progress is shown using an UIActivityIndicatorView. This is the default. */ + MBProgressHUDModeIndeterminate, + /** Progress is shown using a round, pie-chart like, progress view. */ + MBProgressHUDModeDeterminate, + /** Progress is shown using a horizontal progress bar */ + MBProgressHUDModeDeterminateHorizontalBar, + /** Progress is shown using a ring-shaped progress view. */ + MBProgressHUDModeAnnularDeterminate, + /** Shows a custom view */ + MBProgressHUDModeCustomView, + /** Shows only labels */ + MBProgressHUDModeText +}; + +typedef NS_ENUM(NSInteger, MBProgressHUDAnimation) { + /** Opacity animation */ + MBProgressHUDAnimationFade, + /** Opacity + scale animation */ + MBProgressHUDAnimationZoom, + MBProgressHUDAnimationZoomOut = MBProgressHUDAnimationZoom, + MBProgressHUDAnimationZoomIn +}; + + +#ifndef MB_INSTANCETYPE +#if __has_feature(objc_instancetype) + #define MB_INSTANCETYPE instancetype +#else + #define MB_INSTANCETYPE id +#endif +#endif + +#ifndef MB_STRONG +#if __has_feature(objc_arc) + #define MB_STRONG strong +#else + #define MB_STRONG retain +#endif +#endif + +#ifndef MB_WEAK +#if __has_feature(objc_arc_weak) + #define MB_WEAK weak +#elif __has_feature(objc_arc) + #define MB_WEAK unsafe_unretained +#else + #define MB_WEAK assign +#endif +#endif + +#if NS_BLOCKS_AVAILABLE +typedef void (^MBProgressHUDCompletionBlock)(); +#endif + + +/** + * Displays a simple HUD window containing a progress indicator and two optional labels for short messages. + * + * This is a simple drop-in class for displaying a progress HUD view similar to Apple's private UIProgressHUD class. + * The MBProgressHUD window spans over the entire space given to it by the initWithFrame constructor and catches all + * user input on this region, thereby preventing the user operations on components below the view. The HUD itself is + * drawn centered as a rounded semi-transparent view which resizes depending on the user specified content. + * + * This view supports four modes of operation: + * - MBProgressHUDModeIndeterminate - shows a UIActivityIndicatorView + * - MBProgressHUDModeDeterminate - shows a custom round progress indicator + * - MBProgressHUDModeAnnularDeterminate - shows a custom annular progress indicator + * - MBProgressHUDModeCustomView - shows an arbitrary, user specified view (see `customView`) + * + * All three modes can have optional labels assigned: + * - If the labelText property is set and non-empty then a label containing the provided content is placed below the + * indicator view. + * - If also the detailsLabelText property is set then another label is placed below the first label. + */ +@interface MBProgressHUD : UIView + +/** + * Creates a new HUD, adds it to provided view and shows it. The counterpart to this method is hideHUDForView:animated:. + * + * @note This method sets `removeFromSuperViewOnHide`. The HUD will automatically be removed from the view hierarchy when hidden. + * + * @param view The view that the HUD will be added to + * @param animated If set to YES the HUD will appear using the current animationType. If set to NO the HUD will not use + * animations while appearing. + * @return A reference to the created HUD. + * + * @see hideHUDForView:animated: + * @see animationType + */ ++ (MB_INSTANCETYPE)showHUDAddedTo:(UIView *)view animated:(BOOL)animated; + +/** + * Finds the top-most HUD subview and hides it. The counterpart to this method is showHUDAddedTo:animated:. + * + * @note This method sets `removeFromSuperViewOnHide`. The HUD will automatically be removed from the view hierarchy when hidden. + * + * @param view The view that is going to be searched for a HUD subview. + * @param animated If set to YES the HUD will disappear using the current animationType. If set to NO the HUD will not use + * animations while disappearing. + * @return YES if a HUD was found and removed, NO otherwise. + * + * @see showHUDAddedTo:animated: + * @see animationType + */ ++ (BOOL)hideHUDForView:(UIView *)view animated:(BOOL)animated; + +/** + * Finds all the HUD subviews and hides them. + * + * @note This method sets `removeFromSuperViewOnHide`. The HUDs will automatically be removed from the view hierarchy when hidden. + * + * @param view The view that is going to be searched for HUD subviews. + * @param animated If set to YES the HUDs will disappear using the current animationType. If set to NO the HUDs will not use + * animations while disappearing. + * @return the number of HUDs found and removed. + * + * @see hideHUDForView:animated: + * @see animationType + */ ++ (NSUInteger)hideAllHUDsForView:(UIView *)view animated:(BOOL)animated; + +/** + * Finds the top-most HUD subview and returns it. + * + * @param view The view that is going to be searched. + * @return A reference to the last HUD subview discovered. + */ ++ (MB_INSTANCETYPE)HUDForView:(UIView *)view; + +/** + * Finds all HUD subviews and returns them. + * + * @param view The view that is going to be searched. + * @return All found HUD views (array of MBProgressHUD objects). + */ ++ (NSArray *)allHUDsForView:(UIView *)view; + +/** + * A convenience constructor that initializes the HUD with the window's bounds. Calls the designated constructor with + * window.bounds as the parameter. + * + * @param window The window instance that will provide the bounds for the HUD. Should be the same instance as + * the HUD's superview (i.e., the window that the HUD will be added to). + */ +- (id)initWithWindow:(UIWindow *)window; + +/** + * A convenience constructor that initializes the HUD with the view's bounds. Calls the designated constructor with + * view.bounds as the parameter + * + * @param view The view instance that will provide the bounds for the HUD. Should be the same instance as + * the HUD's superview (i.e., the view that the HUD will be added to). + */ +- (id)initWithView:(UIView *)view; + +/** + * Display the HUD. You need to make sure that the main thread completes its run loop soon after this method call so + * the user interface can be updated. Call this method when your task is already set-up to be executed in a new thread + * (e.g., when using something like NSOperation or calling an asynchronous call like NSURLRequest). + * + * @param animated If set to YES the HUD will appear using the current animationType. If set to NO the HUD will not use + * animations while appearing. + * + * @see animationType + */ +- (void)show:(BOOL)animated; + +/** + * Hide the HUD. This still calls the hudWasHidden: delegate. This is the counterpart of the show: method. Use it to + * hide the HUD when your task completes. + * + * @param animated If set to YES the HUD will disappear using the current animationType. If set to NO the HUD will not use + * animations while disappearing. + * + * @see animationType + */ +- (void)hide:(BOOL)animated; + +/** + * Hide the HUD after a delay. This still calls the hudWasHidden: delegate. This is the counterpart of the show: method. Use it to + * hide the HUD when your task completes. + * + * @param animated If set to YES the HUD will disappear using the current animationType. If set to NO the HUD will not use + * animations while disappearing. + * @param delay Delay in seconds until the HUD is hidden. + * + * @see animationType + */ +- (void)hide:(BOOL)animated afterDelay:(NSTimeInterval)delay; + +/** + * Shows the HUD while a background task is executing in a new thread, then hides the HUD. + * + * This method also takes care of autorelease pools so your method does not have to be concerned with setting up a + * pool. + * + * @param method The method to be executed while the HUD is shown. This method will be executed in a new thread. + * @param target The object that the target method belongs to. + * @param object An optional object to be passed to the method. + * @param animated If set to YES the HUD will (dis)appear using the current animationType. If set to NO the HUD will not use + * animations while (dis)appearing. + */ +- (void)showWhileExecuting:(SEL)method onTarget:(id)target withObject:(id)object animated:(BOOL)animated; + +#if NS_BLOCKS_AVAILABLE + +/** + * Shows the HUD while a block is executing on a background queue, then hides the HUD. + * + * @see showAnimated:whileExecutingBlock:onQueue:completionBlock: + */ +- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block; + +/** + * Shows the HUD while a block is executing on a background queue, then hides the HUD. + * + * @see showAnimated:whileExecutingBlock:onQueue:completionBlock: + */ +- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block completionBlock:(MBProgressHUDCompletionBlock)completion; + +/** + * Shows the HUD while a block is executing on the specified dispatch queue, then hides the HUD. + * + * @see showAnimated:whileExecutingBlock:onQueue:completionBlock: + */ +- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue; + +/** + * Shows the HUD while a block is executing on the specified dispatch queue, executes completion block on the main queue, and then hides the HUD. + * + * @param animated If set to YES the HUD will (dis)appear using the current animationType. If set to NO the HUD will + * not use animations while (dis)appearing. + * @param block The block to be executed while the HUD is shown. + * @param queue The dispatch queue on which the block should be executed. + * @param completion The block to be executed on completion. + * + * @see completionBlock + */ +- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue + completionBlock:(MBProgressHUDCompletionBlock)completion; + +/** + * A block that gets called after the HUD was completely hidden. + */ +@property (copy) MBProgressHUDCompletionBlock completionBlock; + +#endif + +/** + * MBProgressHUD operation mode. The default is MBProgressHUDModeIndeterminate. + * + * @see MBProgressHUDMode + */ +@property (assign) MBProgressHUDMode mode; + +/** + * The animation type that should be used when the HUD is shown and hidden. + * + * @see MBProgressHUDAnimation + */ +@property (assign) MBProgressHUDAnimation animationType; + +/** + * The UIView (e.g., a UIImageView) to be shown when the HUD is in MBProgressHUDModeCustomView. + * For best results use a 37 by 37 pixel view (so the bounds match the built in indicator bounds). + */ +@property (MB_STRONG) UIView *customView; + +/** + * The HUD delegate object. + * + * @see MBProgressHUDDelegate + */ +@property (MB_WEAK) id delegate; + +/** + * An optional short message to be displayed below the activity indicator. The HUD is automatically resized to fit + * the entire text. If the text is too long it will get clipped by displaying "..." at the end. If left unchanged or + * set to @"", then no message is displayed. + */ +@property (copy) NSString *labelText; + +/** + * An optional details message displayed below the labelText message. This message is displayed only if the labelText + * property is also set and is different from an empty string (@""). The details text can span multiple lines. + */ +@property (copy) NSString *detailsLabelText; + +/** + * The opacity of the HUD window. Defaults to 0.8 (80% opacity). + */ +@property (assign) float opacity; + +/** + * The color of the HUD window. Defaults to black. If this property is set, color is set using + * this UIColor and the opacity property is not used. using retain because performing copy on + * UIColor base colors (like [UIColor greenColor]) cause problems with the copyZone. + */ +@property (MB_STRONG) UIColor *color; + +/** + * The x-axis offset of the HUD relative to the centre of the superview. + */ +@property (assign) float xOffset; + +/** + * The y-axis offset of the HUD relative to the centre of the superview. + */ +@property (assign) float yOffset; + +/** + * The amount of space between the HUD edge and the HUD elements (labels, indicators or custom views). + * Defaults to 20.0 + */ +@property (assign) float margin; + +/** + * The corner radius for the HUD + * Defaults to 10.0 + */ +@property (assign) float cornerRadius; + +/** + * Cover the HUD background view with a radial gradient. + */ +@property (assign) BOOL dimBackground; + +/* + * Grace period is the time (in seconds) that the invoked method may be run without + * showing the HUD. If the task finishes before the grace time runs out, the HUD will + * not be shown at all. + * This may be used to prevent HUD display for very short tasks. + * Defaults to 0 (no grace time). + * Grace time functionality is only supported when the task status is known! + * @see taskInProgress + */ +@property (assign) float graceTime; + +/** + * The minimum time (in seconds) that the HUD is shown. + * This avoids the problem of the HUD being shown and than instantly hidden. + * Defaults to 0 (no minimum show time). + */ +@property (assign) float minShowTime; + +/** + * Indicates that the executed operation is in progress. Needed for correct graceTime operation. + * If you don't set a graceTime (different than 0.0) this does nothing. + * This property is automatically set when using showWhileExecuting:onTarget:withObject:animated:. + * When threading is done outside of the HUD (i.e., when the show: and hide: methods are used directly), + * you need to set this property when your task starts and completes in order to have normal graceTime + * functionality. + */ +@property (assign) BOOL taskInProgress; + +/** + * Removes the HUD from its parent view when hidden. + * Defaults to NO. + */ +@property (assign) BOOL removeFromSuperViewOnHide; + +/** + * Font to be used for the main label. Set this property if the default is not adequate. + */ +@property (MB_STRONG) UIFont* labelFont; + +/** + * Color to be used for the main label. Set this property if the default is not adequate. + */ +@property (MB_STRONG) UIColor* labelColor; + +/** + * Font to be used for the details label. Set this property if the default is not adequate. + */ +@property (MB_STRONG) UIFont* detailsLabelFont; + +/** + * Color to be used for the details label. Set this property if the default is not adequate. + */ +@property (MB_STRONG) UIColor* detailsLabelColor; + +/** + * The color of the activity indicator. Defaults to [UIColor whiteColor] + * Does nothing on pre iOS 5. + */ +@property (MB_STRONG) UIColor *activityIndicatorColor; + +/** + * The progress of the progress indicator, from 0.0 to 1.0. Defaults to 0.0. + */ +@property (assign) float progress; + +/** + * The minimum size of the HUD bezel. Defaults to CGSizeZero (no minimum size). + */ +@property (assign) CGSize minSize; + + +/** + * The actual size of the HUD bezel. + * You can use this to limit touch handling on the bezel area only. + * @see https://github.com/jdg/MBProgressHUD/pull/200 + */ +@property (atomic, assign, readonly) CGSize size; + + +/** + * Force the HUD dimensions to be equal if possible. + */ +@property (assign, getter = isSquare) BOOL square; + +@end + + +@protocol MBProgressHUDDelegate + +@optional + +/** + * Called after the HUD was fully hidden from the screen. + */ +- (void)hudWasHidden:(MBProgressHUD *)hud; + +@end + + +/** + * A progress view for showing definite progress by filling up a circle (pie chart). + */ +@interface MBRoundProgressView : UIView + +/** + * Progress (0.0 to 1.0) + */ +@property (nonatomic, assign) float progress; + +/** + * Indicator progress color. + * Defaults to white [UIColor whiteColor] + */ +@property (nonatomic, MB_STRONG) UIColor *progressTintColor; + +/** + * Indicator background (non-progress) color. + * Defaults to translucent white (alpha 0.1) + */ +@property (nonatomic, MB_STRONG) UIColor *backgroundTintColor; + +/* + * Display mode - NO = round or YES = annular. Defaults to round. + */ +@property (nonatomic, assign, getter = isAnnular) BOOL annular; + +@end + + +/** + * A flat bar progress view. + */ +@interface MBBarProgressView : UIView + +/** + * Progress (0.0 to 1.0) + */ +@property (nonatomic, assign) float progress; + +/** + * Bar border line color. + * Defaults to white [UIColor whiteColor]. + */ +@property (nonatomic, MB_STRONG) UIColor *lineColor; + +/** + * Bar background color. + * Defaults to clear [UIColor clearColor]; + */ +@property (nonatomic, MB_STRONG) UIColor *progressRemainingColor; + +/** + * Bar progress color. + * Defaults to white [UIColor whiteColor]. + */ +@property (nonatomic, MB_STRONG) UIColor *progressColor; + +@end diff --git a/Pods/MBProgressHUD/MBProgressHUD.m b/Pods/MBProgressHUD/MBProgressHUD.m new file mode 100644 index 0000000..bf5f7ff --- /dev/null +++ b/Pods/MBProgressHUD/MBProgressHUD.m @@ -0,0 +1,1033 @@ +// +// MBProgressHUD.m +// Version 0.9.2 +// Created by Matej Bukovinski on 2.4.09. +// + +#import "MBProgressHUD.h" +#import + + +#if __has_feature(objc_arc) + #define MB_AUTORELEASE(exp) exp + #define MB_RELEASE(exp) exp + #define MB_RETAIN(exp) exp +#else + #define MB_AUTORELEASE(exp) [exp autorelease] + #define MB_RELEASE(exp) [exp release] + #define MB_RETAIN(exp) [exp retain] +#endif + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 60000 + #define MBLabelAlignmentCenter NSTextAlignmentCenter +#else + #define MBLabelAlignmentCenter UITextAlignmentCenter +#endif + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 + #define MB_TEXTSIZE(text, font) [text length] > 0 ? [text \ + sizeWithAttributes:@{NSFontAttributeName:font}] : CGSizeZero; +#else + #define MB_TEXTSIZE(text, font) [text length] > 0 ? [text sizeWithFont:font] : CGSizeZero; +#endif + +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000 + #define MB_MULTILINE_TEXTSIZE(text, font, maxSize, mode) [text length] > 0 ? [text \ + boundingRectWithSize:maxSize options:(NSStringDrawingUsesLineFragmentOrigin) \ + attributes:@{NSFontAttributeName:font} context:nil].size : CGSizeZero; +#else + #define MB_MULTILINE_TEXTSIZE(text, font, maxSize, mode) [text length] > 0 ? [text \ + sizeWithFont:font constrainedToSize:maxSize lineBreakMode:mode] : CGSizeZero; +#endif + +#ifndef kCFCoreFoundationVersionNumber_iOS_7_0 + #define kCFCoreFoundationVersionNumber_iOS_7_0 847.20 +#endif + +#ifndef kCFCoreFoundationVersionNumber_iOS_8_0 + #define kCFCoreFoundationVersionNumber_iOS_8_0 1129.15 +#endif + + +static const CGFloat kPadding = 4.f; +static const CGFloat kLabelFontSize = 16.f; +static const CGFloat kDetailsLabelFontSize = 12.f; + + +@interface MBProgressHUD () { + BOOL useAnimation; + SEL methodForExecution; + id targetForExecution; + id objectForExecution; + UILabel *label; + UILabel *detailsLabel; + BOOL isFinished; + CGAffineTransform rotationTransform; +} + +@property (atomic, MB_STRONG) UIView *indicator; +@property (atomic, MB_STRONG) NSTimer *graceTimer; +@property (atomic, MB_STRONG) NSTimer *minShowTimer; +@property (atomic, MB_STRONG) NSDate *showStarted; + +@end + + +@implementation MBProgressHUD + +#pragma mark - Properties + +@synthesize animationType; +@synthesize delegate; +@synthesize opacity; +@synthesize color; +@synthesize labelFont; +@synthesize labelColor; +@synthesize detailsLabelFont; +@synthesize detailsLabelColor; +@synthesize indicator; +@synthesize xOffset; +@synthesize yOffset; +@synthesize minSize; +@synthesize square; +@synthesize margin; +@synthesize dimBackground; +@synthesize graceTime; +@synthesize minShowTime; +@synthesize graceTimer; +@synthesize minShowTimer; +@synthesize taskInProgress; +@synthesize removeFromSuperViewOnHide; +@synthesize customView; +@synthesize showStarted; +@synthesize mode; +@synthesize labelText; +@synthesize detailsLabelText; +@synthesize progress; +@synthesize size; +@synthesize activityIndicatorColor; +#if NS_BLOCKS_AVAILABLE +@synthesize completionBlock; +#endif + +#pragma mark - Class methods + ++ (MB_INSTANCETYPE)showHUDAddedTo:(UIView *)view animated:(BOOL)animated { + MBProgressHUD *hud = [[self alloc] initWithView:view]; + hud.removeFromSuperViewOnHide = YES; + [view addSubview:hud]; + [hud show:animated]; + return MB_AUTORELEASE(hud); +} + ++ (BOOL)hideHUDForView:(UIView *)view animated:(BOOL)animated { + MBProgressHUD *hud = [self HUDForView:view]; + if (hud != nil) { + hud.removeFromSuperViewOnHide = YES; + [hud hide:animated]; + return YES; + } + return NO; +} + ++ (NSUInteger)hideAllHUDsForView:(UIView *)view animated:(BOOL)animated { + NSArray *huds = [MBProgressHUD allHUDsForView:view]; + for (MBProgressHUD *hud in huds) { + hud.removeFromSuperViewOnHide = YES; + [hud hide:animated]; + } + return [huds count]; +} + ++ (MB_INSTANCETYPE)HUDForView:(UIView *)view { + NSEnumerator *subviewsEnum = [view.subviews reverseObjectEnumerator]; + for (UIView *subview in subviewsEnum) { + if ([subview isKindOfClass:self]) { + return (MBProgressHUD *)subview; + } + } + return nil; +} + ++ (NSArray *)allHUDsForView:(UIView *)view { + NSMutableArray *huds = [NSMutableArray array]; + NSArray *subviews = view.subviews; + for (UIView *aView in subviews) { + if ([aView isKindOfClass:self]) { + [huds addObject:aView]; + } + } + return [NSArray arrayWithArray:huds]; +} + +#pragma mark - Lifecycle + +- (id)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self) { + // Set default values for properties + self.animationType = MBProgressHUDAnimationFade; + self.mode = MBProgressHUDModeIndeterminate; + self.labelText = nil; + self.detailsLabelText = nil; + self.opacity = 0.8f; + self.color = nil; + self.labelFont = [UIFont boldSystemFontOfSize:kLabelFontSize]; + self.labelColor = [UIColor whiteColor]; + self.detailsLabelFont = [UIFont boldSystemFontOfSize:kDetailsLabelFontSize]; + self.detailsLabelColor = [UIColor whiteColor]; + self.activityIndicatorColor = [UIColor whiteColor]; + self.xOffset = 0.0f; + self.yOffset = 0.0f; + self.dimBackground = NO; + self.margin = 20.0f; + self.cornerRadius = 10.0f; + self.graceTime = 0.0f; + self.minShowTime = 0.0f; + self.removeFromSuperViewOnHide = NO; + self.minSize = CGSizeZero; + self.square = NO; + self.contentMode = UIViewContentModeCenter; + self.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin + | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin; + + // Transparent background + self.opaque = NO; + self.backgroundColor = [UIColor clearColor]; + // Make it invisible for now + self.alpha = 0.0f; + + taskInProgress = NO; + rotationTransform = CGAffineTransformIdentity; + + [self setupLabels]; + [self updateIndicators]; + [self registerForKVO]; + [self registerForNotifications]; + } + return self; +} + +- (id)initWithView:(UIView *)view { + NSAssert(view, @"View must not be nil."); + return [self initWithFrame:view.bounds]; +} + +- (id)initWithWindow:(UIWindow *)window { + return [self initWithView:window]; +} + +- (void)dealloc { + [self unregisterFromNotifications]; + [self unregisterFromKVO]; +#if !__has_feature(objc_arc) + [color release]; + [indicator release]; + [label release]; + [detailsLabel release]; + [labelText release]; + [detailsLabelText release]; + [graceTimer release]; + [minShowTimer release]; + [showStarted release]; + [customView release]; + [labelFont release]; + [labelColor release]; + [detailsLabelFont release]; + [detailsLabelColor release]; +#if NS_BLOCKS_AVAILABLE + [completionBlock release]; +#endif + [super dealloc]; +#endif +} + +#pragma mark - Show & hide + +- (void)show:(BOOL)animated { + NSAssert([NSThread isMainThread], @"MBProgressHUD needs to be accessed on the main thread."); + useAnimation = animated; + // If the grace time is set postpone the HUD display + if (self.graceTime > 0.0) { + NSTimer *newGraceTimer = [NSTimer timerWithTimeInterval:self.graceTime target:self selector:@selector(handleGraceTimer:) userInfo:nil repeats:NO]; + [[NSRunLoop currentRunLoop] addTimer:newGraceTimer forMode:NSRunLoopCommonModes]; + self.graceTimer = newGraceTimer; + } + // ... otherwise show the HUD imediately + else { + [self showUsingAnimation:useAnimation]; + } +} + +- (void)hide:(BOOL)animated { + NSAssert([NSThread isMainThread], @"MBProgressHUD needs to be accessed on the main thread."); + useAnimation = animated; + // If the minShow time is set, calculate how long the hud was shown, + // and pospone the hiding operation if necessary + if (self.minShowTime > 0.0 && showStarted) { + NSTimeInterval interv = [[NSDate date] timeIntervalSinceDate:showStarted]; + if (interv < self.minShowTime) { + self.minShowTimer = [NSTimer scheduledTimerWithTimeInterval:(self.minShowTime - interv) target:self + selector:@selector(handleMinShowTimer:) userInfo:nil repeats:NO]; + return; + } + } + // ... otherwise hide the HUD immediately + [self hideUsingAnimation:useAnimation]; +} + +- (void)hide:(BOOL)animated afterDelay:(NSTimeInterval)delay { + [self performSelector:@selector(hideDelayed:) withObject:[NSNumber numberWithBool:animated] afterDelay:delay]; +} + +- (void)hideDelayed:(NSNumber *)animated { + [self hide:[animated boolValue]]; +} + +#pragma mark - Timer callbacks + +- (void)handleGraceTimer:(NSTimer *)theTimer { + // Show the HUD only if the task is still running + if (taskInProgress) { + [self showUsingAnimation:useAnimation]; + } +} + +- (void)handleMinShowTimer:(NSTimer *)theTimer { + [self hideUsingAnimation:useAnimation]; +} + +#pragma mark - View Hierrarchy + +- (void)didMoveToSuperview { + [self updateForCurrentOrientationAnimated:NO]; +} + +#pragma mark - Internal show & hide operations + +- (void)showUsingAnimation:(BOOL)animated { + // Cancel any scheduled hideDelayed: calls + [NSObject cancelPreviousPerformRequestsWithTarget:self]; + [self setNeedsDisplay]; + + if (animated && animationType == MBProgressHUDAnimationZoomIn) { + self.transform = CGAffineTransformConcat(rotationTransform, CGAffineTransformMakeScale(0.5f, 0.5f)); + } else if (animated && animationType == MBProgressHUDAnimationZoomOut) { + self.transform = CGAffineTransformConcat(rotationTransform, CGAffineTransformMakeScale(1.5f, 1.5f)); + } + self.showStarted = [NSDate date]; + // Fade in + if (animated) { + [UIView beginAnimations:nil context:NULL]; + [UIView setAnimationDuration:0.30]; + self.alpha = 1.0f; + if (animationType == MBProgressHUDAnimationZoomIn || animationType == MBProgressHUDAnimationZoomOut) { + self.transform = rotationTransform; + } + [UIView commitAnimations]; + } + else { + self.alpha = 1.0f; + } +} + +- (void)hideUsingAnimation:(BOOL)animated { + // Fade out + if (animated && showStarted) { + [UIView beginAnimations:nil context:NULL]; + [UIView setAnimationDuration:0.30]; + [UIView setAnimationDelegate:self]; + [UIView setAnimationDidStopSelector:@selector(animationFinished:finished:context:)]; + // 0.02 prevents the hud from passing through touches during the animation the hud will get completely hidden + // in the done method + if (animationType == MBProgressHUDAnimationZoomIn) { + self.transform = CGAffineTransformConcat(rotationTransform, CGAffineTransformMakeScale(1.5f, 1.5f)); + } else if (animationType == MBProgressHUDAnimationZoomOut) { + self.transform = CGAffineTransformConcat(rotationTransform, CGAffineTransformMakeScale(0.5f, 0.5f)); + } + + self.alpha = 0.02f; + [UIView commitAnimations]; + } + else { + self.alpha = 0.0f; + [self done]; + } + self.showStarted = nil; +} + +- (void)animationFinished:(NSString *)animationID finished:(BOOL)finished context:(void*)context { + [self done]; +} + +- (void)done { + [NSObject cancelPreviousPerformRequestsWithTarget:self]; + isFinished = YES; + self.alpha = 0.0f; + if (removeFromSuperViewOnHide) { + [self removeFromSuperview]; + } +#if NS_BLOCKS_AVAILABLE + if (self.completionBlock) { + self.completionBlock(); + self.completionBlock = NULL; + } +#endif + if ([delegate respondsToSelector:@selector(hudWasHidden:)]) { + [delegate performSelector:@selector(hudWasHidden:) withObject:self]; + } +} + +#pragma mark - Threading + +- (void)showWhileExecuting:(SEL)method onTarget:(id)target withObject:(id)object animated:(BOOL)animated { + methodForExecution = method; + targetForExecution = MB_RETAIN(target); + objectForExecution = MB_RETAIN(object); + // Launch execution in new thread + self.taskInProgress = YES; + [NSThread detachNewThreadSelector:@selector(launchExecution) toTarget:self withObject:nil]; + // Show HUD view + [self show:animated]; +} + +#if NS_BLOCKS_AVAILABLE + +- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block { + dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + [self showAnimated:animated whileExecutingBlock:block onQueue:queue completionBlock:NULL]; +} + +- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block completionBlock:(void (^)())completion { + dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + [self showAnimated:animated whileExecutingBlock:block onQueue:queue completionBlock:completion]; +} + +- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue { + [self showAnimated:animated whileExecutingBlock:block onQueue:queue completionBlock:NULL]; +} + +- (void)showAnimated:(BOOL)animated whileExecutingBlock:(dispatch_block_t)block onQueue:(dispatch_queue_t)queue + completionBlock:(MBProgressHUDCompletionBlock)completion { + self.taskInProgress = YES; + self.completionBlock = completion; + dispatch_async(queue, ^(void) { + block(); + dispatch_async(dispatch_get_main_queue(), ^(void) { + [self cleanUp]; + }); + }); + [self show:animated]; +} + +#endif + +- (void)launchExecution { + @autoreleasepool { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + // Start executing the requested task + [targetForExecution performSelector:methodForExecution withObject:objectForExecution]; +#pragma clang diagnostic pop + // Task completed, update view in main thread (note: view operations should + // be done only in the main thread) + [self performSelectorOnMainThread:@selector(cleanUp) withObject:nil waitUntilDone:NO]; + } +} + +- (void)cleanUp { + taskInProgress = NO; +#if !__has_feature(objc_arc) + [targetForExecution release]; + [objectForExecution release]; +#else + targetForExecution = nil; + objectForExecution = nil; +#endif + [self hide:useAnimation]; +} + +#pragma mark - UI + +- (void)setupLabels { + label = [[UILabel alloc] initWithFrame:self.bounds]; + label.adjustsFontSizeToFitWidth = NO; + label.textAlignment = MBLabelAlignmentCenter; + label.opaque = NO; + label.backgroundColor = [UIColor clearColor]; + label.textColor = self.labelColor; + label.font = self.labelFont; + label.text = self.labelText; + [self addSubview:label]; + + detailsLabel = [[UILabel alloc] initWithFrame:self.bounds]; + detailsLabel.font = self.detailsLabelFont; + detailsLabel.adjustsFontSizeToFitWidth = NO; + detailsLabel.textAlignment = MBLabelAlignmentCenter; + detailsLabel.opaque = NO; + detailsLabel.backgroundColor = [UIColor clearColor]; + detailsLabel.textColor = self.detailsLabelColor; + detailsLabel.numberOfLines = 0; + detailsLabel.font = self.detailsLabelFont; + detailsLabel.text = self.detailsLabelText; + [self addSubview:detailsLabel]; +} + +- (void)updateIndicators { + + BOOL isActivityIndicator = [indicator isKindOfClass:[UIActivityIndicatorView class]]; + BOOL isRoundIndicator = [indicator isKindOfClass:[MBRoundProgressView class]]; + + if (mode == MBProgressHUDModeIndeterminate) { + if (!isActivityIndicator) { + // Update to indeterminate indicator + [indicator removeFromSuperview]; + self.indicator = MB_AUTORELEASE([[UIActivityIndicatorView alloc] + initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]); + [(UIActivityIndicatorView *)indicator startAnimating]; + [self addSubview:indicator]; + } +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 50000 + [(UIActivityIndicatorView *)indicator setColor:self.activityIndicatorColor]; +#endif + } + else if (mode == MBProgressHUDModeDeterminateHorizontalBar) { + // Update to bar determinate indicator + [indicator removeFromSuperview]; + self.indicator = MB_AUTORELEASE([[MBBarProgressView alloc] init]); + [self addSubview:indicator]; + } + else if (mode == MBProgressHUDModeDeterminate || mode == MBProgressHUDModeAnnularDeterminate) { + if (!isRoundIndicator) { + // Update to determinante indicator + [indicator removeFromSuperview]; + self.indicator = MB_AUTORELEASE([[MBRoundProgressView alloc] init]); + [self addSubview:indicator]; + } + if (mode == MBProgressHUDModeAnnularDeterminate) { + [(MBRoundProgressView *)indicator setAnnular:YES]; + } + [(MBRoundProgressView *)indicator setProgressTintColor:self.activityIndicatorColor]; + [(MBRoundProgressView *)indicator setBackgroundTintColor:[self.activityIndicatorColor colorWithAlphaComponent:0.1f]]; + } + else if (mode == MBProgressHUDModeCustomView && customView != indicator) { + // Update custom view indicator + [indicator removeFromSuperview]; + self.indicator = customView; + [self addSubview:indicator]; + } else if (mode == MBProgressHUDModeText) { + [indicator removeFromSuperview]; + self.indicator = nil; + } +} + +#pragma mark - Layout + +- (void)layoutSubviews { + [super layoutSubviews]; + + // Entirely cover the parent view + UIView *parent = self.superview; + if (parent) { + self.frame = parent.bounds; + } + CGRect bounds = self.bounds; + + // Determine the total width and height needed + CGFloat maxWidth = bounds.size.width - 4 * margin; + CGSize totalSize = CGSizeZero; + + CGRect indicatorF = indicator.bounds; + indicatorF.size.width = MIN(indicatorF.size.width, maxWidth); + totalSize.width = MAX(totalSize.width, indicatorF.size.width); + totalSize.height += indicatorF.size.height; + + CGSize labelSize = MB_TEXTSIZE(label.text, label.font); + labelSize.width = MIN(labelSize.width, maxWidth); + totalSize.width = MAX(totalSize.width, labelSize.width); + totalSize.height += labelSize.height; + if (labelSize.height > 0.f && indicatorF.size.height > 0.f) { + totalSize.height += kPadding; + } + + CGFloat remainingHeight = bounds.size.height - totalSize.height - kPadding - 4 * margin; + CGSize maxSize = CGSizeMake(maxWidth, remainingHeight); + CGSize detailsLabelSize = MB_MULTILINE_TEXTSIZE(detailsLabel.text, detailsLabel.font, maxSize, detailsLabel.lineBreakMode); + totalSize.width = MAX(totalSize.width, detailsLabelSize.width); + totalSize.height += detailsLabelSize.height; + if (detailsLabelSize.height > 0.f && (indicatorF.size.height > 0.f || labelSize.height > 0.f)) { + totalSize.height += kPadding; + } + + totalSize.width += 2 * margin; + totalSize.height += 2 * margin; + + // Position elements + CGFloat yPos = round(((bounds.size.height - totalSize.height) / 2)) + margin + yOffset; + CGFloat xPos = xOffset; + indicatorF.origin.y = yPos; + indicatorF.origin.x = round((bounds.size.width - indicatorF.size.width) / 2) + xPos; + indicator.frame = indicatorF; + yPos += indicatorF.size.height; + + if (labelSize.height > 0.f && indicatorF.size.height > 0.f) { + yPos += kPadding; + } + CGRect labelF; + labelF.origin.y = yPos; + labelF.origin.x = round((bounds.size.width - labelSize.width) / 2) + xPos; + labelF.size = labelSize; + label.frame = labelF; + yPos += labelF.size.height; + + if (detailsLabelSize.height > 0.f && (indicatorF.size.height > 0.f || labelSize.height > 0.f)) { + yPos += kPadding; + } + CGRect detailsLabelF; + detailsLabelF.origin.y = yPos; + detailsLabelF.origin.x = round((bounds.size.width - detailsLabelSize.width) / 2) + xPos; + detailsLabelF.size = detailsLabelSize; + detailsLabel.frame = detailsLabelF; + + // Enforce minsize and quare rules + if (square) { + CGFloat max = MAX(totalSize.width, totalSize.height); + if (max <= bounds.size.width - 2 * margin) { + totalSize.width = max; + } + if (max <= bounds.size.height - 2 * margin) { + totalSize.height = max; + } + } + if (totalSize.width < minSize.width) { + totalSize.width = minSize.width; + } + if (totalSize.height < minSize.height) { + totalSize.height = minSize.height; + } + + size = totalSize; +} + +#pragma mark BG Drawing + +- (void)drawRect:(CGRect)rect { + + CGContextRef context = UIGraphicsGetCurrentContext(); + UIGraphicsPushContext(context); + + if (self.dimBackground) { + //Gradient colours + size_t gradLocationsNum = 2; + CGFloat gradLocations[2] = {0.0f, 1.0f}; + CGFloat gradColors[8] = {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.75f}; + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocations, gradLocationsNum); + CGColorSpaceRelease(colorSpace); + //Gradient center + CGPoint gradCenter= CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2); + //Gradient radius + float gradRadius = MIN(self.bounds.size.width , self.bounds.size.height) ; + //Gradient draw + CGContextDrawRadialGradient (context, gradient, gradCenter, + 0, gradCenter, gradRadius, + kCGGradientDrawsAfterEndLocation); + CGGradientRelease(gradient); + } + + // Set background rect color + if (self.color) { + CGContextSetFillColorWithColor(context, self.color.CGColor); + } else { + CGContextSetGrayFillColor(context, 0.0f, self.opacity); + } + + + // Center HUD + CGRect allRect = self.bounds; + // Draw rounded HUD backgroud rect + CGRect boxRect = CGRectMake(round((allRect.size.width - size.width) / 2) + self.xOffset, + round((allRect.size.height - size.height) / 2) + self.yOffset, size.width, size.height); + float radius = self.cornerRadius; + CGContextBeginPath(context); + CGContextMoveToPoint(context, CGRectGetMinX(boxRect) + radius, CGRectGetMinY(boxRect)); + CGContextAddArc(context, CGRectGetMaxX(boxRect) - radius, CGRectGetMinY(boxRect) + radius, radius, 3 * (float)M_PI / 2, 0, 0); + CGContextAddArc(context, CGRectGetMaxX(boxRect) - radius, CGRectGetMaxY(boxRect) - radius, radius, 0, (float)M_PI / 2, 0); + CGContextAddArc(context, CGRectGetMinX(boxRect) + radius, CGRectGetMaxY(boxRect) - radius, radius, (float)M_PI / 2, (float)M_PI, 0); + CGContextAddArc(context, CGRectGetMinX(boxRect) + radius, CGRectGetMinY(boxRect) + radius, radius, (float)M_PI, 3 * (float)M_PI / 2, 0); + CGContextClosePath(context); + CGContextFillPath(context); + + UIGraphicsPopContext(); +} + +#pragma mark - KVO + +- (void)registerForKVO { + for (NSString *keyPath in [self observableKeypaths]) { + [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:NULL]; + } +} + +- (void)unregisterFromKVO { + for (NSString *keyPath in [self observableKeypaths]) { + [self removeObserver:self forKeyPath:keyPath]; + } +} + +- (NSArray *)observableKeypaths { + return [NSArray arrayWithObjects:@"mode", @"customView", @"labelText", @"labelFont", @"labelColor", + @"detailsLabelText", @"detailsLabelFont", @"detailsLabelColor", @"progress", @"activityIndicatorColor", nil]; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + if (![NSThread isMainThread]) { + [self performSelectorOnMainThread:@selector(updateUIForKeypath:) withObject:keyPath waitUntilDone:NO]; + } else { + [self updateUIForKeypath:keyPath]; + } +} + +- (void)updateUIForKeypath:(NSString *)keyPath { + if ([keyPath isEqualToString:@"mode"] || [keyPath isEqualToString:@"customView"] || + [keyPath isEqualToString:@"activityIndicatorColor"]) { + [self updateIndicators]; + } else if ([keyPath isEqualToString:@"labelText"]) { + label.text = self.labelText; + } else if ([keyPath isEqualToString:@"labelFont"]) { + label.font = self.labelFont; + } else if ([keyPath isEqualToString:@"labelColor"]) { + label.textColor = self.labelColor; + } else if ([keyPath isEqualToString:@"detailsLabelText"]) { + detailsLabel.text = self.detailsLabelText; + } else if ([keyPath isEqualToString:@"detailsLabelFont"]) { + detailsLabel.font = self.detailsLabelFont; + } else if ([keyPath isEqualToString:@"detailsLabelColor"]) { + detailsLabel.textColor = self.detailsLabelColor; + } else if ([keyPath isEqualToString:@"progress"]) { + if ([indicator respondsToSelector:@selector(setProgress:)]) { + [(id)indicator setValue:@(progress) forKey:@"progress"]; + } + return; + } + [self setNeedsLayout]; + [self setNeedsDisplay]; +} + +#pragma mark - Notifications + +- (void)registerForNotifications { +#if !TARGET_OS_TV + NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; + + [nc addObserver:self selector:@selector(statusBarOrientationDidChange:) + name:UIApplicationDidChangeStatusBarOrientationNotification object:nil]; +#endif +} + +- (void)unregisterFromNotifications { +#if !TARGET_OS_TV + NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; + [nc removeObserver:self name:UIApplicationDidChangeStatusBarOrientationNotification object:nil]; +#endif +} + +#if !TARGET_OS_TV +- (void)statusBarOrientationDidChange:(NSNotification *)notification { + UIView *superview = self.superview; + if (!superview) { + return; + } else { + [self updateForCurrentOrientationAnimated:YES]; + } +} +#endif + +- (void)updateForCurrentOrientationAnimated:(BOOL)animated { + // Stay in sync with the superview in any case + if (self.superview) { + self.bounds = self.superview.bounds; + [self setNeedsDisplay]; + } + + // Not needed on iOS 8+, compile out when the deployment target allows, + // to avoid sharedApplication problems on extension targets +#if __IPHONE_OS_VERSION_MIN_REQUIRED < 80000 + // Only needed pre iOS 7 when added to a window + BOOL iOS8OrLater = kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_8_0; + if (iOS8OrLater || ![self.superview isKindOfClass:[UIWindow class]]) return; + + UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation; + CGFloat radians = 0; + if (UIInterfaceOrientationIsLandscape(orientation)) { + if (orientation == UIInterfaceOrientationLandscapeLeft) { radians = -(CGFloat)M_PI_2; } + else { radians = (CGFloat)M_PI_2; } + // Window coordinates differ! + self.bounds = CGRectMake(0, 0, self.bounds.size.height, self.bounds.size.width); + } else { + if (orientation == UIInterfaceOrientationPortraitUpsideDown) { radians = (CGFloat)M_PI; } + else { radians = 0; } + } + rotationTransform = CGAffineTransformMakeRotation(radians); + + if (animated) { + [UIView beginAnimations:nil context:nil]; + [UIView setAnimationDuration:0.3]; + } + [self setTransform:rotationTransform]; + if (animated) { + [UIView commitAnimations]; + } +#endif +} + +@end + + +@implementation MBRoundProgressView + +#pragma mark - Lifecycle + +- (id)init { + return [self initWithFrame:CGRectMake(0.f, 0.f, 37.f, 37.f)]; +} + +- (id)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self) { + self.backgroundColor = [UIColor clearColor]; + self.opaque = NO; + _progress = 0.f; + _annular = NO; + _progressTintColor = [[UIColor alloc] initWithWhite:1.f alpha:1.f]; + _backgroundTintColor = [[UIColor alloc] initWithWhite:1.f alpha:.1f]; + [self registerForKVO]; + } + return self; +} + +- (void)dealloc { + [self unregisterFromKVO]; +#if !__has_feature(objc_arc) + [_progressTintColor release]; + [_backgroundTintColor release]; + [super dealloc]; +#endif +} + +#pragma mark - Drawing + +- (void)drawRect:(CGRect)rect { + + CGRect allRect = self.bounds; + CGRect circleRect = CGRectInset(allRect, 2.0f, 2.0f); + CGContextRef context = UIGraphicsGetCurrentContext(); + + if (_annular) { + // Draw background + BOOL isPreiOS7 = kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iOS_7_0; + CGFloat lineWidth = isPreiOS7 ? 5.f : 2.f; + UIBezierPath *processBackgroundPath = [UIBezierPath bezierPath]; + processBackgroundPath.lineWidth = lineWidth; + processBackgroundPath.lineCapStyle = kCGLineCapButt; + CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2); + CGFloat radius = (self.bounds.size.width - lineWidth)/2; + CGFloat startAngle = - ((float)M_PI / 2); // 90 degrees + CGFloat endAngle = (2 * (float)M_PI) + startAngle; + [processBackgroundPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES]; + [_backgroundTintColor set]; + [processBackgroundPath stroke]; + // Draw progress + UIBezierPath *processPath = [UIBezierPath bezierPath]; + processPath.lineCapStyle = isPreiOS7 ? kCGLineCapRound : kCGLineCapSquare; + processPath.lineWidth = lineWidth; + endAngle = (self.progress * 2 * (float)M_PI) + startAngle; + [processPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES]; + [_progressTintColor set]; + [processPath stroke]; + } else { + // Draw background + [_progressTintColor setStroke]; + [_backgroundTintColor setFill]; + CGContextSetLineWidth(context, 2.0f); + CGContextFillEllipseInRect(context, circleRect); + CGContextStrokeEllipseInRect(context, circleRect); + // Draw progress + CGPoint center = CGPointMake(allRect.size.width / 2, allRect.size.height / 2); + CGFloat radius = (allRect.size.width - 4) / 2; + CGFloat startAngle = - ((float)M_PI / 2); // 90 degrees + CGFloat endAngle = (self.progress * 2 * (float)M_PI) + startAngle; + [_progressTintColor setFill]; + CGContextMoveToPoint(context, center.x, center.y); + CGContextAddArc(context, center.x, center.y, radius, startAngle, endAngle, 0); + CGContextClosePath(context); + CGContextFillPath(context); + } +} + +#pragma mark - KVO + +- (void)registerForKVO { + for (NSString *keyPath in [self observableKeypaths]) { + [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:NULL]; + } +} + +- (void)unregisterFromKVO { + for (NSString *keyPath in [self observableKeypaths]) { + [self removeObserver:self forKeyPath:keyPath]; + } +} + +- (NSArray *)observableKeypaths { + return [NSArray arrayWithObjects:@"progressTintColor", @"backgroundTintColor", @"progress", @"annular", nil]; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + [self setNeedsDisplay]; +} + +@end + + +@implementation MBBarProgressView + +#pragma mark - Lifecycle + +- (id)init { + return [self initWithFrame:CGRectMake(.0f, .0f, 120.0f, 20.0f)]; +} + +- (id)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (self) { + _progress = 0.f; + _lineColor = [UIColor whiteColor]; + _progressColor = [UIColor whiteColor]; + _progressRemainingColor = [UIColor clearColor]; + self.backgroundColor = [UIColor clearColor]; + self.opaque = NO; + [self registerForKVO]; + } + return self; +} + +- (void)dealloc { + [self unregisterFromKVO]; +#if !__has_feature(objc_arc) + [_lineColor release]; + [_progressColor release]; + [_progressRemainingColor release]; + [super dealloc]; +#endif +} + +#pragma mark - Drawing + +- (void)drawRect:(CGRect)rect { + CGContextRef context = UIGraphicsGetCurrentContext(); + + CGContextSetLineWidth(context, 2); + CGContextSetStrokeColorWithColor(context,[_lineColor CGColor]); + CGContextSetFillColorWithColor(context, [_progressRemainingColor CGColor]); + + // Draw background + float radius = (rect.size.height / 2) - 2; + CGContextMoveToPoint(context, 2, rect.size.height/2); + CGContextAddArcToPoint(context, 2, 2, radius + 2, 2, radius); + CGContextAddLineToPoint(context, rect.size.width - radius - 2, 2); + CGContextAddArcToPoint(context, rect.size.width - 2, 2, rect.size.width - 2, rect.size.height / 2, radius); + CGContextAddArcToPoint(context, rect.size.width - 2, rect.size.height - 2, rect.size.width - radius - 2, rect.size.height - 2, radius); + CGContextAddLineToPoint(context, radius + 2, rect.size.height - 2); + CGContextAddArcToPoint(context, 2, rect.size.height - 2, 2, rect.size.height/2, radius); + CGContextFillPath(context); + + // Draw border + CGContextMoveToPoint(context, 2, rect.size.height/2); + CGContextAddArcToPoint(context, 2, 2, radius + 2, 2, radius); + CGContextAddLineToPoint(context, rect.size.width - radius - 2, 2); + CGContextAddArcToPoint(context, rect.size.width - 2, 2, rect.size.width - 2, rect.size.height / 2, radius); + CGContextAddArcToPoint(context, rect.size.width - 2, rect.size.height - 2, rect.size.width - radius - 2, rect.size.height - 2, radius); + CGContextAddLineToPoint(context, radius + 2, rect.size.height - 2); + CGContextAddArcToPoint(context, 2, rect.size.height - 2, 2, rect.size.height/2, radius); + CGContextStrokePath(context); + + CGContextSetFillColorWithColor(context, [_progressColor CGColor]); + radius = radius - 2; + float amount = self.progress * rect.size.width; + + // Progress in the middle area + if (amount >= radius + 4 && amount <= (rect.size.width - radius - 4)) { + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, 4, radius + 4, 4, radius); + CGContextAddLineToPoint(context, amount, 4); + CGContextAddLineToPoint(context, amount, radius + 4); + + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, rect.size.height - 4, radius + 4, rect.size.height - 4, radius); + CGContextAddLineToPoint(context, amount, rect.size.height - 4); + CGContextAddLineToPoint(context, amount, radius + 4); + + CGContextFillPath(context); + } + + // Progress in the right arc + else if (amount > radius + 4) { + float x = amount - (rect.size.width - radius - 4); + + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, 4, radius + 4, 4, radius); + CGContextAddLineToPoint(context, rect.size.width - radius - 4, 4); + float angle = -acos(x/radius); + if (isnan(angle)) angle = 0; + CGContextAddArc(context, rect.size.width - radius - 4, rect.size.height/2, radius, M_PI, angle, 0); + CGContextAddLineToPoint(context, amount, rect.size.height/2); + + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, rect.size.height - 4, radius + 4, rect.size.height - 4, radius); + CGContextAddLineToPoint(context, rect.size.width - radius - 4, rect.size.height - 4); + angle = acos(x/radius); + if (isnan(angle)) angle = 0; + CGContextAddArc(context, rect.size.width - radius - 4, rect.size.height/2, radius, -M_PI, angle, 1); + CGContextAddLineToPoint(context, amount, rect.size.height/2); + + CGContextFillPath(context); + } + + // Progress is in the left arc + else if (amount < radius + 4 && amount > 0) { + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, 4, radius + 4, 4, radius); + CGContextAddLineToPoint(context, radius + 4, rect.size.height/2); + + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, rect.size.height - 4, radius + 4, rect.size.height - 4, radius); + CGContextAddLineToPoint(context, radius + 4, rect.size.height/2); + + CGContextFillPath(context); + } +} + +#pragma mark - KVO + +- (void)registerForKVO { + for (NSString *keyPath in [self observableKeypaths]) { + [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:NULL]; + } +} + +- (void)unregisterFromKVO { + for (NSString *keyPath in [self observableKeypaths]) { + [self removeObserver:self forKeyPath:keyPath]; + } +} + +- (NSArray *)observableKeypaths { + return [NSArray arrayWithObjects:@"lineColor", @"progressRemainingColor", @"progressColor", @"progress", nil]; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + [self setNeedsDisplay]; +} + +@end diff --git a/Pods/MBProgressHUD/README.mdown b/Pods/MBProgressHUD/README.mdown new file mode 100644 index 0000000..df96756 --- /dev/null +++ b/Pods/MBProgressHUD/README.mdown @@ -0,0 +1,101 @@ +# MBProgressHUD [![Build Status](https://travis-ci.org/matej/MBProgressHUD.svg?branch=master)](https://travis-ci.org/matej/MBProgressHUD) + +MBProgressHUD is an iOS drop-in class that displays a translucent HUD with an indicator and/or labels while work is being done in a background thread. The HUD is meant as a replacement for the undocumented, private UIKit UIProgressHUD with some additional features. + +[![](http://dl.dropbox.com/u/378729/MBProgressHUD/1-thumb.png)](http://dl.dropbox.com/u/378729/MBProgressHUD/1.png) +[![](http://dl.dropbox.com/u/378729/MBProgressHUD/2-thumb.png)](http://dl.dropbox.com/u/378729/MBProgressHUD/2.png) +[![](http://dl.dropbox.com/u/378729/MBProgressHUD/3-thumb.png)](http://dl.dropbox.com/u/378729/MBProgressHUD/3.png) +[![](http://dl.dropbox.com/u/378729/MBProgressHUD/4-thumb.png)](http://dl.dropbox.com/u/378729/MBProgressHUD/4.png) +[![](http://dl.dropbox.com/u/378729/MBProgressHUD/5-thumb.png)](http://dl.dropbox.com/u/378729/MBProgressHUD/5.png) +[![](http://dl.dropbox.com/u/378729/MBProgressHUD/6-thumb.png)](http://dl.dropbox.com/u/378729/MBProgressHUD/6.png) +[![](http://dl.dropbox.com/u/378729/MBProgressHUD/7-thumb.png)](http://dl.dropbox.com/u/378729/MBProgressHUD/7.png) + +## Requirements + +MBProgressHUD works on any iOS version and is compatible with both ARC and non-ARC projects. It depends on the following Apple frameworks, which should already be included with most Xcode templates: + +* Foundation.framework +* UIKit.framework +* CoreGraphics.framework + +You will need the latest developer tools in order to build MBProgressHUD. Old Xcode versions might work, but compatibility will not be explicitly maintained. + +## Adding MBProgressHUD to your project + +### Cocoapods + +[CocoaPods](http://cocoapods.org) is the recommended way to add MBProgressHUD to your project. + +1. Add a pod entry for MBProgressHUD to your Podfile `pod 'MBProgressHUD', '~> 0.9.2'` +2. Install the pod(s) by running `pod install`. +3. Include MBProgressHUD wherever you need it with `#import "MBProgressHUD.h"`. + +### Source files + +Alternatively you can directly add the `MBProgressHUD.h` and `MBProgressHUD.m` source files to your project. + +1. Download the [latest code version](https://github.com/matej/MBProgressHUD/archive/master.zip) or add the repository as a git submodule to your git-tracked project. +2. Open your project in Xcode, then drag and drop `MBProgressHUD.h` and `MBProgressHUD.m` onto your project (use the "Product Navigator view"). Make sure to select Copy items when asked if you extracted the code archive outside of your project. +3. Include MBProgressHUD wherever you need it with `#import "MBProgressHUD.h"`. + +### Static library + +You can also add MBProgressHUD as a static library to your project or workspace. + +1. Download the [latest code version](https://github.com/matej/MBProgressHUD/downloads) or add the repository as a git submodule to your git-tracked project. +2. Open your project in Xcode, then drag and drop `MBProgressHUD.xcodeproj` onto your project or workspace (use the "Product Navigator view"). +3. Select your target and go to the Build phases tab. In the Link Binary With Libraries section select the add button. On the sheet find and add `libMBProgressHUD.a`. You might also need to add `MBProgressHUD` to the Target Dependencies list. +4. Include MBProgressHUD wherever you need it with `#import `. + +## Usage + +The main guideline you need to follow when dealing with MBProgressHUD while running long-running tasks is keeping the main thread work-free, so the UI can be updated promptly. The recommended way of using MBProgressHUD is therefore to set it up on the main thread and then spinning the task, that you want to perform, off onto a new thread. + +```objective-c +[MBProgressHUD showHUDAddedTo:self.view animated:YES]; +dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{ + // Do something... + dispatch_async(dispatch_get_main_queue(), ^{ + [MBProgressHUD hideHUDForView:self.view animated:YES]; + }); +}); +``` + +If you need to configure the HUD you can do this by using the MBProgressHUD reference that showHUDAddedTo:animated: returns. + +```objective-c +MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; +hud.mode = MBProgressHUDModeAnnularDeterminate; +hud.labelText = @"Loading"; +[self doSomethingInBackgroundWithProgressCallback:^(float progress) { + hud.progress = progress; +} completionCallback:^{ + [hud hide:YES]; +}]; +``` + +UI updates should always be done on the main thread. Some MBProgressHUD setters are however considered "thread safe" and can be called from background threads. Those also include `setMode:`, `setCustomView:`, `setLabelText:`, `setLabelFont:`, `setDetailsLabelText:`, `setDetailsLabelFont:` and `setProgress:`. + +If you need to run your long-running task in the main thread, you should perform it with a slight delay, so UIKit will have enough time to update the UI (i.e., draw the HUD) before you block the main thread with your task. + +```objective-c +[MBProgressHUD showHUDAddedTo:self.view animated:YES]; +dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC); +dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ + // Do something... + [MBProgressHUD hideHUDForView:self.view animated:YES]; +}); +``` + +You should be aware that any HUD updates issued inside the above block won't be displayed until the block completes. + +For more examples, including how to use MBProgressHUD with asynchronous operations such as NSURLConnection, take a look at the bundled demo project. Extensive API documentation is provided in the header file (MBProgressHUD.h). + + +## License + +This code is distributed under the terms and conditions of the [MIT license](LICENSE). + +## Change-log + +A brief summary of each MBProgressHUD release can be found on the [wiki](https://github.com/matej/MBProgressHUD/wiki/Change-log). diff --git a/Pods/MJRefresh/LICENSE b/Pods/MJRefresh/LICENSE new file mode 100644 index 0000000..11bf234 --- /dev/null +++ b/Pods/MJRefresh/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2013-2015 MJRefresh (https://github.com/CoderMJLee/MJRefresh) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshAutoFooter.h b/Pods/MJRefresh/MJRefresh/Base/MJRefreshAutoFooter.h new file mode 100644 index 0000000..71ea478 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshAutoFooter.h @@ -0,0 +1,23 @@ +// +// MJRefreshAutoFooter.h +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshFooter.h" + +@interface MJRefreshAutoFooter : MJRefreshFooter +/** 是否自动刷新(默认为YES) */ +@property (assign, nonatomic, getter=isAutomaticallyRefresh) BOOL automaticallyRefresh; + +/** 当底部控件出现多少时就自动刷新(默认为1.0,也就是底部控件完全出现时,才会自动刷新) */ +@property (assign, nonatomic) CGFloat appearencePercentTriggerAutoRefresh MJRefreshDeprecated("请使用triggerAutomaticallyRefreshPercent属性"); + +/** 当底部控件出现多少时就自动刷新(默认为1.0,也就是底部控件完全出现时,才会自动刷新) */ +@property (assign, nonatomic) CGFloat triggerAutomaticallyRefreshPercent; + +/** 是否每一次拖拽只发一次请求 */ +@property (assign, nonatomic, getter=isOnlyRefreshPerDrag) BOOL onlyRefreshPerDrag; +@end diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshAutoFooter.m b/Pods/MJRefresh/MJRefresh/Base/MJRefreshAutoFooter.m new file mode 100644 index 0000000..207df04 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshAutoFooter.m @@ -0,0 +1,154 @@ +// +// MJRefreshAutoFooter.m +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshAutoFooter.h" + +@interface MJRefreshAutoFooter() +/** 一个新的拖拽 */ +@property (assign, nonatomic, getter=isOneNewPan) BOOL oneNewPan; +@end + +@implementation MJRefreshAutoFooter + +#pragma mark - 初始化 +- (void)willMoveToSuperview:(UIView *)newSuperview +{ + [super willMoveToSuperview:newSuperview]; + + if (newSuperview) { // 新的父控件 + if (self.hidden == NO) { + self.scrollView.mj_insetB += self.mj_h; + } + + // 设置位置 + self.mj_y = _scrollView.mj_contentH; + } else { // 被移除了 + if (self.hidden == NO) { + self.scrollView.mj_insetB -= self.mj_h; + } + } +} + +#pragma mark - 过期方法 +- (void)setAppearencePercentTriggerAutoRefresh:(CGFloat)appearencePercentTriggerAutoRefresh +{ + self.triggerAutomaticallyRefreshPercent = appearencePercentTriggerAutoRefresh; +} + +- (CGFloat)appearencePercentTriggerAutoRefresh +{ + return self.triggerAutomaticallyRefreshPercent; +} + +#pragma mark - 实现父类的方法 +- (void)prepare +{ + [super prepare]; + + // 默认底部控件100%出现时才会自动刷新 + self.triggerAutomaticallyRefreshPercent = 1.0; + + // 设置为默认状态 + self.automaticallyRefresh = YES; + + // 默认是当offset达到条件就发送请求(可连续) + self.onlyRefreshPerDrag = NO; +} + +- (void)scrollViewContentSizeDidChange:(NSDictionary *)change +{ + [super scrollViewContentSizeDidChange:change]; + + // 设置位置 + self.mj_y = self.scrollView.mj_contentH; +} + +- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change +{ + [super scrollViewContentOffsetDidChange:change]; + + if (self.state != MJRefreshStateIdle || !self.automaticallyRefresh || self.mj_y == 0) return; + + if (_scrollView.mj_insetT + _scrollView.mj_contentH > _scrollView.mj_h) { // 内容超过一个屏幕 + // 这里的_scrollView.mj_contentH替换掉self.mj_y更为合理 + if (_scrollView.mj_offsetY >= _scrollView.mj_contentH - _scrollView.mj_h + self.mj_h * self.triggerAutomaticallyRefreshPercent + _scrollView.mj_insetB - self.mj_h) { + // 防止手松开时连续调用 + CGPoint old = [change[@"old"] CGPointValue]; + CGPoint new = [change[@"new"] CGPointValue]; + if (new.y <= old.y) return; + + // 当底部刷新控件完全出现时,才刷新 + [self beginRefreshing]; + } + } +} + +- (void)scrollViewPanStateDidChange:(NSDictionary *)change +{ + [super scrollViewPanStateDidChange:change]; + + if (self.state != MJRefreshStateIdle) return; + + UIGestureRecognizerState panState = _scrollView.panGestureRecognizer.state; + if (panState == UIGestureRecognizerStateEnded) {// 手松开 + if (_scrollView.mj_insetT + _scrollView.mj_contentH <= _scrollView.mj_h) { // 不够一个屏幕 + if (_scrollView.mj_offsetY >= - _scrollView.mj_insetT) { // 向上拽 + [self beginRefreshing]; + } + } else { // 超出一个屏幕 + if (_scrollView.mj_offsetY >= _scrollView.mj_contentH + _scrollView.mj_insetB - _scrollView.mj_h) { + [self beginRefreshing]; + } + } + } else if (panState == UIGestureRecognizerStateBegan) { + self.oneNewPan = YES; + } +} + +- (void)beginRefreshing +{ + if (!self.isOneNewPan && self.isOnlyRefreshPerDrag) return; + + [super beginRefreshing]; + + self.oneNewPan = NO; +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + if (state == MJRefreshStateRefreshing) { + [self executeRefreshingCallback]; + } else if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) { + if (MJRefreshStateRefreshing == oldState) { + if (self.endRefreshingCompletionBlock) { + self.endRefreshingCompletionBlock(); + } + } + } +} + +- (void)setHidden:(BOOL)hidden +{ + BOOL lastHidden = self.isHidden; + + [super setHidden:hidden]; + + if (!lastHidden && hidden) { + self.state = MJRefreshStateIdle; + + self.scrollView.mj_insetB -= self.mj_h; + } else if (lastHidden && !hidden) { + self.scrollView.mj_insetB += self.mj_h; + + // 设置位置 + self.mj_y = _scrollView.mj_contentH; + } +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshBackFooter.h b/Pods/MJRefresh/MJRefresh/Base/MJRefreshBackFooter.h new file mode 100644 index 0000000..347083c --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshBackFooter.h @@ -0,0 +1,13 @@ +// +// MJRefreshBackFooter.h +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshFooter.h" + +@interface MJRefreshBackFooter : MJRefreshFooter + +@end diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshBackFooter.m b/Pods/MJRefresh/MJRefresh/Base/MJRefreshBackFooter.m new file mode 100644 index 0000000..71b9579 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshBackFooter.m @@ -0,0 +1,146 @@ +// +// MJRefreshBackFooter.m +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshBackFooter.h" + +@interface MJRefreshBackFooter() +@property (assign, nonatomic) NSInteger lastRefreshCount; +@property (assign, nonatomic) CGFloat lastBottomDelta; +@end + +@implementation MJRefreshBackFooter + +#pragma mark - 初始化 +- (void)willMoveToSuperview:(UIView *)newSuperview +{ + [super willMoveToSuperview:newSuperview]; + + [self scrollViewContentSizeDidChange:nil]; +} + +#pragma mark - 实现父类的方法 +- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change +{ + [super scrollViewContentOffsetDidChange:change]; + + // 如果正在刷新,直接返回 + if (self.state == MJRefreshStateRefreshing) return; + + _scrollViewOriginalInset = self.scrollView.mj_inset; + + // 当前的contentOffset + CGFloat currentOffsetY = self.scrollView.mj_offsetY; + // 尾部控件刚好出现的offsetY + CGFloat happenOffsetY = [self happenOffsetY]; + // 如果是向下滚动到看不见尾部控件,直接返回 + if (currentOffsetY <= happenOffsetY) return; + + CGFloat pullingPercent = (currentOffsetY - happenOffsetY) / self.mj_h; + + // 如果已全部加载,仅设置pullingPercent,然后返回 + if (self.state == MJRefreshStateNoMoreData) { + self.pullingPercent = pullingPercent; + return; + } + + if (self.scrollView.isDragging) { + self.pullingPercent = pullingPercent; + // 普通 和 即将刷新 的临界点 + CGFloat normal2pullingOffsetY = happenOffsetY + self.mj_h; + + if (self.state == MJRefreshStateIdle && currentOffsetY > normal2pullingOffsetY) { + // 转为即将刷新状态 + self.state = MJRefreshStatePulling; + } else if (self.state == MJRefreshStatePulling && currentOffsetY <= normal2pullingOffsetY) { + // 转为普通状态 + self.state = MJRefreshStateIdle; + } + } else if (self.state == MJRefreshStatePulling) {// 即将刷新 && 手松开 + // 开始刷新 + [self beginRefreshing]; + } else if (pullingPercent < 1) { + self.pullingPercent = pullingPercent; + } +} + +- (void)scrollViewContentSizeDidChange:(NSDictionary *)change +{ + [super scrollViewContentSizeDidChange:change]; + + // 内容的高度 + CGFloat contentHeight = self.scrollView.mj_contentH + self.ignoredScrollViewContentInsetBottom; + // 表格的高度 + CGFloat scrollHeight = self.scrollView.mj_h - self.scrollViewOriginalInset.top - self.scrollViewOriginalInset.bottom + self.ignoredScrollViewContentInsetBottom; + // 设置位置和尺寸 + self.mj_y = MAX(contentHeight, scrollHeight); +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 根据状态来设置属性 + if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) { + // 刷新完毕 + if (MJRefreshStateRefreshing == oldState) { + [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{ + self.scrollView.mj_insetB -= self.lastBottomDelta; + + // 自动调整透明度 + if (self.isAutomaticallyChangeAlpha) self.alpha = 0.0; + } completion:^(BOOL finished) { + self.pullingPercent = 0.0; + + if (self.endRefreshingCompletionBlock) { + self.endRefreshingCompletionBlock(); + } + }]; + } + + CGFloat deltaH = [self heightForContentBreakView]; + // 刚刷新完毕 + if (MJRefreshStateRefreshing == oldState && deltaH > 0 && self.scrollView.mj_totalDataCount != self.lastRefreshCount) { + self.scrollView.mj_offsetY = self.scrollView.mj_offsetY; + } + } else if (state == MJRefreshStateRefreshing) { + // 记录刷新前的数量 + self.lastRefreshCount = self.scrollView.mj_totalDataCount; + + [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{ + CGFloat bottom = self.mj_h + self.scrollViewOriginalInset.bottom; + CGFloat deltaH = [self heightForContentBreakView]; + if (deltaH < 0) { // 如果内容高度小于view的高度 + bottom -= deltaH; + } + self.lastBottomDelta = bottom - self.scrollView.mj_insetB; + self.scrollView.mj_insetB = bottom; + self.scrollView.mj_offsetY = [self happenOffsetY] + self.mj_h; + } completion:^(BOOL finished) { + [self executeRefreshingCallback]; + }]; + } +} +#pragma mark - 私有方法 +#pragma mark 获得scrollView的内容 超出 view 的高度 +- (CGFloat)heightForContentBreakView +{ + CGFloat h = self.scrollView.frame.size.height - self.scrollViewOriginalInset.bottom - self.scrollViewOriginalInset.top; + return self.scrollView.contentSize.height - h; +} + +#pragma mark 刚好看到上拉刷新控件时的contentOffset.y +- (CGFloat)happenOffsetY +{ + CGFloat deltaH = [self heightForContentBreakView]; + if (deltaH > 0) { + return deltaH - self.scrollViewOriginalInset.top; + } else { + return - self.scrollViewOriginalInset.top; + } +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshComponent.h b/Pods/MJRefresh/MJRefresh/Base/MJRefreshComponent.h new file mode 100644 index 0000000..46e1068 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshComponent.h @@ -0,0 +1,107 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// 代码地址: http://code4app.com/ios/%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90%E4%B8%8B%E6%8B%89%E4%B8%8A%E6%8B%89%E5%88%B7%E6%96%B0/52326ce26803fabc46000000 +// MJRefreshComponent.h +// MJRefreshExample +// +// Created by MJ Lee on 15/3/4. +// Copyright (c) 2015年 小码哥. All rights reserved. +// 刷新控件的基类 + +#import +#import "MJRefreshConst.h" +#import "UIView+MJExtension.h" +#import "UIScrollView+MJExtension.h" +#import "UIScrollView+MJRefresh.h" +#import "NSBundle+MJRefresh.h" + +/** 刷新控件的状态 */ +typedef NS_ENUM(NSInteger, MJRefreshState) { + /** 普通闲置状态 */ + MJRefreshStateIdle = 1, + /** 松开就可以进行刷新的状态 */ + MJRefreshStatePulling, + /** 正在刷新中的状态 */ + MJRefreshStateRefreshing, + /** 即将刷新的状态 */ + MJRefreshStateWillRefresh, + /** 所有数据加载完毕,没有更多的数据了 */ + MJRefreshStateNoMoreData +}; + +/** 进入刷新状态的回调 */ +typedef void (^MJRefreshComponentRefreshingBlock)(void); +/** 开始刷新后的回调(进入刷新状态后的回调) */ +typedef void (^MJRefreshComponentbeginRefreshingCompletionBlock)(void); +/** 结束刷新后的回调 */ +typedef void (^MJRefreshComponentEndRefreshingCompletionBlock)(void); + +/** 刷新控件的基类 */ +@interface MJRefreshComponent : UIView +{ + /** 记录scrollView刚开始的inset */ + UIEdgeInsets _scrollViewOriginalInset; + /** 父控件 */ + __weak UIScrollView *_scrollView; +} +#pragma mark - 刷新回调 +/** 正在刷新的回调 */ +@property (copy, nonatomic) MJRefreshComponentRefreshingBlock refreshingBlock; +/** 设置回调对象和回调方法 */ +- (void)setRefreshingTarget:(id)target refreshingAction:(SEL)action; + +/** 回调对象 */ +@property (weak, nonatomic) id refreshingTarget; +/** 回调方法 */ +@property (assign, nonatomic) SEL refreshingAction; +/** 触发回调(交给子类去调用) */ +- (void)executeRefreshingCallback; + +#pragma mark - 刷新状态控制 +/** 进入刷新状态 */ +- (void)beginRefreshing; +- (void)beginRefreshingWithCompletionBlock:(void (^)(void))completionBlock; +/** 开始刷新后的回调(进入刷新状态后的回调) */ +@property (copy, nonatomic) MJRefreshComponentbeginRefreshingCompletionBlock beginRefreshingCompletionBlock; +/** 结束刷新的回调 */ +@property (copy, nonatomic) MJRefreshComponentEndRefreshingCompletionBlock endRefreshingCompletionBlock; +/** 结束刷新状态 */ +- (void)endRefreshing; +- (void)endRefreshingWithCompletionBlock:(void (^)(void))completionBlock; +/** 是否正在刷新 */ +@property (assign, nonatomic, readonly, getter=isRefreshing) BOOL refreshing; +//- (BOOL)isRefreshing; +/** 刷新状态 一般交给子类内部实现 */ +@property (assign, nonatomic) MJRefreshState state; + +#pragma mark - 交给子类去访问 +/** 记录scrollView刚开始的inset */ +@property (assign, nonatomic, readonly) UIEdgeInsets scrollViewOriginalInset; +/** 父控件 */ +@property (weak, nonatomic, readonly) UIScrollView *scrollView; + +#pragma mark - 交给子类们去实现 +/** 初始化 */ +- (void)prepare NS_REQUIRES_SUPER; +/** 摆放子控件frame */ +- (void)placeSubviews NS_REQUIRES_SUPER; +/** 当scrollView的contentOffset发生改变的时候调用 */ +- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change NS_REQUIRES_SUPER; +/** 当scrollView的contentSize发生改变的时候调用 */ +- (void)scrollViewContentSizeDidChange:(NSDictionary *)change NS_REQUIRES_SUPER; +/** 当scrollView的拖拽状态发生改变的时候调用 */ +- (void)scrollViewPanStateDidChange:(NSDictionary *)change NS_REQUIRES_SUPER; + + +#pragma mark - 其他 +/** 拉拽的百分比(交给子类重写) */ +@property (assign, nonatomic) CGFloat pullingPercent; +/** 根据拖拽比例自动切换透明度 */ +@property (assign, nonatomic, getter=isAutoChangeAlpha) BOOL autoChangeAlpha MJRefreshDeprecated("请使用automaticallyChangeAlpha属性"); +/** 根据拖拽比例自动切换透明度 */ +@property (assign, nonatomic, getter=isAutomaticallyChangeAlpha) BOOL automaticallyChangeAlpha; +@end + +@interface UILabel(MJRefresh) ++ (instancetype)mj_label; +- (CGFloat)mj_textWith; +@end diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshComponent.m b/Pods/MJRefresh/MJRefresh/Base/MJRefreshComponent.m new file mode 100644 index 0000000..6661ba6 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshComponent.m @@ -0,0 +1,276 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// 代码地址: http://code4app.com/ios/%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90%E4%B8%8B%E6%8B%89%E4%B8%8A%E6%8B%89%E5%88%B7%E6%96%B0/52326ce26803fabc46000000 +// MJRefreshComponent.m +// MJRefreshExample +// +// Created by MJ Lee on 15/3/4. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshComponent.h" +#import "MJRefreshConst.h" + +@interface MJRefreshComponent() +@property (strong, nonatomic) UIPanGestureRecognizer *pan; +@end + +@implementation MJRefreshComponent +#pragma mark - 初始化 +- (instancetype)initWithFrame:(CGRect)frame +{ + if (self = [super initWithFrame:frame]) { + // 准备工作 + [self prepare]; + + // 默认是普通状态 + self.state = MJRefreshStateIdle; + } + return self; +} + +- (void)prepare +{ + // 基本属性 + self.autoresizingMask = UIViewAutoresizingFlexibleWidth; + self.backgroundColor = [UIColor clearColor]; +} + +- (void)layoutSubviews +{ + [self placeSubviews]; + + [super layoutSubviews]; +} + +- (void)placeSubviews{} + +- (void)willMoveToSuperview:(UIView *)newSuperview +{ + [super willMoveToSuperview:newSuperview]; + + // 如果不是UIScrollView,不做任何事情 + if (newSuperview && ![newSuperview isKindOfClass:[UIScrollView class]]) return; + + // 旧的父控件移除监听 + [self removeObservers]; + + if (newSuperview) { // 新的父控件 + // 设置宽度 + self.mj_w = newSuperview.mj_w; + // 设置位置 + self.mj_x = -_scrollView.mj_insetL; + + // 记录UIScrollView + _scrollView = (UIScrollView *)newSuperview; + // 设置永远支持垂直弹簧效果 + _scrollView.alwaysBounceVertical = YES; + // 记录UIScrollView最开始的contentInset + _scrollViewOriginalInset = _scrollView.mj_inset; + + // 添加监听 + [self addObservers]; + } +} + +- (void)drawRect:(CGRect)rect +{ + [super drawRect:rect]; + + if (self.state == MJRefreshStateWillRefresh) { + // 预防view还没显示出来就调用了beginRefreshing + self.state = MJRefreshStateRefreshing; + } +} + +#pragma mark - KVO监听 +- (void)addObservers +{ + NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld; + [self.scrollView addObserver:self forKeyPath:MJRefreshKeyPathContentOffset options:options context:nil]; + [self.scrollView addObserver:self forKeyPath:MJRefreshKeyPathContentSize options:options context:nil]; + self.pan = self.scrollView.panGestureRecognizer; + [self.pan addObserver:self forKeyPath:MJRefreshKeyPathPanState options:options context:nil]; +} + +- (void)removeObservers +{ + [self.superview removeObserver:self forKeyPath:MJRefreshKeyPathContentOffset]; + [self.superview removeObserver:self forKeyPath:MJRefreshKeyPathContentSize]; + [self.pan removeObserver:self forKeyPath:MJRefreshKeyPathPanState]; + self.pan = nil; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context +{ + // 遇到这些情况就直接返回 + if (!self.userInteractionEnabled) return; + + // 这个就算看不见也需要处理 + if ([keyPath isEqualToString:MJRefreshKeyPathContentSize]) { + [self scrollViewContentSizeDidChange:change]; + } + + // 看不见 + if (self.hidden) return; + if ([keyPath isEqualToString:MJRefreshKeyPathContentOffset]) { + [self scrollViewContentOffsetDidChange:change]; + } else if ([keyPath isEqualToString:MJRefreshKeyPathPanState]) { + [self scrollViewPanStateDidChange:change]; + } +} + +- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change{} +- (void)scrollViewContentSizeDidChange:(NSDictionary *)change{} +- (void)scrollViewPanStateDidChange:(NSDictionary *)change{} + +#pragma mark - 公共方法 +#pragma mark 设置回调对象和回调方法 +- (void)setRefreshingTarget:(id)target refreshingAction:(SEL)action +{ + self.refreshingTarget = target; + self.refreshingAction = action; +} + +- (void)setState:(MJRefreshState)state +{ + _state = state; + + // 加入主队列的目的是等setState:方法调用完毕、设置完文字后再去布局子控件 + dispatch_async(dispatch_get_main_queue(), ^{ + [self setNeedsLayout]; + }); +} + +#pragma mark 进入刷新状态 +- (void)beginRefreshing +{ + [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{ + self.alpha = 1.0; + }]; + self.pullingPercent = 1.0; + // 只要正在刷新,就完全显示 + if (self.window) { + self.state = MJRefreshStateRefreshing; + } else { + // 预防正在刷新中时,调用本方法使得header inset回置失败 + if (self.state != MJRefreshStateRefreshing) { + self.state = MJRefreshStateWillRefresh; + // 刷新(预防从另一个控制器回到这个控制器的情况,回来要重新刷新一下) + [self setNeedsDisplay]; + } + } +} + +- (void)beginRefreshingWithCompletionBlock:(void (^)(void))completionBlock +{ + self.beginRefreshingCompletionBlock = completionBlock; + + [self beginRefreshing]; +} + +#pragma mark 结束刷新状态 +- (void)endRefreshing +{ + dispatch_async(dispatch_get_main_queue(), ^{ + self.state = MJRefreshStateIdle; + }); +} + +- (void)endRefreshingWithCompletionBlock:(void (^)(void))completionBlock +{ + self.endRefreshingCompletionBlock = completionBlock; + + [self endRefreshing]; +} + +#pragma mark 是否正在刷新 +- (BOOL)isRefreshing +{ + return self.state == MJRefreshStateRefreshing || self.state == MJRefreshStateWillRefresh; +} + +#pragma mark 自动切换透明度 +- (void)setAutoChangeAlpha:(BOOL)autoChangeAlpha +{ + self.automaticallyChangeAlpha = autoChangeAlpha; +} + +- (BOOL)isAutoChangeAlpha +{ + return self.isAutomaticallyChangeAlpha; +} + +- (void)setAutomaticallyChangeAlpha:(BOOL)automaticallyChangeAlpha +{ + _automaticallyChangeAlpha = automaticallyChangeAlpha; + + if (self.isRefreshing) return; + + if (automaticallyChangeAlpha) { + self.alpha = self.pullingPercent; + } else { + self.alpha = 1.0; + } +} + +#pragma mark 根据拖拽进度设置透明度 +- (void)setPullingPercent:(CGFloat)pullingPercent +{ + _pullingPercent = pullingPercent; + + if (self.isRefreshing) return; + + if (self.isAutomaticallyChangeAlpha) { + self.alpha = pullingPercent; + } +} + +#pragma mark - 内部方法 +- (void)executeRefreshingCallback +{ + dispatch_async(dispatch_get_main_queue(), ^{ + if (self.refreshingBlock) { + self.refreshingBlock(); + } + if ([self.refreshingTarget respondsToSelector:self.refreshingAction]) { + MJRefreshMsgSend(MJRefreshMsgTarget(self.refreshingTarget), self.refreshingAction, self); + } + if (self.beginRefreshingCompletionBlock) { + self.beginRefreshingCompletionBlock(); + } + }); +} +@end + +@implementation UILabel(MJRefresh) ++ (instancetype)mj_label +{ + UILabel *label = [[self alloc] init]; + label.font = MJRefreshLabelFont; + label.textColor = MJRefreshLabelTextColor; + label.autoresizingMask = UIViewAutoresizingFlexibleWidth; + label.textAlignment = NSTextAlignmentCenter; + label.backgroundColor = [UIColor clearColor]; + return label; +} + +- (CGFloat)mj_textWith { + CGFloat stringWidth = 0; + CGSize size = CGSizeMake(MAXFLOAT, MAXFLOAT); + if (self.text.length > 0) { +#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 + stringWidth =[self.text + boundingRectWithSize:size + options:NSStringDrawingUsesLineFragmentOrigin + attributes:@{NSFontAttributeName:self.font} + context:nil].size.width; +#else + + stringWidth = [self.text sizeWithFont:self.font + constrainedToSize:size + lineBreakMode:NSLineBreakByCharWrapping].width; +#endif + } + return stringWidth; +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshFooter.h b/Pods/MJRefresh/MJRefresh/Base/MJRefreshFooter.h new file mode 100644 index 0000000..272f270 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshFooter.h @@ -0,0 +1,30 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// 代码地址: http://code4app.com/ios/%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90%E4%B8%8B%E6%8B%89%E4%B8%8A%E6%8B%89%E5%88%B7%E6%96%B0/52326ce26803fabc46000000 +// MJRefreshFooter.h +// MJRefreshExample +// +// Created by MJ Lee on 15/3/5. +// Copyright (c) 2015年 小码哥. All rights reserved. +// 上拉刷新控件 + +#import "MJRefreshComponent.h" + +@interface MJRefreshFooter : MJRefreshComponent +/** 创建footer */ ++ (instancetype)footerWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock; +/** 创建footer */ ++ (instancetype)footerWithRefreshingTarget:(id)target refreshingAction:(SEL)action; + +/** 提示没有更多的数据 */ +- (void)endRefreshingWithNoMoreData; +- (void)noticeNoMoreData MJRefreshDeprecated("使用endRefreshingWithNoMoreData"); + +/** 重置没有更多的数据(消除没有更多数据的状态) */ +- (void)resetNoMoreData; + +/** 忽略多少scrollView的contentInset的bottom */ +@property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetBottom; + +/** 自动根据有无数据来显示和隐藏(有数据就显示,没有数据隐藏。默认是NO) */ +@property (assign, nonatomic, getter=isAutomaticallyHidden) BOOL automaticallyHidden MJRefreshDeprecated("不建议使用此属性,开发者请自行控制footer的显示和隐藏。基于安全考虑,在未来的某些版本此属性可能作废"); +@end diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshFooter.m b/Pods/MJRefresh/MJRefresh/Base/MJRefreshFooter.m new file mode 100644 index 0000000..efecb5f --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshFooter.m @@ -0,0 +1,84 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// 代码地址: http://code4app.com/ios/%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90%E4%B8%8B%E6%8B%89%E4%B8%8A%E6%8B%89%E5%88%B7%E6%96%B0/52326ce26803fabc46000000 +// MJRefreshFooter.m +// MJRefreshExample +// +// Created by MJ Lee on 15/3/5. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshFooter.h" +#include "UIScrollView+MJRefresh.h" + +@interface MJRefreshFooter() + +@end + +@implementation MJRefreshFooter +#pragma mark - 构造方法 ++ (instancetype)footerWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock +{ + MJRefreshFooter *cmp = [[self alloc] init]; + cmp.refreshingBlock = refreshingBlock; + return cmp; +} ++ (instancetype)footerWithRefreshingTarget:(id)target refreshingAction:(SEL)action +{ + MJRefreshFooter *cmp = [[self alloc] init]; + [cmp setRefreshingTarget:target refreshingAction:action]; + return cmp; +} + +#pragma mark - 重写父类的方法 +- (void)prepare +{ + [super prepare]; + + // 设置自己的高度 + self.mj_h = MJRefreshFooterHeight; + + // 默认不会自动隐藏 + self.automaticallyHidden = NO; +} + +- (void)willMoveToSuperview:(UIView *)newSuperview +{ + [super willMoveToSuperview:newSuperview]; + + if (newSuperview) { + // 监听scrollView数据的变化 + if ([self.scrollView isKindOfClass:[UITableView class]] || [self.scrollView isKindOfClass:[UICollectionView class]]) { + [self.scrollView setMj_reloadDataBlock:^(NSInteger totalDataCount) { + if (self.isAutomaticallyHidden) { + self.hidden = (totalDataCount == 0); + } + }]; + } + } +} + +#pragma mark - 公共方法 +- (void)endRefreshingWithNoMoreData +{ + dispatch_async(dispatch_get_main_queue(), ^{ + self.state = MJRefreshStateNoMoreData; + }); +} + +- (void)noticeNoMoreData +{ + [self endRefreshingWithNoMoreData]; +} + +- (void)resetNoMoreData +{ + dispatch_async(dispatch_get_main_queue(), ^{ + self.state = MJRefreshStateIdle; + }); +} + +- (void)setAutomaticallyHidden:(BOOL)automaticallyHidden +{ + _automaticallyHidden = automaticallyHidden; +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshHeader.h b/Pods/MJRefresh/MJRefresh/Base/MJRefreshHeader.h new file mode 100644 index 0000000..0816024 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshHeader.h @@ -0,0 +1,25 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// 代码地址: http://code4app.com/ios/%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90%E4%B8%8B%E6%8B%89%E4%B8%8A%E6%8B%89%E5%88%B7%E6%96%B0/52326ce26803fabc46000000 +// MJRefreshHeader.h +// MJRefreshExample +// +// Created by MJ Lee on 15/3/4. +// Copyright (c) 2015年 小码哥. All rights reserved. +// 下拉刷新控件:负责监控用户下拉的状态 + +#import "MJRefreshComponent.h" + +@interface MJRefreshHeader : MJRefreshComponent +/** 创建header */ ++ (instancetype)headerWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock; +/** 创建header */ ++ (instancetype)headerWithRefreshingTarget:(id)target refreshingAction:(SEL)action; + +/** 这个key用来存储上一次下拉刷新成功的时间 */ +@property (copy, nonatomic) NSString *lastUpdatedTimeKey; +/** 上一次下拉刷新成功的时间 */ +@property (strong, nonatomic, readonly) NSDate *lastUpdatedTime; + +/** 忽略多少scrollView的contentInset的top */ +@property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetTop; +@end diff --git a/Pods/MJRefresh/MJRefresh/Base/MJRefreshHeader.m b/Pods/MJRefresh/MJRefresh/Base/MJRefreshHeader.m new file mode 100644 index 0000000..7b7249c --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Base/MJRefreshHeader.m @@ -0,0 +1,149 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// 代码地址: http://code4app.com/ios/%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90%E4%B8%8B%E6%8B%89%E4%B8%8A%E6%8B%89%E5%88%B7%E6%96%B0/52326ce26803fabc46000000 +// MJRefreshHeader.m +// MJRefreshExample +// +// Created by MJ Lee on 15/3/4. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshHeader.h" + +@interface MJRefreshHeader() +@property (assign, nonatomic) CGFloat insetTDelta; +@end + +@implementation MJRefreshHeader +#pragma mark - 构造方法 ++ (instancetype)headerWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock +{ + MJRefreshHeader *cmp = [[self alloc] init]; + cmp.refreshingBlock = refreshingBlock; + return cmp; +} ++ (instancetype)headerWithRefreshingTarget:(id)target refreshingAction:(SEL)action +{ + MJRefreshHeader *cmp = [[self alloc] init]; + [cmp setRefreshingTarget:target refreshingAction:action]; + return cmp; +} + +#pragma mark - 覆盖父类的方法 +- (void)prepare +{ + [super prepare]; + + // 设置key + self.lastUpdatedTimeKey = MJRefreshHeaderLastUpdatedTimeKey; + + // 设置高度 + self.mj_h = MJRefreshHeaderHeight; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + // 设置y值(当自己的高度发生改变了,肯定要重新调整Y值,所以放到placeSubviews方法中设置y值) + self.mj_y = - self.mj_h - self.ignoredScrollViewContentInsetTop; +} + +- (void)scrollViewContentOffsetDidChange:(NSDictionary *)change +{ + [super scrollViewContentOffsetDidChange:change]; + + // 在刷新的refreshing状态 + if (self.state == MJRefreshStateRefreshing) { + // 暂时保留 + if (self.window == nil) return; + + // sectionheader停留解决 + CGFloat insetT = - self.scrollView.mj_offsetY > _scrollViewOriginalInset.top ? - self.scrollView.mj_offsetY : _scrollViewOriginalInset.top; + insetT = insetT > self.mj_h + _scrollViewOriginalInset.top ? self.mj_h + _scrollViewOriginalInset.top : insetT; + self.scrollView.mj_insetT = insetT; + + self.insetTDelta = _scrollViewOriginalInset.top - insetT; + return; + } + + // 跳转到下一个控制器时,contentInset可能会变 + _scrollViewOriginalInset = self.scrollView.mj_inset; + + // 当前的contentOffset + CGFloat offsetY = self.scrollView.mj_offsetY; + // 头部控件刚好出现的offsetY + CGFloat happenOffsetY = - self.scrollViewOriginalInset.top; + + // 如果是向上滚动到看不见头部控件,直接返回 + // >= -> > + if (offsetY > happenOffsetY) return; + + // 普通 和 即将刷新 的临界点 + CGFloat normal2pullingOffsetY = happenOffsetY - self.mj_h; + CGFloat pullingPercent = (happenOffsetY - offsetY) / self.mj_h; + + if (self.scrollView.isDragging) { // 如果正在拖拽 + self.pullingPercent = pullingPercent; + if (self.state == MJRefreshStateIdle && offsetY < normal2pullingOffsetY) { + // 转为即将刷新状态 + self.state = MJRefreshStatePulling; + } else if (self.state == MJRefreshStatePulling && offsetY >= normal2pullingOffsetY) { + // 转为普通状态 + self.state = MJRefreshStateIdle; + } + } else if (self.state == MJRefreshStatePulling) {// 即将刷新 && 手松开 + // 开始刷新 + [self beginRefreshing]; + } else if (pullingPercent < 1) { + self.pullingPercent = pullingPercent; + } +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 根据状态做事情 + if (state == MJRefreshStateIdle) { + if (oldState != MJRefreshStateRefreshing) return; + + // 保存刷新时间 + [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:self.lastUpdatedTimeKey]; + [[NSUserDefaults standardUserDefaults] synchronize]; + + // 恢复inset和offset + [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{ + self.scrollView.mj_insetT += self.insetTDelta; + + // 自动调整透明度 + if (self.isAutomaticallyChangeAlpha) self.alpha = 0.0; + } completion:^(BOOL finished) { + self.pullingPercent = 0.0; + + if (self.endRefreshingCompletionBlock) { + self.endRefreshingCompletionBlock(); + } + }]; + } else if (state == MJRefreshStateRefreshing) { + dispatch_async(dispatch_get_main_queue(), ^{ + [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{ + CGFloat top = self.scrollViewOriginalInset.top + self.mj_h; + // 增加滚动区域top + self.scrollView.mj_insetT = top; + // 设置滚动位置 + CGPoint offset = self.scrollView.contentOffset; + offset.y = -top; + [self.scrollView setContentOffset:offset animated:NO]; + } completion:^(BOOL finished) { + [self executeRefreshingCallback]; + }]; + }); + } +} + +#pragma mark - 公共方法 +- (NSDate *)lastUpdatedTime +{ + return [[NSUserDefaults standardUserDefaults] objectForKey:self.lastUpdatedTimeKey]; +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.h b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.h new file mode 100644 index 0000000..6a127e6 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.h @@ -0,0 +1,17 @@ +// +// MJRefreshAutoGifFooter.h +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshAutoStateFooter.h" + +@interface MJRefreshAutoGifFooter : MJRefreshAutoStateFooter +@property (weak, nonatomic, readonly) UIImageView *gifView; + +/** 设置state状态下的动画图片images 动画持续时间duration*/ +- (void)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state; +- (void)setImages:(NSArray *)images forState:(MJRefreshState)state; +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.m b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.m new file mode 100644 index 0000000..2507138 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.m @@ -0,0 +1,116 @@ +// +// MJRefreshAutoGifFooter.m +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshAutoGifFooter.h" + +@interface MJRefreshAutoGifFooter() +{ + __unsafe_unretained UIImageView *_gifView; +} +/** 所有状态对应的动画图片 */ +@property (strong, nonatomic) NSMutableDictionary *stateImages; +/** 所有状态对应的动画时间 */ +@property (strong, nonatomic) NSMutableDictionary *stateDurations; +@end + +@implementation MJRefreshAutoGifFooter +#pragma mark - 懒加载 +- (UIImageView *)gifView +{ + if (!_gifView) { + UIImageView *gifView = [[UIImageView alloc] init]; + [self addSubview:_gifView = gifView]; + } + return _gifView; +} + +- (NSMutableDictionary *)stateImages +{ + if (!_stateImages) { + self.stateImages = [NSMutableDictionary dictionary]; + } + return _stateImages; +} + +- (NSMutableDictionary *)stateDurations +{ + if (!_stateDurations) { + self.stateDurations = [NSMutableDictionary dictionary]; + } + return _stateDurations; +} + +#pragma mark - 公共方法 +- (void)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state +{ + if (images == nil) return; + + self.stateImages[@(state)] = images; + self.stateDurations[@(state)] = @(duration); + + /* 根据图片设置控件的高度 */ + UIImage *image = [images firstObject]; + if (image.size.height > self.mj_h) { + self.mj_h = image.size.height; + } +} + +- (void)setImages:(NSArray *)images forState:(MJRefreshState)state +{ + [self setImages:images duration:images.count * 0.1 forState:state]; +} + +#pragma mark - 实现父类的方法 +- (void)prepare +{ + [super prepare]; + + // 初始化间距 + self.labelLeftInset = 20; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + if (self.gifView.constraints.count) return; + + self.gifView.frame = self.bounds; + if (self.isRefreshingTitleHidden) { + self.gifView.contentMode = UIViewContentModeCenter; + } else { + self.gifView.contentMode = UIViewContentModeRight; + self.gifView.mj_w = self.mj_w * 0.5 - self.labelLeftInset - self.stateLabel.mj_textWith * 0.5; + } +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 根据状态做事情 + if (state == MJRefreshStateRefreshing) { + NSArray *images = self.stateImages[@(state)]; + if (images.count == 0) return; + [self.gifView stopAnimating]; + + self.gifView.hidden = NO; + if (images.count == 1) { // 单张图片 + self.gifView.image = [images lastObject]; + } else { // 多张图片 + self.gifView.animationImages = images; + self.gifView.animationDuration = [self.stateDurations[@(state)] doubleValue]; + [self.gifView startAnimating]; + } + } else if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) { + [self.gifView stopAnimating]; + self.gifView.hidden = YES; + } +} +@end + diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.h b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.h new file mode 100644 index 0000000..5549cff --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.h @@ -0,0 +1,14 @@ +// +// MJRefreshAutoNormalFooter.h +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshAutoStateFooter.h" + +@interface MJRefreshAutoNormalFooter : MJRefreshAutoStateFooter +/** 菊花的样式 */ +@property (assign, nonatomic) UIActivityIndicatorViewStyle activityIndicatorViewStyle; +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.m b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.m new file mode 100644 index 0000000..dae9060 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.m @@ -0,0 +1,69 @@ +// +// MJRefreshAutoNormalFooter.m +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshAutoNormalFooter.h" + +@interface MJRefreshAutoNormalFooter() +@property (weak, nonatomic) UIActivityIndicatorView *loadingView; +@end + +@implementation MJRefreshAutoNormalFooter +#pragma mark - 懒加载子控件 +- (UIActivityIndicatorView *)loadingView +{ + if (!_loadingView) { + UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:self.activityIndicatorViewStyle]; + loadingView.hidesWhenStopped = YES; + [self addSubview:_loadingView = loadingView]; + } + return _loadingView; +} + +- (void)setActivityIndicatorViewStyle:(UIActivityIndicatorViewStyle)activityIndicatorViewStyle +{ + _activityIndicatorViewStyle = activityIndicatorViewStyle; + + self.loadingView = nil; + [self setNeedsLayout]; +} +#pragma mark - 重写父类的方法 +- (void)prepare +{ + [super prepare]; + + self.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + if (self.loadingView.constraints.count) return; + + // 圈圈 + CGFloat loadingCenterX = self.mj_w * 0.5; + if (!self.isRefreshingTitleHidden) { + loadingCenterX -= self.stateLabel.mj_textWith * 0.5 + self.labelLeftInset; + } + CGFloat loadingCenterY = self.mj_h * 0.5; + self.loadingView.center = CGPointMake(loadingCenterX, loadingCenterY); +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 根据状态做事情 + if (state == MJRefreshStateNoMoreData || state == MJRefreshStateIdle) { + [self.loadingView stopAnimating]; + } else if (state == MJRefreshStateRefreshing) { + [self.loadingView startAnimating]; + } +} + +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.h b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.h new file mode 100644 index 0000000..9fe7915 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.h @@ -0,0 +1,22 @@ +// +// MJRefreshAutoStateFooter.h +// MJRefreshExample +// +// Created by MJ Lee on 15/6/13. +// Copyright © 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshAutoFooter.h" + +@interface MJRefreshAutoStateFooter : MJRefreshAutoFooter +/** 文字距离圈圈、箭头的距离 */ +@property (assign, nonatomic) CGFloat labelLeftInset; +/** 显示刷新状态的label */ +@property (weak, nonatomic, readonly) UILabel *stateLabel; + +/** 设置state状态下的文字 */ +- (void)setTitle:(NSString *)title forState:(MJRefreshState)state; + +/** 隐藏刷新状态的文字 */ +@property (assign, nonatomic, getter=isRefreshingTitleHidden) BOOL refreshingTitleHidden; +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.m b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.m new file mode 100644 index 0000000..d16547d --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.m @@ -0,0 +1,92 @@ +// +// MJRefreshAutoStateFooter.m +// MJRefreshExample +// +// Created by MJ Lee on 15/6/13. +// Copyright © 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshAutoStateFooter.h" + +@interface MJRefreshAutoStateFooter() +{ + /** 显示刷新状态的label */ + __unsafe_unretained UILabel *_stateLabel; +} +/** 所有状态对应的文字 */ +@property (strong, nonatomic) NSMutableDictionary *stateTitles; +@end + +@implementation MJRefreshAutoStateFooter +#pragma mark - 懒加载 +- (NSMutableDictionary *)stateTitles +{ + if (!_stateTitles) { + self.stateTitles = [NSMutableDictionary dictionary]; + } + return _stateTitles; +} + +- (UILabel *)stateLabel +{ + if (!_stateLabel) { + [self addSubview:_stateLabel = [UILabel mj_label]]; + } + return _stateLabel; +} + +#pragma mark - 公共方法 +- (void)setTitle:(NSString *)title forState:(MJRefreshState)state +{ + if (title == nil) return; + self.stateTitles[@(state)] = title; + self.stateLabel.text = self.stateTitles[@(self.state)]; +} + +#pragma mark - 私有方法 +- (void)stateLabelClick +{ + if (self.state == MJRefreshStateIdle) { + [self beginRefreshing]; + } +} + +#pragma mark - 重写父类的方法 +- (void)prepare +{ + [super prepare]; + + // 初始化间距 + self.labelLeftInset = MJRefreshLabelLeftInset; + + // 初始化文字 + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshAutoFooterIdleText] forState:MJRefreshStateIdle]; + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshAutoFooterRefreshingText] forState:MJRefreshStateRefreshing]; + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshAutoFooterNoMoreDataText] forState:MJRefreshStateNoMoreData]; + + // 监听label + self.stateLabel.userInteractionEnabled = YES; + [self.stateLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(stateLabelClick)]]; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + if (self.stateLabel.constraints.count) return; + + // 状态标签 + self.stateLabel.frame = self.bounds; +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + if (self.isRefreshingTitleHidden && state == MJRefreshStateRefreshing) { + self.stateLabel.text = nil; + } else { + self.stateLabel.text = self.stateTitles[@(state)]; + } +} +@end \ No newline at end of file diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.h b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.h new file mode 100644 index 0000000..b29af86 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.h @@ -0,0 +1,17 @@ +// +// MJRefreshBackGifFooter.h +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshBackStateFooter.h" + +@interface MJRefreshBackGifFooter : MJRefreshBackStateFooter +@property (weak, nonatomic, readonly) UIImageView *gifView; + +/** 设置state状态下的动画图片images 动画持续时间duration*/ +- (void)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state; +- (void)setImages:(NSArray *)images forState:(MJRefreshState)state; +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.m b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.m new file mode 100644 index 0000000..fa97c72 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.m @@ -0,0 +1,127 @@ +// +// MJRefreshBackGifFooter.m +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshBackGifFooter.h" + +@interface MJRefreshBackGifFooter() +{ + __unsafe_unretained UIImageView *_gifView; +} +/** 所有状态对应的动画图片 */ +@property (strong, nonatomic) NSMutableDictionary *stateImages; +/** 所有状态对应的动画时间 */ +@property (strong, nonatomic) NSMutableDictionary *stateDurations; +@end + +@implementation MJRefreshBackGifFooter +#pragma mark - 懒加载 +- (UIImageView *)gifView +{ + if (!_gifView) { + UIImageView *gifView = [[UIImageView alloc] init]; + [self addSubview:_gifView = gifView]; + } + return _gifView; +} + +- (NSMutableDictionary *)stateImages +{ + if (!_stateImages) { + self.stateImages = [NSMutableDictionary dictionary]; + } + return _stateImages; +} + +- (NSMutableDictionary *)stateDurations +{ + if (!_stateDurations) { + self.stateDurations = [NSMutableDictionary dictionary]; + } + return _stateDurations; +} + +#pragma mark - 公共方法 +- (void)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state +{ + if (images == nil) return; + + self.stateImages[@(state)] = images; + self.stateDurations[@(state)] = @(duration); + + /* 根据图片设置控件的高度 */ + UIImage *image = [images firstObject]; + if (image.size.height > self.mj_h) { + self.mj_h = image.size.height; + } +} + +- (void)setImages:(NSArray *)images forState:(MJRefreshState)state +{ + [self setImages:images duration:images.count * 0.1 forState:state]; +} + +#pragma mark - 实现父类的方法 +- (void)prepare +{ + [super prepare]; + + // 初始化间距 + self.labelLeftInset = 20; +} + +- (void)setPullingPercent:(CGFloat)pullingPercent +{ + [super setPullingPercent:pullingPercent]; + NSArray *images = self.stateImages[@(MJRefreshStateIdle)]; + if (self.state != MJRefreshStateIdle || images.count == 0) return; + [self.gifView stopAnimating]; + NSUInteger index = images.count * pullingPercent; + if (index >= images.count) index = images.count - 1; + self.gifView.image = images[index]; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + if (self.gifView.constraints.count) return; + + self.gifView.frame = self.bounds; + if (self.stateLabel.hidden) { + self.gifView.contentMode = UIViewContentModeCenter; + } else { + self.gifView.contentMode = UIViewContentModeRight; + self.gifView.mj_w = self.mj_w * 0.5 - self.labelLeftInset - self.stateLabel.mj_textWith * 0.5; + } +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 根据状态做事情 + if (state == MJRefreshStatePulling || state == MJRefreshStateRefreshing) { + NSArray *images = self.stateImages[@(state)]; + if (images.count == 0) return; + + self.gifView.hidden = NO; + [self.gifView stopAnimating]; + if (images.count == 1) { // 单张图片 + self.gifView.image = [images lastObject]; + } else { // 多张图片 + self.gifView.animationImages = images; + self.gifView.animationDuration = [self.stateDurations[@(state)] doubleValue]; + [self.gifView startAnimating]; + } + } else if (state == MJRefreshStateIdle) { + self.gifView.hidden = NO; + } else if (state == MJRefreshStateNoMoreData) { + self.gifView.hidden = YES; + } +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.h b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.h new file mode 100644 index 0000000..90e8b77 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.h @@ -0,0 +1,15 @@ +// +// MJRefreshBackNormalFooter.h +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshBackStateFooter.h" + +@interface MJRefreshBackNormalFooter : MJRefreshBackStateFooter +@property (weak, nonatomic, readonly) UIImageView *arrowView; +/** 菊花的样式 */ +@property (assign, nonatomic) UIActivityIndicatorViewStyle activityIndicatorViewStyle; +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.m b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.m new file mode 100644 index 0000000..30e5ecf --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.m @@ -0,0 +1,120 @@ +// +// MJRefreshBackNormalFooter.m +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshBackNormalFooter.h" +#import "NSBundle+MJRefresh.h" + +@interface MJRefreshBackNormalFooter() +{ + __unsafe_unretained UIImageView *_arrowView; +} +@property (weak, nonatomic) UIActivityIndicatorView *loadingView; +@end + +@implementation MJRefreshBackNormalFooter +#pragma mark - 懒加载子控件 +- (UIImageView *)arrowView +{ + if (!_arrowView) { + UIImageView *arrowView = [[UIImageView alloc] initWithImage:[NSBundle mj_arrowImage]]; + [self addSubview:_arrowView = arrowView]; + } + return _arrowView; +} + + +- (UIActivityIndicatorView *)loadingView +{ + if (!_loadingView) { + UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:self.activityIndicatorViewStyle]; + loadingView.hidesWhenStopped = YES; + [self addSubview:_loadingView = loadingView]; + } + return _loadingView; +} + +- (void)setActivityIndicatorViewStyle:(UIActivityIndicatorViewStyle)activityIndicatorViewStyle +{ + _activityIndicatorViewStyle = activityIndicatorViewStyle; + + self.loadingView = nil; + [self setNeedsLayout]; +} +#pragma mark - 重写父类的方法 +- (void)prepare +{ + [super prepare]; + + self.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + // 箭头的中心点 + CGFloat arrowCenterX = self.mj_w * 0.5; + if (!self.stateLabel.hidden) { + arrowCenterX -= self.labelLeftInset + self.stateLabel.mj_textWith * 0.5; + } + CGFloat arrowCenterY = self.mj_h * 0.5; + CGPoint arrowCenter = CGPointMake(arrowCenterX, arrowCenterY); + + // 箭头 + if (self.arrowView.constraints.count == 0) { + self.arrowView.mj_size = self.arrowView.image.size; + self.arrowView.center = arrowCenter; + } + + // 圈圈 + if (self.loadingView.constraints.count == 0) { + self.loadingView.center = arrowCenter; + } + + self.arrowView.tintColor = self.stateLabel.textColor; +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 根据状态做事情 + if (state == MJRefreshStateIdle) { + if (oldState == MJRefreshStateRefreshing) { + self.arrowView.transform = CGAffineTransformMakeRotation(0.000001 - M_PI); + [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{ + self.loadingView.alpha = 0.0; + } completion:^(BOOL finished) { + self.loadingView.alpha = 1.0; + [self.loadingView stopAnimating]; + + self.arrowView.hidden = NO; + }]; + } else { + self.arrowView.hidden = NO; + [self.loadingView stopAnimating]; + [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{ + self.arrowView.transform = CGAffineTransformMakeRotation(0.000001 - M_PI); + }]; + } + } else if (state == MJRefreshStatePulling) { + self.arrowView.hidden = NO; + [self.loadingView stopAnimating]; + [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{ + self.arrowView.transform = CGAffineTransformIdentity; + }]; + } else if (state == MJRefreshStateRefreshing) { + self.arrowView.hidden = YES; + [self.loadingView startAnimating]; + } else if (state == MJRefreshStateNoMoreData) { + self.arrowView.hidden = YES; + [self.loadingView stopAnimating]; + } +} + +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.h b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.h new file mode 100644 index 0000000..99b1483 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.h @@ -0,0 +1,21 @@ +// +// MJRefreshBackStateFooter.h +// MJRefreshExample +// +// Created by MJ Lee on 15/6/13. +// Copyright © 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshBackFooter.h" + +@interface MJRefreshBackStateFooter : MJRefreshBackFooter +/** 文字距离圈圈、箭头的距离 */ +@property (assign, nonatomic) CGFloat labelLeftInset; +/** 显示刷新状态的label */ +@property (weak, nonatomic, readonly) UILabel *stateLabel; +/** 设置state状态下的文字 */ +- (void)setTitle:(NSString *)title forState:(MJRefreshState)state; + +/** 获取state状态下的title */ +- (NSString *)titleForState:(MJRefreshState)state; +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.m b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.m new file mode 100644 index 0000000..cc784d0 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.m @@ -0,0 +1,82 @@ +// +// MJRefreshBackStateFooter.m +// MJRefreshExample +// +// Created by MJ Lee on 15/6/13. +// Copyright © 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshBackStateFooter.h" + +@interface MJRefreshBackStateFooter() +{ + /** 显示刷新状态的label */ + __unsafe_unretained UILabel *_stateLabel; +} +/** 所有状态对应的文字 */ +@property (strong, nonatomic) NSMutableDictionary *stateTitles; +@end + +@implementation MJRefreshBackStateFooter +#pragma mark - 懒加载 +- (NSMutableDictionary *)stateTitles +{ + if (!_stateTitles) { + self.stateTitles = [NSMutableDictionary dictionary]; + } + return _stateTitles; +} + +- (UILabel *)stateLabel +{ + if (!_stateLabel) { + [self addSubview:_stateLabel = [UILabel mj_label]]; + } + return _stateLabel; +} + +#pragma mark - 公共方法 +- (void)setTitle:(NSString *)title forState:(MJRefreshState)state +{ + if (title == nil) return; + self.stateTitles[@(state)] = title; + self.stateLabel.text = self.stateTitles[@(self.state)]; +} + +- (NSString *)titleForState:(MJRefreshState)state { + return self.stateTitles[@(state)]; +} + +#pragma mark - 重写父类的方法 +- (void)prepare +{ + [super prepare]; + + // 初始化间距 + self.labelLeftInset = MJRefreshLabelLeftInset; + + // 初始化文字 + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshBackFooterIdleText] forState:MJRefreshStateIdle]; + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshBackFooterPullingText] forState:MJRefreshStatePulling]; + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshBackFooterRefreshingText] forState:MJRefreshStateRefreshing]; + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshBackFooterNoMoreDataText] forState:MJRefreshStateNoMoreData]; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + if (self.stateLabel.constraints.count) return; + + // 状态标签 + self.stateLabel.frame = self.bounds; +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 设置状态文字 + self.stateLabel.text = self.stateTitles[@(state)]; +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshGifHeader.h b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshGifHeader.h new file mode 100644 index 0000000..ce3ed42 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshGifHeader.h @@ -0,0 +1,17 @@ +// +// MJRefreshGifHeader.h +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshStateHeader.h" + +@interface MJRefreshGifHeader : MJRefreshStateHeader +@property (weak, nonatomic, readonly) UIImageView *gifView; + +/** 设置state状态下的动画图片images 动画持续时间duration*/ +- (void)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state; +- (void)setImages:(NSArray *)images forState:(MJRefreshState)state; +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshGifHeader.m b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshGifHeader.m new file mode 100644 index 0000000..f8bcc9b --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshGifHeader.m @@ -0,0 +1,133 @@ +// +// MJRefreshGifHeader.m +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshGifHeader.h" + +@interface MJRefreshGifHeader() +{ + __unsafe_unretained UIImageView *_gifView; +} +/** 所有状态对应的动画图片 */ +@property (strong, nonatomic) NSMutableDictionary *stateImages; +/** 所有状态对应的动画时间 */ +@property (strong, nonatomic) NSMutableDictionary *stateDurations; +@end + +@implementation MJRefreshGifHeader +#pragma mark - 懒加载 +- (UIImageView *)gifView +{ + if (!_gifView) { + UIImageView *gifView = [[UIImageView alloc] init]; + [self addSubview:_gifView = gifView]; + } + return _gifView; +} + +- (NSMutableDictionary *)stateImages +{ + if (!_stateImages) { + self.stateImages = [NSMutableDictionary dictionary]; + } + return _stateImages; +} + +- (NSMutableDictionary *)stateDurations +{ + if (!_stateDurations) { + self.stateDurations = [NSMutableDictionary dictionary]; + } + return _stateDurations; +} + +#pragma mark - 公共方法 +- (void)setImages:(NSArray *)images duration:(NSTimeInterval)duration forState:(MJRefreshState)state +{ + if (images == nil) return; + + self.stateImages[@(state)] = images; + self.stateDurations[@(state)] = @(duration); + + /* 根据图片设置控件的高度 */ + UIImage *image = [images firstObject]; + if (image.size.height > self.mj_h) { + self.mj_h = image.size.height; + } +} + +- (void)setImages:(NSArray *)images forState:(MJRefreshState)state +{ + [self setImages:images duration:images.count * 0.1 forState:state]; +} + +#pragma mark - 实现父类的方法 +- (void)prepare +{ + [super prepare]; + + // 初始化间距 + self.labelLeftInset = 20; +} + +- (void)setPullingPercent:(CGFloat)pullingPercent +{ + [super setPullingPercent:pullingPercent]; + NSArray *images = self.stateImages[@(MJRefreshStateIdle)]; + if (self.state != MJRefreshStateIdle || images.count == 0) return; + // 停止动画 + [self.gifView stopAnimating]; + // 设置当前需要显示的图片 + NSUInteger index = images.count * pullingPercent; + if (index >= images.count) index = images.count - 1; + self.gifView.image = images[index]; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + if (self.gifView.constraints.count) return; + + self.gifView.frame = self.bounds; + if (self.stateLabel.hidden && self.lastUpdatedTimeLabel.hidden) { + self.gifView.contentMode = UIViewContentModeCenter; + } else { + self.gifView.contentMode = UIViewContentModeRight; + + CGFloat stateWidth = self.stateLabel.mj_textWith; + CGFloat timeWidth = 0.0; + if (!self.lastUpdatedTimeLabel.hidden) { + timeWidth = self.lastUpdatedTimeLabel.mj_textWith; + } + CGFloat textWidth = MAX(stateWidth, timeWidth); + self.gifView.mj_w = self.mj_w * 0.5 - textWidth * 0.5 - self.labelLeftInset; + } +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 根据状态做事情 + if (state == MJRefreshStatePulling || state == MJRefreshStateRefreshing) { + NSArray *images = self.stateImages[@(state)]; + if (images.count == 0) return; + + [self.gifView stopAnimating]; + if (images.count == 1) { // 单张图片 + self.gifView.image = [images lastObject]; + } else { // 多张图片 + self.gifView.animationImages = images; + self.gifView.animationDuration = [self.stateDurations[@(state)] doubleValue]; + [self.gifView startAnimating]; + } + } else if (state == MJRefreshStateIdle) { + [self.gifView stopAnimating]; + } +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshNormalHeader.h b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshNormalHeader.h new file mode 100644 index 0000000..547d05e --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshNormalHeader.h @@ -0,0 +1,15 @@ +// +// MJRefreshNormalHeader.h +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshStateHeader.h" + +@interface MJRefreshNormalHeader : MJRefreshStateHeader +@property (weak, nonatomic, readonly) UIImageView *arrowView; +/** 菊花的样式 */ +@property (assign, nonatomic) UIActivityIndicatorViewStyle activityIndicatorViewStyle; +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshNormalHeader.m b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshNormalHeader.m new file mode 100644 index 0000000..32d8de7 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshNormalHeader.m @@ -0,0 +1,127 @@ +// +// MJRefreshNormalHeader.m +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshNormalHeader.h" +#import "NSBundle+MJRefresh.h" + +@interface MJRefreshNormalHeader() +{ + __unsafe_unretained UIImageView *_arrowView; +} +@property (weak, nonatomic) UIActivityIndicatorView *loadingView; +@end + +@implementation MJRefreshNormalHeader +#pragma mark - 懒加载子控件 +- (UIImageView *)arrowView +{ + if (!_arrowView) { + UIImageView *arrowView = [[UIImageView alloc] initWithImage:[NSBundle mj_arrowImage]]; + [self addSubview:_arrowView = arrowView]; + } + return _arrowView; +} + +- (UIActivityIndicatorView *)loadingView +{ + if (!_loadingView) { + UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:self.activityIndicatorViewStyle]; + loadingView.hidesWhenStopped = YES; + [self addSubview:_loadingView = loadingView]; + } + return _loadingView; +} + +#pragma mark - 公共方法 +- (void)setActivityIndicatorViewStyle:(UIActivityIndicatorViewStyle)activityIndicatorViewStyle +{ + _activityIndicatorViewStyle = activityIndicatorViewStyle; + + self.loadingView = nil; + [self setNeedsLayout]; +} + +#pragma mark - 重写父类的方法 +- (void)prepare +{ + [super prepare]; + + self.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + // 箭头的中心点 + CGFloat arrowCenterX = self.mj_w * 0.5; + if (!self.stateLabel.hidden) { + CGFloat stateWidth = self.stateLabel.mj_textWith; + CGFloat timeWidth = 0.0; + if (!self.lastUpdatedTimeLabel.hidden) { + timeWidth = self.lastUpdatedTimeLabel.mj_textWith; + } + CGFloat textWidth = MAX(stateWidth, timeWidth); + arrowCenterX -= textWidth / 2 + self.labelLeftInset; + } + CGFloat arrowCenterY = self.mj_h * 0.5; + CGPoint arrowCenter = CGPointMake(arrowCenterX, arrowCenterY); + + // 箭头 + if (self.arrowView.constraints.count == 0) { + self.arrowView.mj_size = self.arrowView.image.size; + self.arrowView.center = arrowCenter; + } + + // 圈圈 + if (self.loadingView.constraints.count == 0) { + self.loadingView.center = arrowCenter; + } + + self.arrowView.tintColor = self.stateLabel.textColor; +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 根据状态做事情 + if (state == MJRefreshStateIdle) { + if (oldState == MJRefreshStateRefreshing) { + self.arrowView.transform = CGAffineTransformIdentity; + + [UIView animateWithDuration:MJRefreshSlowAnimationDuration animations:^{ + self.loadingView.alpha = 0.0; + } completion:^(BOOL finished) { + // 如果执行完动画发现不是idle状态,就直接返回,进入其他状态 + if (self.state != MJRefreshStateIdle) return; + + self.loadingView.alpha = 1.0; + [self.loadingView stopAnimating]; + self.arrowView.hidden = NO; + }]; + } else { + [self.loadingView stopAnimating]; + self.arrowView.hidden = NO; + [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{ + self.arrowView.transform = CGAffineTransformIdentity; + }]; + } + } else if (state == MJRefreshStatePulling) { + [self.loadingView stopAnimating]; + self.arrowView.hidden = NO; + [UIView animateWithDuration:MJRefreshFastAnimationDuration animations:^{ + self.arrowView.transform = CGAffineTransformMakeRotation(0.000001 - M_PI); + }]; + } else if (state == MJRefreshStateRefreshing) { + self.loadingView.alpha = 1.0; // 防止refreshing -> idle的动画完毕动作没有被执行 + [self.loadingView startAnimating]; + self.arrowView.hidden = YES; + } +} +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshStateHeader.h b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshStateHeader.h new file mode 100644 index 0000000..1f3dbc4 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshStateHeader.h @@ -0,0 +1,25 @@ +// +// MJRefreshStateHeader.h +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshHeader.h" + +@interface MJRefreshStateHeader : MJRefreshHeader +#pragma mark - 刷新时间相关 +/** 利用这个block来决定显示的更新时间文字 */ +@property (copy, nonatomic) NSString *(^lastUpdatedTimeText)(NSDate *lastUpdatedTime); +/** 显示上一次刷新时间的label */ +@property (weak, nonatomic, readonly) UILabel *lastUpdatedTimeLabel; + +#pragma mark - 状态相关 +/** 文字距离圈圈、箭头的距离 */ +@property (assign, nonatomic) CGFloat labelLeftInset; +/** 显示刷新状态的label */ +@property (weak, nonatomic, readonly) UILabel *stateLabel; +/** 设置state状态下的文字 */ +- (void)setTitle:(NSString *)title forState:(MJRefreshState)state; +@end diff --git a/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshStateHeader.m b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshStateHeader.m new file mode 100644 index 0000000..ca78b52 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/Custom/Header/MJRefreshStateHeader.m @@ -0,0 +1,167 @@ +// +// MJRefreshStateHeader.m +// MJRefreshExample +// +// Created by MJ Lee on 15/4/24. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "MJRefreshStateHeader.h" + +@interface MJRefreshStateHeader() +{ + /** 显示上一次刷新时间的label */ + __unsafe_unretained UILabel *_lastUpdatedTimeLabel; + /** 显示刷新状态的label */ + __unsafe_unretained UILabel *_stateLabel; +} +/** 所有状态对应的文字 */ +@property (strong, nonatomic) NSMutableDictionary *stateTitles; +@end + +@implementation MJRefreshStateHeader +#pragma mark - 懒加载 +- (NSMutableDictionary *)stateTitles +{ + if (!_stateTitles) { + self.stateTitles = [NSMutableDictionary dictionary]; + } + return _stateTitles; +} + +- (UILabel *)stateLabel +{ + if (!_stateLabel) { + [self addSubview:_stateLabel = [UILabel mj_label]]; + } + return _stateLabel; +} + +- (UILabel *)lastUpdatedTimeLabel +{ + if (!_lastUpdatedTimeLabel) { + [self addSubview:_lastUpdatedTimeLabel = [UILabel mj_label]]; + } + return _lastUpdatedTimeLabel; +} + +#pragma mark - 公共方法 +- (void)setTitle:(NSString *)title forState:(MJRefreshState)state +{ + if (title == nil) return; + self.stateTitles[@(state)] = title; + self.stateLabel.text = self.stateTitles[@(self.state)]; +} + +#pragma mark - 日历获取在9.x之后的系统使用currentCalendar会出异常。在8.0之后使用系统新API。 +- (NSCalendar *)currentCalendar { + if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) { + return [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]; + } + return [NSCalendar currentCalendar]; +} + +#pragma mark key的处理 +- (void)setLastUpdatedTimeKey:(NSString *)lastUpdatedTimeKey +{ + [super setLastUpdatedTimeKey:lastUpdatedTimeKey]; + + // 如果label隐藏了,就不用再处理 + if (self.lastUpdatedTimeLabel.hidden) return; + + NSDate *lastUpdatedTime = [[NSUserDefaults standardUserDefaults] objectForKey:lastUpdatedTimeKey]; + + // 如果有block + if (self.lastUpdatedTimeText) { + self.lastUpdatedTimeLabel.text = self.lastUpdatedTimeText(lastUpdatedTime); + return; + } + + if (lastUpdatedTime) { + // 1.获得年月日 + NSCalendar *calendar = [self currentCalendar]; + NSUInteger unitFlags = NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour |NSCalendarUnitMinute; + NSDateComponents *cmp1 = [calendar components:unitFlags fromDate:lastUpdatedTime]; + NSDateComponents *cmp2 = [calendar components:unitFlags fromDate:[NSDate date]]; + + // 2.格式化日期 + NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; + BOOL isToday = NO; + if ([cmp1 day] == [cmp2 day]) { // 今天 + formatter.dateFormat = @" HH:mm"; + isToday = YES; + } else if ([cmp1 year] == [cmp2 year]) { // 今年 + formatter.dateFormat = @"MM-dd HH:mm"; + } else { + formatter.dateFormat = @"yyyy-MM-dd HH:mm"; + } + NSString *time = [formatter stringFromDate:lastUpdatedTime]; + + // 3.显示日期 + self.lastUpdatedTimeLabel.text = [NSString stringWithFormat:@"%@%@%@", + [NSBundle mj_localizedStringForKey:MJRefreshHeaderLastTimeText], + isToday ? [NSBundle mj_localizedStringForKey:MJRefreshHeaderDateTodayText] : @"", + time]; + } else { + self.lastUpdatedTimeLabel.text = [NSString stringWithFormat:@"%@%@", + [NSBundle mj_localizedStringForKey:MJRefreshHeaderLastTimeText], + [NSBundle mj_localizedStringForKey:MJRefreshHeaderNoneLastDateText]]; + } +} + +#pragma mark - 覆盖父类的方法 +- (void)prepare +{ + [super prepare]; + + // 初始化间距 + self.labelLeftInset = MJRefreshLabelLeftInset; + + // 初始化文字 + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshHeaderIdleText] forState:MJRefreshStateIdle]; + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshHeaderPullingText] forState:MJRefreshStatePulling]; + [self setTitle:[NSBundle mj_localizedStringForKey:MJRefreshHeaderRefreshingText] forState:MJRefreshStateRefreshing]; +} + +- (void)placeSubviews +{ + [super placeSubviews]; + + if (self.stateLabel.hidden) return; + + BOOL noConstrainsOnStatusLabel = self.stateLabel.constraints.count == 0; + + if (self.lastUpdatedTimeLabel.hidden) { + // 状态 + if (noConstrainsOnStatusLabel) self.stateLabel.frame = self.bounds; + } else { + CGFloat stateLabelH = self.mj_h * 0.5; + // 状态 + if (noConstrainsOnStatusLabel) { + self.stateLabel.mj_x = 0; + self.stateLabel.mj_y = 0; + self.stateLabel.mj_w = self.mj_w; + self.stateLabel.mj_h = stateLabelH; + } + + // 更新时间 + if (self.lastUpdatedTimeLabel.constraints.count == 0) { + self.lastUpdatedTimeLabel.mj_x = 0; + self.lastUpdatedTimeLabel.mj_y = stateLabelH; + self.lastUpdatedTimeLabel.mj_w = self.mj_w; + self.lastUpdatedTimeLabel.mj_h = self.mj_h - self.lastUpdatedTimeLabel.mj_y; + } + } +} + +- (void)setState:(MJRefreshState)state +{ + MJRefreshCheckState + + // 设置状态文字 + self.stateLabel.text = self.stateTitles[@(state)]; + + // 重新设置key(重新显示时间) + self.lastUpdatedTimeKey = self.lastUpdatedTimeKey; +} +@end diff --git a/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/arrow@2x.png b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/arrow@2x.png new file mode 100755 index 0000000..b1078de Binary files /dev/null and b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/arrow@2x.png differ diff --git a/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/en.lproj/Localizable.strings b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/en.lproj/Localizable.strings new file mode 100644 index 0000000..a75f6b1 Binary files /dev/null and b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/en.lproj/Localizable.strings differ diff --git a/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/zh-Hans.lproj/Localizable.strings b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/zh-Hans.lproj/Localizable.strings new file mode 100644 index 0000000..0a36d7e Binary files /dev/null and b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/zh-Hans.lproj/Localizable.strings differ diff --git a/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/zh-Hant.lproj/Localizable.strings b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/zh-Hant.lproj/Localizable.strings new file mode 100644 index 0000000..7924bba --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/MJRefresh.bundle/zh-Hant.lproj/Localizable.strings @@ -0,0 +1,16 @@ +"MJRefreshHeaderIdleText" = "下拉可以刷新"; +"MJRefreshHeaderPullingText" = "鬆開立即刷新"; +"MJRefreshHeaderRefreshingText" = "正在刷新數據中..."; + +"MJRefreshAutoFooterIdleText" = "點擊或上拉加載更多"; +"MJRefreshAutoFooterRefreshingText" = "正在加載更多的數據..."; +"MJRefreshAutoFooterNoMoreDataText" = "已經全部加載完畢"; + +"MJRefreshBackFooterIdleText" = "上拉可以加載更多"; +"MJRefreshBackFooterPullingText" = "鬆開立即加載更多"; +"MJRefreshBackFooterRefreshingText" = "正在加載更多的數據..."; +"MJRefreshBackFooterNoMoreDataText" = "已經全部加載完畢"; + +"MJRefreshHeaderLastTimeText" = "最後更新:"; +"MJRefreshHeaderDateTodayText" = "今天"; +"MJRefreshHeaderNoneLastDateText" = "無記錄"; diff --git a/Pods/MJRefresh/MJRefresh/MJRefresh.h b/Pods/MJRefresh/MJRefresh/MJRefresh.h new file mode 100644 index 0000000..196e6ec --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/MJRefresh.h @@ -0,0 +1,14 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// 代码地址: http://code4app.com/ios/%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90%E4%B8%8B%E6%8B%89%E4%B8%8A%E6%8B%89%E5%88%B7%E6%96%B0/52326ce26803fabc46000000 + +#import "UIScrollView+MJRefresh.h" +#import "UIScrollView+MJExtension.h" +#import "UIView+MJExtension.h" + +#import "MJRefreshNormalHeader.h" +#import "MJRefreshGifHeader.h" + +#import "MJRefreshBackNormalFooter.h" +#import "MJRefreshBackGifFooter.h" +#import "MJRefreshAutoNormalFooter.h" +#import "MJRefreshAutoGifFooter.h" \ No newline at end of file diff --git a/Pods/MJRefresh/MJRefresh/MJRefreshConst.h b/Pods/MJRefresh/MJRefresh/MJRefreshConst.h new file mode 100644 index 0000000..4a72021 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/MJRefreshConst.h @@ -0,0 +1,67 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// 代码地址: http://code4app.com/ios/%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90%E4%B8%8B%E6%8B%89%E4%B8%8A%E6%8B%89%E5%88%B7%E6%96%B0/52326ce26803fabc46000000 +#import +#import + +// 弱引用 +#define MJWeakSelf __weak typeof(self) weakSelf = self; + +// 日志输出 +#ifdef DEBUG +#define MJRefreshLog(...) NSLog(__VA_ARGS__) +#else +#define MJRefreshLog(...) +#endif + +// 过期提醒 +#define MJRefreshDeprecated(instead) NS_DEPRECATED(2_0, 2_0, 2_0, 2_0, instead) + +// 运行时objc_msgSend +#define MJRefreshMsgSend(...) ((void (*)(void *, SEL, UIView *))objc_msgSend)(__VA_ARGS__) +#define MJRefreshMsgTarget(target) (__bridge void *)(target) + +// RGB颜色 +#define MJRefreshColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0] + +// 文字颜色 +#define MJRefreshLabelTextColor MJRefreshColor(90, 90, 90) + +// 字体大小 +#define MJRefreshLabelFont [UIFont boldSystemFontOfSize:14] + +// 常量 +UIKIT_EXTERN const CGFloat MJRefreshLabelLeftInset; +UIKIT_EXTERN const CGFloat MJRefreshHeaderHeight; +UIKIT_EXTERN const CGFloat MJRefreshFooterHeight; +UIKIT_EXTERN const CGFloat MJRefreshFastAnimationDuration; +UIKIT_EXTERN const CGFloat MJRefreshSlowAnimationDuration; + +UIKIT_EXTERN NSString *const MJRefreshKeyPathContentOffset; +UIKIT_EXTERN NSString *const MJRefreshKeyPathContentSize; +UIKIT_EXTERN NSString *const MJRefreshKeyPathContentInset; +UIKIT_EXTERN NSString *const MJRefreshKeyPathPanState; + +UIKIT_EXTERN NSString *const MJRefreshHeaderLastUpdatedTimeKey; + +UIKIT_EXTERN NSString *const MJRefreshHeaderIdleText; +UIKIT_EXTERN NSString *const MJRefreshHeaderPullingText; +UIKIT_EXTERN NSString *const MJRefreshHeaderRefreshingText; + +UIKIT_EXTERN NSString *const MJRefreshAutoFooterIdleText; +UIKIT_EXTERN NSString *const MJRefreshAutoFooterRefreshingText; +UIKIT_EXTERN NSString *const MJRefreshAutoFooterNoMoreDataText; + +UIKIT_EXTERN NSString *const MJRefreshBackFooterIdleText; +UIKIT_EXTERN NSString *const MJRefreshBackFooterPullingText; +UIKIT_EXTERN NSString *const MJRefreshBackFooterRefreshingText; +UIKIT_EXTERN NSString *const MJRefreshBackFooterNoMoreDataText; + +UIKIT_EXTERN NSString *const MJRefreshHeaderLastTimeText; +UIKIT_EXTERN NSString *const MJRefreshHeaderDateTodayText; +UIKIT_EXTERN NSString *const MJRefreshHeaderNoneLastDateText; + +// 状态检查 +#define MJRefreshCheckState \ +MJRefreshState oldState = self.state; \ +if (state == oldState) return; \ +[super setState:state]; diff --git a/Pods/MJRefresh/MJRefresh/MJRefreshConst.m b/Pods/MJRefresh/MJRefresh/MJRefreshConst.m new file mode 100644 index 0000000..7c0733e --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/MJRefreshConst.m @@ -0,0 +1,33 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// 代码地址: http://code4app.com/ios/%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90%E4%B8%8B%E6%8B%89%E4%B8%8A%E6%8B%89%E5%88%B7%E6%96%B0/52326ce26803fabc46000000 +#import + +const CGFloat MJRefreshLabelLeftInset = 25; +const CGFloat MJRefreshHeaderHeight = 54.0; +const CGFloat MJRefreshFooterHeight = 44.0; +const CGFloat MJRefreshFastAnimationDuration = 0.25; +const CGFloat MJRefreshSlowAnimationDuration = 0.4; + +NSString *const MJRefreshKeyPathContentOffset = @"contentOffset"; +NSString *const MJRefreshKeyPathContentInset = @"contentInset"; +NSString *const MJRefreshKeyPathContentSize = @"contentSize"; +NSString *const MJRefreshKeyPathPanState = @"state"; + +NSString *const MJRefreshHeaderLastUpdatedTimeKey = @"MJRefreshHeaderLastUpdatedTimeKey"; + +NSString *const MJRefreshHeaderIdleText = @"MJRefreshHeaderIdleText"; +NSString *const MJRefreshHeaderPullingText = @"MJRefreshHeaderPullingText"; +NSString *const MJRefreshHeaderRefreshingText = @"MJRefreshHeaderRefreshingText"; + +NSString *const MJRefreshAutoFooterIdleText = @"MJRefreshAutoFooterIdleText"; +NSString *const MJRefreshAutoFooterRefreshingText = @"MJRefreshAutoFooterRefreshingText"; +NSString *const MJRefreshAutoFooterNoMoreDataText = @"MJRefreshAutoFooterNoMoreDataText"; + +NSString *const MJRefreshBackFooterIdleText = @"MJRefreshBackFooterIdleText"; +NSString *const MJRefreshBackFooterPullingText = @"MJRefreshBackFooterPullingText"; +NSString *const MJRefreshBackFooterRefreshingText = @"MJRefreshBackFooterRefreshingText"; +NSString *const MJRefreshBackFooterNoMoreDataText = @"MJRefreshBackFooterNoMoreDataText"; + +NSString *const MJRefreshHeaderLastTimeText = @"MJRefreshHeaderLastTimeText"; +NSString *const MJRefreshHeaderDateTodayText = @"MJRefreshHeaderDateTodayText"; +NSString *const MJRefreshHeaderNoneLastDateText = @"MJRefreshHeaderNoneLastDateText"; \ No newline at end of file diff --git a/Pods/MJRefresh/MJRefresh/NSBundle+MJRefresh.h b/Pods/MJRefresh/MJRefresh/NSBundle+MJRefresh.h new file mode 100644 index 0000000..01df06c --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/NSBundle+MJRefresh.h @@ -0,0 +1,16 @@ +// +// NSBundle+MJRefresh.h +// MJRefreshExample +// +// Created by MJ Lee on 16/6/13. +// Copyright © 2016年 小码哥. All rights reserved. +// + +#import + +@interface NSBundle (MJRefresh) ++ (instancetype)mj_refreshBundle; ++ (UIImage *)mj_arrowImage; ++ (NSString *)mj_localizedStringForKey:(NSString *)key value:(NSString *)value; ++ (NSString *)mj_localizedStringForKey:(NSString *)key; +@end diff --git a/Pods/MJRefresh/MJRefresh/NSBundle+MJRefresh.m b/Pods/MJRefresh/MJRefresh/NSBundle+MJRefresh.m new file mode 100644 index 0000000..c155ad4 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/NSBundle+MJRefresh.m @@ -0,0 +1,61 @@ +// +// NSBundle+MJRefresh.m +// MJRefreshExample +// +// Created by MJ Lee on 16/6/13. +// Copyright © 2016年 小码哥. All rights reserved. +// + +#import "NSBundle+MJRefresh.h" +#import "MJRefreshComponent.h" + +@implementation NSBundle (MJRefresh) ++ (instancetype)mj_refreshBundle +{ + static NSBundle *refreshBundle = nil; + if (refreshBundle == nil) { + // 这里不使用mainBundle是为了适配pod 1.x和0.x + refreshBundle = [NSBundle bundleWithPath:[[NSBundle bundleForClass:[MJRefreshComponent class]] pathForResource:@"MJRefresh" ofType:@"bundle"]]; + } + return refreshBundle; +} + ++ (UIImage *)mj_arrowImage +{ + static UIImage *arrowImage = nil; + if (arrowImage == nil) { + arrowImage = [[UIImage imageWithContentsOfFile:[[self mj_refreshBundle] pathForResource:@"arrow@2x" ofType:@"png"]] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; + } + return arrowImage; +} + ++ (NSString *)mj_localizedStringForKey:(NSString *)key +{ + return [self mj_localizedStringForKey:key value:nil]; +} + ++ (NSString *)mj_localizedStringForKey:(NSString *)key value:(NSString *)value +{ + static NSBundle *bundle = nil; + if (bundle == nil) { + // (iOS获取的语言字符串比较不稳定)目前框架只处理en、zh-Hans、zh-Hant三种情况,其他按照系统默认处理 + NSString *language = [NSLocale preferredLanguages].firstObject; + if ([language hasPrefix:@"en"]) { + language = @"en"; + } else if ([language hasPrefix:@"zh"]) { + if ([language rangeOfString:@"Hans"].location != NSNotFound) { + language = @"zh-Hans"; // 简体中文 + } else { // zh-Hant\zh-HK\zh-TW + language = @"zh-Hant"; // 繁體中文 + } + } else { + language = @"en"; + } + + // 从MJRefresh.bundle中查找资源 + bundle = [NSBundle bundleWithPath:[[NSBundle mj_refreshBundle] pathForResource:language ofType:@"lproj"]]; + } + value = [bundle localizedStringForKey:key value:value table:nil]; + return [[NSBundle mainBundle] localizedStringForKey:key value:value table:nil]; +} +@end diff --git a/Pods/MJRefresh/MJRefresh/UIScrollView+MJExtension.h b/Pods/MJRefresh/MJRefresh/UIScrollView+MJExtension.h new file mode 100644 index 0000000..dd70d08 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/UIScrollView+MJExtension.h @@ -0,0 +1,25 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// 代码地址: http://code4app.com/ios/%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90%E4%B8%8B%E6%8B%89%E4%B8%8A%E6%8B%89%E5%88%B7%E6%96%B0/52326ce26803fabc46000000 +// UIScrollView+Extension.h +// MJRefreshExample +// +// Created by MJ Lee on 14-5-28. +// Copyright (c) 2014年 小码哥. All rights reserved. +// + +#import + +@interface UIScrollView (MJExtension) +@property (readonly, nonatomic) UIEdgeInsets mj_inset; + +@property (assign, nonatomic) CGFloat mj_insetT; +@property (assign, nonatomic) CGFloat mj_insetB; +@property (assign, nonatomic) CGFloat mj_insetL; +@property (assign, nonatomic) CGFloat mj_insetR; + +@property (assign, nonatomic) CGFloat mj_offsetX; +@property (assign, nonatomic) CGFloat mj_offsetY; + +@property (assign, nonatomic) CGFloat mj_contentW; +@property (assign, nonatomic) CGFloat mj_contentH; +@end diff --git a/Pods/MJRefresh/MJRefresh/UIScrollView+MJExtension.m b/Pods/MJRefresh/MJRefresh/UIScrollView+MJExtension.m new file mode 100644 index 0000000..045c1b3 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/UIScrollView+MJExtension.m @@ -0,0 +1,151 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// 代码地址: http://code4app.com/ios/%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90%E4%B8%8B%E6%8B%89%E4%B8%8A%E6%8B%89%E5%88%B7%E6%96%B0/52326ce26803fabc46000000 +// UIScrollView+Extension.m +// MJRefreshExample +// +// Created by MJ Lee on 14-5-28. +// Copyright (c) 2014年 小码哥. All rights reserved. +// + +#import "UIScrollView+MJExtension.h" +#import + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability-new" + +@implementation UIScrollView (MJExtension) + +static BOOL gt_ios_11_; ++ (void)load +{ + // 缓存判断值 + gt_ios_11_ = [[[UIDevice currentDevice] systemVersion] compare:@"11.0" options:NSNumericSearch] != NSOrderedAscending; +} + +- (UIEdgeInsets)mj_inset +{ +#ifdef __IPHONE_11_0 + if (gt_ios_11_) { + return self.adjustedContentInset; + } +#endif + return self.contentInset; +} + +- (void)setMj_insetT:(CGFloat)mj_insetT +{ + UIEdgeInsets inset = self.contentInset; + inset.top = mj_insetT; +#ifdef __IPHONE_11_0 + if (gt_ios_11_) { + inset.top -= (self.adjustedContentInset.top - self.contentInset.top); + } +#endif + self.contentInset = inset; +} + +- (CGFloat)mj_insetT +{ + return self.mj_inset.top; +} + +- (void)setMj_insetB:(CGFloat)mj_insetB +{ + UIEdgeInsets inset = self.contentInset; + inset.bottom = mj_insetB; +#ifdef __IPHONE_11_0 + if (gt_ios_11_) { + inset.bottom -= (self.adjustedContentInset.bottom - self.contentInset.bottom); + } +#endif + self.contentInset = inset; +} + +- (CGFloat)mj_insetB +{ + return self.mj_inset.bottom; +} + +- (void)setMj_insetL:(CGFloat)mj_insetL +{ + UIEdgeInsets inset = self.contentInset; + inset.left = mj_insetL; +#ifdef __IPHONE_11_0 + if (gt_ios_11_) { + inset.left -= (self.adjustedContentInset.left - self.contentInset.left); + } +#endif + self.contentInset = inset; +} + +- (CGFloat)mj_insetL +{ + return self.mj_inset.left; +} + +- (void)setMj_insetR:(CGFloat)mj_insetR +{ + UIEdgeInsets inset = self.contentInset; + inset.right = mj_insetR; +#ifdef __IPHONE_11_0 + if (gt_ios_11_) { + inset.right -= (self.adjustedContentInset.right - self.contentInset.right); + } +#endif + self.contentInset = inset; +} + +- (CGFloat)mj_insetR +{ + return self.mj_inset.right; +} + +- (void)setMj_offsetX:(CGFloat)mj_offsetX +{ + CGPoint offset = self.contentOffset; + offset.x = mj_offsetX; + self.contentOffset = offset; +} + +- (CGFloat)mj_offsetX +{ + return self.contentOffset.x; +} + +- (void)setMj_offsetY:(CGFloat)mj_offsetY +{ + CGPoint offset = self.contentOffset; + offset.y = mj_offsetY; + self.contentOffset = offset; +} + +- (CGFloat)mj_offsetY +{ + return self.contentOffset.y; +} + +- (void)setMj_contentW:(CGFloat)mj_contentW +{ + CGSize size = self.contentSize; + size.width = mj_contentW; + self.contentSize = size; +} + +- (CGFloat)mj_contentW +{ + return self.contentSize.width; +} + +- (void)setMj_contentH:(CGFloat)mj_contentH +{ + CGSize size = self.contentSize; + size.height = mj_contentH; + self.contentSize = size; +} + +- (CGFloat)mj_contentH +{ + return self.contentSize.height; +} +@end +#pragma clang diagnostic pop diff --git a/Pods/MJRefresh/MJRefresh/UIScrollView+MJRefresh.h b/Pods/MJRefresh/MJRefresh/UIScrollView+MJRefresh.h new file mode 100644 index 0000000..17d4715 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/UIScrollView+MJRefresh.h @@ -0,0 +1,26 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// 代码地址: http://code4app.com/ios/%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90%E4%B8%8B%E6%8B%89%E4%B8%8A%E6%8B%89%E5%88%B7%E6%96%B0/52326ce26803fabc46000000 +// UIScrollView+MJRefresh.h +// MJRefreshExample +// +// Created by MJ Lee on 15/3/4. +// Copyright (c) 2015年 小码哥. All rights reserved. +// 给ScrollView增加下拉刷新、上拉刷新的功能 + +#import +#import "MJRefreshConst.h" + +@class MJRefreshHeader, MJRefreshFooter; + +@interface UIScrollView (MJRefresh) +/** 下拉刷新控件 */ +@property (strong, nonatomic) MJRefreshHeader *mj_header; +@property (strong, nonatomic) MJRefreshHeader *header MJRefreshDeprecated("使用mj_header"); +/** 上拉刷新控件 */ +@property (strong, nonatomic) MJRefreshFooter *mj_footer; +@property (strong, nonatomic) MJRefreshFooter *footer MJRefreshDeprecated("使用mj_footer"); + +#pragma mark - other +- (NSInteger)mj_totalDataCount; +@property (copy, nonatomic) void (^mj_reloadDataBlock)(NSInteger totalDataCount); +@end diff --git a/Pods/MJRefresh/MJRefresh/UIScrollView+MJRefresh.m b/Pods/MJRefresh/MJRefresh/UIScrollView+MJRefresh.m new file mode 100644 index 0000000..b1b9942 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/UIScrollView+MJRefresh.m @@ -0,0 +1,163 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// 代码地址: http://code4app.com/ios/%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90%E4%B8%8B%E6%8B%89%E4%B8%8A%E6%8B%89%E5%88%B7%E6%96%B0/52326ce26803fabc46000000 +// UIScrollView+MJRefresh.m +// MJRefreshExample +// +// Created by MJ Lee on 15/3/4. +// Copyright (c) 2015年 小码哥. All rights reserved. +// + +#import "UIScrollView+MJRefresh.h" +#import "MJRefreshHeader.h" +#import "MJRefreshFooter.h" +#import + +@implementation NSObject (MJRefresh) + ++ (void)exchangeInstanceMethod1:(SEL)method1 method2:(SEL)method2 +{ + method_exchangeImplementations(class_getInstanceMethod(self, method1), class_getInstanceMethod(self, method2)); +} + ++ (void)exchangeClassMethod1:(SEL)method1 method2:(SEL)method2 +{ + method_exchangeImplementations(class_getClassMethod(self, method1), class_getClassMethod(self, method2)); +} + +@end + +@implementation UIScrollView (MJRefresh) + +#pragma mark - header +static const char MJRefreshHeaderKey = '\0'; +- (void)setMj_header:(MJRefreshHeader *)mj_header +{ + if (mj_header != self.mj_header) { + // 删除旧的,添加新的 + [self.mj_header removeFromSuperview]; + [self insertSubview:mj_header atIndex:0]; + + // 存储新的 + [self willChangeValueForKey:@"mj_header"]; // KVO + objc_setAssociatedObject(self, &MJRefreshHeaderKey, + mj_header, OBJC_ASSOCIATION_ASSIGN); + [self didChangeValueForKey:@"mj_header"]; // KVO + } +} + +- (MJRefreshHeader *)mj_header +{ + return objc_getAssociatedObject(self, &MJRefreshHeaderKey); +} + +#pragma mark - footer +static const char MJRefreshFooterKey = '\0'; +- (void)setMj_footer:(MJRefreshFooter *)mj_footer +{ + if (mj_footer != self.mj_footer) { + // 删除旧的,添加新的 + [self.mj_footer removeFromSuperview]; + [self insertSubview:mj_footer atIndex:0]; + + // 存储新的 + [self willChangeValueForKey:@"mj_footer"]; // KVO + objc_setAssociatedObject(self, &MJRefreshFooterKey, + mj_footer, OBJC_ASSOCIATION_ASSIGN); + [self didChangeValueForKey:@"mj_footer"]; // KVO + } +} + +- (MJRefreshFooter *)mj_footer +{ + return objc_getAssociatedObject(self, &MJRefreshFooterKey); +} + +#pragma mark - 过期 +- (void)setFooter:(MJRefreshFooter *)footer +{ + self.mj_footer = footer; +} + +- (MJRefreshFooter *)footer +{ + return self.mj_footer; +} + +- (void)setHeader:(MJRefreshHeader *)header +{ + self.mj_header = header; +} + +- (MJRefreshHeader *)header +{ + return self.mj_header; +} + +#pragma mark - other +- (NSInteger)mj_totalDataCount +{ + NSInteger totalCount = 0; + if ([self isKindOfClass:[UITableView class]]) { + UITableView *tableView = (UITableView *)self; + + for (NSInteger section = 0; section + +@interface UIView (MJExtension) +@property (assign, nonatomic) CGFloat mj_x; +@property (assign, nonatomic) CGFloat mj_y; +@property (assign, nonatomic) CGFloat mj_w; +@property (assign, nonatomic) CGFloat mj_h; +@property (assign, nonatomic) CGSize mj_size; +@property (assign, nonatomic) CGPoint mj_origin; +@end diff --git a/Pods/MJRefresh/MJRefresh/UIView+MJExtension.m b/Pods/MJRefresh/MJRefresh/UIView+MJExtension.m new file mode 100644 index 0000000..7e8eda2 --- /dev/null +++ b/Pods/MJRefresh/MJRefresh/UIView+MJExtension.m @@ -0,0 +1,84 @@ +// 代码地址: https://github.com/CoderMJLee/MJRefresh +// 代码地址: http://code4app.com/ios/%E5%BF%AB%E9%80%9F%E9%9B%86%E6%88%90%E4%B8%8B%E6%8B%89%E4%B8%8A%E6%8B%89%E5%88%B7%E6%96%B0/52326ce26803fabc46000000 +// UIView+Extension.m +// MJRefreshExample +// +// Created by MJ Lee on 14-5-28. +// Copyright (c) 2014年 小码哥. All rights reserved. +// + +#import "UIView+MJExtension.h" + +@implementation UIView (MJExtension) +- (void)setMj_x:(CGFloat)mj_x +{ + CGRect frame = self.frame; + frame.origin.x = mj_x; + self.frame = frame; +} + +- (CGFloat)mj_x +{ + return self.frame.origin.x; +} + +- (void)setMj_y:(CGFloat)mj_y +{ + CGRect frame = self.frame; + frame.origin.y = mj_y; + self.frame = frame; +} + +- (CGFloat)mj_y +{ + return self.frame.origin.y; +} + +- (void)setMj_w:(CGFloat)mj_w +{ + CGRect frame = self.frame; + frame.size.width = mj_w; + self.frame = frame; +} + +- (CGFloat)mj_w +{ + return self.frame.size.width; +} + +- (void)setMj_h:(CGFloat)mj_h +{ + CGRect frame = self.frame; + frame.size.height = mj_h; + self.frame = frame; +} + +- (CGFloat)mj_h +{ + return self.frame.size.height; +} + +- (void)setMj_size:(CGSize)mj_size +{ + CGRect frame = self.frame; + frame.size = mj_size; + self.frame = frame; +} + +- (CGSize)mj_size +{ + return self.frame.size; +} + +- (void)setMj_origin:(CGPoint)mj_origin +{ + CGRect frame = self.frame; + frame.origin = mj_origin; + self.frame = frame; +} + +- (CGPoint)mj_origin +{ + return self.frame.origin; +} +@end diff --git a/Pods/MJRefresh/README.md b/Pods/MJRefresh/README.md new file mode 100644 index 0000000..8bf7874 --- /dev/null +++ b/Pods/MJRefresh/README.md @@ -0,0 +1,362 @@ +![(logo)](http://images.cnitblog.com/blog2015/497279/201505/051004492043385.png) +## MJRefresh +* An easy way to use pull-to-refresh + +## Contents +* Getting Started + * [Features【Support what kinds of controls to refresh】](#Support_what_kinds_of_controls_to_refresh) + * [Installation【How to use MJRefresh】](#How_to_use_MJRefresh) + * [Who's using【More than hundreds of Apps are using MJRefresh】](#More_than_hundreds_of_Apps_are_using_MJRefresh) + * [Classes【The Class Structure Chart of MJRefresh】](#The_Class_Structure_Chart_of_MJRefresh) +* Comment API + * [MJRefreshComponent.h](#MJRefreshComponent.h) + * [MJRefreshHeader.h](#MJRefreshHeader.h) + * [MJRefreshFooter.h](#MJRefreshFooter.h) + * [MJRefreshAutoFooter.h](#MJRefreshAutoFooter.h) +* Examples + * [Reference](#Reference) + * [The drop-down refresh 01-Default](#The_drop-down_refresh_01-Default) + * [The drop-down refresh 02-Animation image](#The_drop-down_refresh_02-Animation_image) + * [The drop-down refresh 03-Hide the time](#The_drop-down_refresh_03-Hide_the_time) + * [The drop-down refresh 04-Hide status and time](#The_drop-down_refresh_04-Hide_status_and_time) + * [The drop-down refresh 05-DIY title](#The_drop-down_refresh_05-DIY_title) + * [The drop-down refresh 06-DIY the control of refresh](#The_drop-down_refresh_06-DIY_the_control_of_refresh) + * [The pull to refresh 01-Default](#The_pull_to_refresh_01-Default) + * [The pull to refresh 02-Animation image](#The_pull_to_refresh_02-Animation_image) + * [The pull to refresh 03-Hide the title of refresh status](#The_pull_to_refresh_03-Hide_the_title_of_refresh_status) + * [The pull to refresh 04-All loaded](#The_pull_to_refresh_04-All_loaded) + * [The pull to refresh 05-DIY title](#The_pull_to_refresh_05-DIY_title) + * [The pull to refresh 06-Hidden After loaded](#The_pull_to_refresh_06-Hidden_After_loaded) + * [The pull to refresh 07-Automatic back of the pull01](#The_pull_to_refresh_07-Automatic_back_of_the_pull01) + * [The pull to refresh 08-Automatic back of the pull02](#The_pull_to_refresh_08-Automatic_back_of_the_pull02) + * [The pull to refresh 09-DIY the control of refresh(Automatic refresh)](#The_pull_to_refresh_09-DIY_the_control_of_refresh(Automatic_refresh)) + * [The pull to refresh 10-DIY the control of refresh(Automatic back)](#The_pull_to_refresh_10-DIY_the_control_of_refresh(Automatic_back)) + * [UICollectionView01-The pull and drop-down refresh](#UICollectionView01-The_pull_and_drop-down_refresh) + * [UIWebView01-The drop-down refresh](#UIWebView01-The_drop-down_refresh) +* [Hope](#Hope) + +## Support what kinds of controls to refresh +* `UIScrollView`、`UITableView`、`UICollectionView`、`UIWebView` + +## How to use MJRefresh +* Installation with CocoaPods:`pod 'MJRefresh'` +* Manual import: + * Drag All files in the `MJRefresh` folder to project + * Import the main file:`#import "MJRefresh.h"` + +```objc +Base Custom +MJRefresh.bundle MJRefresh.h +MJRefreshConst.h MJRefreshConst.m +UIScrollView+MJExtension.h UIScrollView+MJExtension.m +UIScrollView+MJRefresh.h UIScrollView+MJRefresh.m +UIView+MJExtension.h UIView+MJExtension.m +``` + +## More than hundreds of Apps are using MJRefresh + +* More information of App can focus on:[M了个J-博客园](http://www.cnblogs.com/mjios/p/4409853.html) + +## The Class Structure Chart of MJRefresh +![](http://images0.cnblogs.com/blog2015/497279/201506/132232456139177.png) +- `The class of red text` in the chart:You can use them directly + - The drop-down refresh control types + - Normal:`MJRefreshNormalHeader` + - Gif:`MJRefreshGifHeader` + - The pull to refresh control types + - Auto refresh + - Normal:`MJRefreshAutoNormalFooter` + - Gif:`MJRefreshAutoGifFooter` + - Auto Back + - Normal:`MJRefreshBackNormalFooter` + - Gif:`MJRefreshBackGifFooter` +- `The class of non-red text` in the chart:For inheritance,to use DIY the control of refresh +- About how to DIY the control of refresh,You can refer the Class in below Chart
+ + +## MJRefreshComponent.h +```objc +/** The Base Class of refresh control */ +@interface MJRefreshComponent : UIView +#pragma mark - Control the state of Refresh + +/** BeginRefreshing */ +- (void)beginRefreshing; +/** EndRefreshing */ +- (void)endRefreshing; +/** IsRefreshing */ +- (BOOL)isRefreshing; + +#pragma mark - Other +/** According to the drag ratio to change alpha automatically */ +@property (assign, nonatomic, getter=isAutomaticallyChangeAlpha) BOOL automaticallyChangeAlpha; +@end +``` + +## MJRefreshHeader.h +```objc +@interface MJRefreshHeader : MJRefreshComponent +/** Creat header */ ++ (instancetype)headerWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock; +/** Creat header */ ++ (instancetype)headerWithRefreshingTarget:(id)target refreshingAction:(SEL)action; + +/** This key is used to storage the time that the last time of drown-down successfully */ +@property (copy, nonatomic) NSString *lastUpdatedTimeKey; +/** The last time of drown-down successfully */ +@property (strong, nonatomic, readonly) NSDate *lastUpdatedTime; + +/** Ignored scrollView contentInset top */ +@property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetTop; +@end +``` + +## MJRefreshFooter.h +```objc +@interface MJRefreshFooter : MJRefreshComponent +/** Creat footer */ ++ (instancetype)footerWithRefreshingBlock:(MJRefreshComponentRefreshingBlock)refreshingBlock; +/** Creat footer */ ++ (instancetype)footerWithRefreshingTarget:(id)target refreshingAction:(SEL)action; + +/** NoticeNoMoreData */ +- (void)noticeNoMoreData; +/** ResetNoMoreData(Clear the status of NoMoreData ) */ +- (void)resetNoMoreData; + +/** Ignored scrollView contentInset bottom */ +@property (assign, nonatomic) CGFloat ignoredScrollViewContentInsetBottom; + +/** Automaticlly show or hidden by the count of data(Show-have data,Hidden- no data) */ +@property (assign, nonatomic) BOOL automaticallyHidden; +@end +``` + +## MJRefreshAutoFooter.h +```objc +@interface MJRefreshAutoFooter : MJRefreshFooter +/** Is Automatically Refresh(Default is Yes) */ +@property (assign, nonatomic, getter=isAutomaticallyRefresh) BOOL automaticallyRefresh; + +/** When there is much at the bottom of the control is automatically refresh(Default is 1.0,Is at the bottom of the control appears in full, will refresh automatically) */ +@property (assign, nonatomic) CGFloat triggerAutomaticallyRefreshPercent; +@end +``` + +## Reference +```objc +* Due to there are more functions of this framework,Don't write specific text describe its usage +* You can directly reference examples MJTableViewController、MJCollectionViewController、MJWebViewController,More intuitive and fast. +``` + + +## The drop-down refresh 01-Default + +```objc +self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{ + //Call this Block When enter the refresh status automatically +}]; +或 +// Set the callback(Once you enter the refresh status,then call the action of target,that is call [self loadNewData]) +self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)]; + +// Enter the refresh status immediately +[self.tableView.header beginRefreshing]; +``` +![(下拉刷新01-普通)](http://images0.cnblogs.com/blog2015/497279/201506/141204343486151.gif) + +## The drop-down refresh 02-Animation image +```objc +// Set the callback(一Once you enter the refresh status,then call the action of target,that is call [self loadNewData]) +MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)]; +// Set the ordinary state of animated images +[header setImages:idleImages forState:MJRefreshStateIdle]; +// Set the pulling state of animated images(Enter the status of refreshing as soon as loosen) +[header setImages:pullingImages forState:MJRefreshStatePulling]; +// Set the refreshing state of animated images +[header setImages:refreshingImages forState:MJRefreshStateRefreshing]; +// Set header +self.tableView.mj_header = header; +``` +![(下拉刷新02-动画图片)](http://images0.cnblogs.com/blog2015/497279/201506/141204402238389.gif) + +## The drop-down refresh 03-Hide the time +```objc +// Hide the time +header.lastUpdatedTimeLabel.hidden = YES; +``` +![(下拉刷新03-隐藏时间)](http://images0.cnblogs.com/blog2015/497279/201506/141204456132944.gif) + +## The drop-down refresh 04-Hide status and time +```objc +// Hide the time +header.lastUpdatedTimeLabel.hidden = YES; + +// Hide the status +header.stateLabel.hidden = YES; +``` +![(下拉刷新04-隐藏状态和时间0)](http://images0.cnblogs.com/blog2015/497279/201506/141204508639539.gif) + +## The drop-down refresh 05-DIY title +```objc +// Set title +[header setTitle:@"Pull down to refresh" forState:MJRefreshStateIdle]; +[header setTitle:@"Release to refresh" forState:MJRefreshStatePulling]; +[header setTitle:@"Loading ..." forState:MJRefreshStateRefreshing]; + +// Set font +header.stateLabel.font = [UIFont systemFontOfSize:15]; +header.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:14]; + +// Set textColor +header.stateLabel.textColor = [UIColor redColor]; +header.lastUpdatedTimeLabel.textColor = [UIColor blueColor]; +``` +![(下拉刷新05-自定义文字)](http://images0.cnblogs.com/blog2015/497279/201506/141204563633593.gif) + +## The drop-down refresh 06-DIY the control of refresh +```objc +self.tableView.mj_header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)]; +// Implementation reference to MJDIYHeader.h和MJDIYHeader.m +``` +![(下拉刷新06-自定义刷新控件)](http://images0.cnblogs.com/blog2015/497279/201506/141205019261159.gif) + +## The pull to refresh 01-Default +```objc +self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{ + //Call this Block When enter the refresh status automatically +}]; +或 +// Set the callback(Once you enter the refresh status,then call the action of target,that is call [self loadMoreData]) +self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)]; +``` +![(上拉刷新01-默认)](http://images0.cnblogs.com/blog2015/497279/201506/141205090047696.gif) + +## The pull to refresh 02-Animation image +```objc +// Set the callback(Once you enter the refresh status,then call the action of target,that is call [self loadMoreData]) +MJRefreshAutoGifFooter *footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)]; + +// Set the refresh image +[footer setImages:refreshingImages forState:MJRefreshStateRefreshing]; + +// Set footer +self.tableView.mj_footer = footer; +``` +![(上拉刷新02-动画图片)](http://images0.cnblogs.com/blog2015/497279/201506/141205141445793.gif) + +## The pull to refresh 03-Hide the title of refresh status +```objc +// Hide the title of refresh status +footer.refreshingTitleHidden = YES; +// If does have not above method,then use footer.stateLabel.hidden = YES; +``` +![(上拉刷新03-隐藏刷新状态的文字)](http://images0.cnblogs.com/blog2015/497279/201506/141205200985774.gif) + +## The pull to refresh 04-All loaded +```objc +//Become the status of NoMoreData +[footer noticeNoMoreData]; +``` +![(上拉刷新04-全部加载完毕)](http://images0.cnblogs.com/blog2015/497279/201506/141205248634686.gif) + +## The pull to refresh 05-DIY title +```objc +// Set title +[footer setTitle:@"Click or drag up to refresh" forState:MJRefreshStateIdle]; +[footer setTitle:@"Loading more ..." forState:MJRefreshStateRefreshing]; +[footer setTitle:@"No more data" forState:MJRefreshStateNoMoreData]; + +// Set font +footer.stateLabel.font = [UIFont systemFontOfSize:17]; + +// Set textColor +footer.stateLabel.textColor = [UIColor blueColor]; +``` +![(上拉刷新05-自定义文字)](http://images0.cnblogs.com/blog2015/497279/201506/141205295511153.gif) + +## The pull to refresh 06-Hidden After loaded +```objc +//Hidden current control of the pull to refresh +self.tableView.mj_footer.hidden = YES; +``` +![(上拉刷新06-加载后隐藏)](http://images0.cnblogs.com/blog2015/497279/201506/141205343481821.gif) + +## The pull to refresh 07-Automatic back of the pull01 +```objc +self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)]; +``` +![(上拉刷新07-自动回弹的上拉01)](http://images0.cnblogs.com/blog2015/497279/201506/141205392239231.gif) + +## The pull to refresh 08-Automatic back of the pull02 +```objc +MJRefreshBackGifFooter *footer = [MJRefreshBackGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)]; + +// Set the normal state of the animated image +[footer setImages:idleImages forState:MJRefreshStateIdle]; +// Set the pulling state of animated images(Enter the status of refreshing as soon as loosen) +[footer setImages:pullingImages forState:MJRefreshStatePulling]; +// Set the refreshing state of animated images +[footer setImages:refreshingImages forState:MJRefreshStateRefreshing]; + +// Set footer +self.tableView.mj_footer = footer; +``` +![(上拉刷新07-自动回弹的上拉02)](http://images0.cnblogs.com/blog2015/497279/201506/141205441443628.gif) + +## The pull to refresh 09-DIY the control of refresh(Automatic refresh) +```objc +self.tableView.mj_footer = [MJDIYAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)]; +// Implementation reference to MJDIYAutoFooter.h和MJDIYAutoFooter.m +``` +![(上拉刷新09-自定义刷新控件(自动刷新))](http://images0.cnblogs.com/blog2015/497279/201506/141205500195866.gif) + +## The pull to refresh 10-DIY the control of refresh(Automatic back) +```objc +self.tableView.mj_footer = [MJDIYBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)]; +// Implementation reference to MJDIYBackFooter.h和MJDIYBackFooter.m +``` +![(上拉刷新10-自定义刷新控件(自动回弹))](http://images0.cnblogs.com/blog2015/497279/201506/141205560666819.gif) + +## UICollectionView01-The pull and drop-down refresh +```objc +// The drop-down refresh +self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{ + //Call this Block When enter the refresh status automatically +}]; + +// The pull to refresh +self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{ + //Call this Block When enter the refresh status automatically +}]; +``` +![(UICollectionView01-上下拉刷新)](http://images0.cnblogs.com/blog2015/497279/201506/141206021603758.gif) + +## UIWebView01-The drop-down refresh +```objc +//Add the control of The drop-down refresh +self.webView.scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{ + //Call this Block When enter the refresh status automatically +}]; +``` +![(UICollectionView01-上下拉刷新)](http://images0.cnblogs.com/blog2015/497279/201506/141206080514524.gif) + +## Remind +* ARC +* iOS>=6.0 +* iPhone \ iPad screen anyway + +## Hope +* If you find bug when used,Hope you can Issues me,Thank you or try to download the latest code of this framework to see the BUG has been fixed or not) +* If you find the function is not enough when used,Hope you can Issues me,I very much to add more useful function to this framework ,Thank you ! +* If you want to contribute code for MJRefresh,please Pull Requests me +* If you use MJRefresh in your develop app,Hope you can go to[CocoaControls](https://www.cocoacontrols.com/controls/mjrefresh)to add the iTunes path + of you app,I Will install your app,and according to the usage of many app,to be a better design and improve to MJRefresh,Thank you ! + * StepO1(WeChat is just an Example,Explore“Your app name itunes”) +![(step01)](http://ww4.sinaimg.cn/mw1024/800cdf9ctw1eq0viiv5rsj20sm0ea41t.jpg) + * StepO2 +![(step02)](http://ww2.sinaimg.cn/mw1024/800cdf9ctw1eq0vilejxlj20tu0me7a0.jpg) + * StepO3 +![(step03)](http://ww1.sinaimg.cn/mw1024/800cdf9ctw1eq0viocpo5j20wc0dc0un.jpg) + * StepO4 +![(step04)](http://ww3.sinaimg.cn/mw1024/800cdf9ctw1eq0vir137xj20si0gewgu.jpg) diff --git a/Pods/Manifest.lock b/Pods/Manifest.lock new file mode 100644 index 0000000..a6e8c16 --- /dev/null +++ b/Pods/Manifest.lock @@ -0,0 +1,110 @@ +PODS: + - AFNetworking (3.2.1): + - AFNetworking/NSURLSession (= 3.2.1) + - AFNetworking/Reachability (= 3.2.1) + - AFNetworking/Security (= 3.2.1) + - AFNetworking/Serialization (= 3.2.1) + - AFNetworking/UIKit (= 3.2.1) + - AFNetworking/NSURLSession (3.2.1): + - AFNetworking/Reachability + - AFNetworking/Security + - AFNetworking/Serialization + - AFNetworking/Reachability (3.2.1) + - AFNetworking/Security (3.2.1) + - AFNetworking/Serialization (3.2.1) + - AFNetworking/UIKit (3.2.1): + - AFNetworking/NSURLSession + - FMDB (2.7.2): + - FMDB/standard (= 2.7.2) + - FMDB/standard (2.7.2) + - IQKeyboardManager (6.1.1) + - JCore (1.2.1) + - JPush (3.1.0): + - JCore (~> 1.2.0) + - JSONModel (1.7.0) + - LKDBHelper (2.5.1): + - LKDBHelper/standard (= 2.5.1) + - LKDBHelper/standard (2.5.1): + - FMDB + - Masonry (1.0.2) + - MBProgressHUD (0.9.2) + - MJRefresh (3.1.15.3) + - NJKWebViewProgress (0.2.3): + - NJKWebViewProgress/Core (= 0.2.3) + - NJKWebViewProgress/ProgressView (= 0.2.3) + - NJKWebViewProgress/Core (0.2.3) + - NJKWebViewProgress/ProgressView (0.2.3) + - SDWebImage (4.4.2): + - SDWebImage/Core (= 4.4.2) + - SDWebImage/Core (4.4.2) + - SocketRocket (0.5.1) + - Toast (4.0.0) + - TTTAttributedLabel (2.0.0) + - "UITableView+FDTemplateLayoutCell (1.6)" + - WechatOpenSDK (1.8.2) + - YTKKeyValueStore (0.1.2): + - FMDB (~> 2.0) + +DEPENDENCIES: + - AFNetworking (~> 3.0) + - FMDB + - IQKeyboardManager + - JPush + - JSONModel + - LKDBHelper + - Masonry (~> 1.0.0) + - MBProgressHUD (~> 0.9.2) + - MJRefresh + - NJKWebViewProgress + - SDWebImage (~> 4.0) + - SocketRocket + - Toast (~> 4.0.0) + - TTTAttributedLabel + - "UITableView+FDTemplateLayoutCell" + - WechatOpenSDK + - YTKKeyValueStore + +SPEC REPOS: + https://github.com/CocoaPods/Specs.git: + - AFNetworking + - FMDB + - IQKeyboardManager + - JCore + - JPush + - JSONModel + - LKDBHelper + - Masonry + - MBProgressHUD + - MJRefresh + - NJKWebViewProgress + - SDWebImage + - SocketRocket + - Toast + - TTTAttributedLabel + - "UITableView+FDTemplateLayoutCell" + - WechatOpenSDK + - YTKKeyValueStore + +SPEC CHECKSUMS: + AFNetworking: b6f891fdfaed196b46c7a83cf209e09697b94057 + FMDB: 6198a90e7b6900cfc046e6bc0ef6ebb7be9236aa + IQKeyboardManager: 79c57795f5c2408d259d37b9da2ed07efcbb5225 + JCore: 467b5b56bd367c548f88ee1b5794d94ee07ab319 + JPush: 5921e25ad13e0386351079217b009f2039084eac + JSONModel: 840bc0fcffb24b8454d2c026bf26fea454b8e98d + LKDBHelper: 9a276ba51f2e16263d46a9517e16cc9b03472664 + Masonry: 7c429b56da9d4ee0bbb3ed77a5ea710d6a5df39e + MBProgressHUD: 1569cf7ace17a8bac47aabfbb8580a49690386d1 + MJRefresh: b48380ae2b927b46c4ef000de9adb8dc748e1df7 + NJKWebViewProgress: f481fd424cb5ecc27eacae11b5397db92fba9a4d + SDWebImage: 624d6e296c69b244bcede364c72ae0430ac14681 + SocketRocket: d57c7159b83c3c6655745cd15302aa24b6bae531 + Toast: 91b396c56ee72a5790816f40d3a94dd357abc196 + TTTAttributedLabel: 8cffe8e127e4e82ff3af1e5386d4cd0ad000b656 + "UITableView+FDTemplateLayoutCell": 5c949b4a5059c404b442926c0e80f81d10a2d66f + WechatOpenSDK: 676feec516a11173eafd1fe64b10d27babf28701 + YTKKeyValueStore: 4d002941540dd5108fa23009b71e0f2f937f7a0f + +PODFILE CHECKSUM: dab9f56b1ec7688e11809754299b1b531ddcca86 + +COCOAPODS: 1.5.0 diff --git a/Pods/Masonry/LICENSE b/Pods/Masonry/LICENSE new file mode 100644 index 0000000..a843c00 --- /dev/null +++ b/Pods/Masonry/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011-2012 Masonry Team - https://github.com/Masonry + +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/Pods/Masonry/Masonry/MASCompositeConstraint.h b/Pods/Masonry/Masonry/MASCompositeConstraint.h new file mode 100644 index 0000000..934c6f1 --- /dev/null +++ b/Pods/Masonry/Masonry/MASCompositeConstraint.h @@ -0,0 +1,26 @@ +// +// MASCompositeConstraint.h +// Masonry +// +// Created by Jonas Budelmann on 21/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASConstraint.h" +#import "MASUtilities.h" + +/** + * A group of MASConstraint objects + */ +@interface MASCompositeConstraint : MASConstraint + +/** + * Creates a composite with a predefined array of children + * + * @param children child MASConstraints + * + * @return a composite constraint + */ +- (id)initWithChildren:(NSArray *)children; + +@end diff --git a/Pods/Masonry/Masonry/MASCompositeConstraint.m b/Pods/Masonry/Masonry/MASCompositeConstraint.m new file mode 100644 index 0000000..ed63ed6 --- /dev/null +++ b/Pods/Masonry/Masonry/MASCompositeConstraint.m @@ -0,0 +1,177 @@ +// +// MASCompositeConstraint.m +// Masonry +// +// Created by Jonas Budelmann on 21/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASCompositeConstraint.h" +#import "MASConstraint+Private.h" + +@interface MASCompositeConstraint () + +@property (nonatomic, strong) id mas_key; +@property (nonatomic, strong) NSMutableArray *childConstraints; + +@end + +@implementation MASCompositeConstraint + +- (id)initWithChildren:(NSArray *)children { + self = [super init]; + if (!self) return nil; + + _childConstraints = [children mutableCopy]; + for (MASConstraint *constraint in _childConstraints) { + constraint.delegate = self; + } + + return self; +} + +#pragma mark - MASConstraintDelegate + +- (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint { + NSUInteger index = [self.childConstraints indexOfObject:constraint]; + NSAssert(index != NSNotFound, @"Could not find constraint %@", constraint); + [self.childConstraints replaceObjectAtIndex:index withObject:replacementConstraint]; +} + +- (MASConstraint *)constraint:(MASConstraint __unused *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { + id strongDelegate = self.delegate; + MASConstraint *newConstraint = [strongDelegate constraint:self addConstraintWithLayoutAttribute:layoutAttribute]; + newConstraint.delegate = self; + [self.childConstraints addObject:newConstraint]; + return newConstraint; +} + +#pragma mark - NSLayoutConstraint multiplier proxies + +- (MASConstraint * (^)(CGFloat))multipliedBy { + return ^id(CGFloat multiplier) { + for (MASConstraint *constraint in self.childConstraints) { + constraint.multipliedBy(multiplier); + } + return self; + }; +} + +- (MASConstraint * (^)(CGFloat))dividedBy { + return ^id(CGFloat divider) { + for (MASConstraint *constraint in self.childConstraints) { + constraint.dividedBy(divider); + } + return self; + }; +} + +#pragma mark - MASLayoutPriority proxy + +- (MASConstraint * (^)(MASLayoutPriority))priority { + return ^id(MASLayoutPriority priority) { + for (MASConstraint *constraint in self.childConstraints) { + constraint.priority(priority); + } + return self; + }; +} + +#pragma mark - NSLayoutRelation proxy + +- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { + return ^id(id attr, NSLayoutRelation relation) { + for (MASConstraint *constraint in self.childConstraints.copy) { + constraint.equalToWithRelation(attr, relation); + } + return self; + }; +} + +#pragma mark - attribute chaining + +- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { + [self constraint:self addConstraintWithLayoutAttribute:layoutAttribute]; + return self; +} + +#pragma mark - Animator proxy + +#if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) + +- (MASConstraint *)animator { + for (MASConstraint *constraint in self.childConstraints) { + [constraint animator]; + } + return self; +} + +#endif + +#pragma mark - debug helpers + +- (MASConstraint * (^)(id))key { + return ^id(id key) { + self.mas_key = key; + int i = 0; + for (MASConstraint *constraint in self.childConstraints) { + constraint.key([NSString stringWithFormat:@"%@[%d]", key, i++]); + } + return self; + }; +} + +#pragma mark - NSLayoutConstraint constant setters + +- (void)setInsets:(MASEdgeInsets)insets { + for (MASConstraint *constraint in self.childConstraints) { + constraint.insets = insets; + } +} + +- (void)setOffset:(CGFloat)offset { + for (MASConstraint *constraint in self.childConstraints) { + constraint.offset = offset; + } +} + +- (void)setSizeOffset:(CGSize)sizeOffset { + for (MASConstraint *constraint in self.childConstraints) { + constraint.sizeOffset = sizeOffset; + } +} + +- (void)setCenterOffset:(CGPoint)centerOffset { + for (MASConstraint *constraint in self.childConstraints) { + constraint.centerOffset = centerOffset; + } +} + +#pragma mark - MASConstraint + +- (void)activate { + for (MASConstraint *constraint in self.childConstraints) { + [constraint activate]; + } +} + +- (void)deactivate { + for (MASConstraint *constraint in self.childConstraints) { + [constraint deactivate]; + } +} + +- (void)install { + for (MASConstraint *constraint in self.childConstraints) { + constraint.updateExisting = self.updateExisting; + [constraint install]; + } +} + +- (void)uninstall { + for (MASConstraint *constraint in self.childConstraints) { + [constraint uninstall]; + } +} + +@end diff --git a/Pods/Masonry/Masonry/MASConstraint+Private.h b/Pods/Masonry/Masonry/MASConstraint+Private.h new file mode 100644 index 0000000..ee0fd96 --- /dev/null +++ b/Pods/Masonry/Masonry/MASConstraint+Private.h @@ -0,0 +1,66 @@ +// +// MASConstraint+Private.h +// Masonry +// +// Created by Nick Tymchenko on 29/04/14. +// Copyright (c) 2014 cloudling. All rights reserved. +// + +#import "MASConstraint.h" + +@protocol MASConstraintDelegate; + + +@interface MASConstraint () + +/** + * Whether or not to check for an existing constraint instead of adding constraint + */ +@property (nonatomic, assign) BOOL updateExisting; + +/** + * Usually MASConstraintMaker but could be a parent MASConstraint + */ +@property (nonatomic, weak) id delegate; + +/** + * Based on a provided value type, is equal to calling: + * NSNumber - setOffset: + * NSValue with CGPoint - setPointOffset: + * NSValue with CGSize - setSizeOffset: + * NSValue with MASEdgeInsets - setInsets: + */ +- (void)setLayoutConstantWithValue:(NSValue *)value; + +@end + + +@interface MASConstraint (Abstract) + +/** + * Sets the constraint relation to given NSLayoutRelation + * returns a block which accepts one of the following: + * MASViewAttribute, UIView, NSValue, NSArray + * see readme for more details. + */ +- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation; + +/** + * Override to set a custom chaining behaviour + */ +- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute; + +@end + + +@protocol MASConstraintDelegate + +/** + * Notifies the delegate when the constraint needs to be replaced with another constraint. For example + * A MASViewConstraint may turn into a MASCompositeConstraint when an array is passed to one of the equality blocks + */ +- (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint; + +- (MASConstraint *)constraint:(MASConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute; + +@end diff --git a/Pods/Masonry/Masonry/MASConstraint.h b/Pods/Masonry/Masonry/MASConstraint.h new file mode 100644 index 0000000..70a10c8 --- /dev/null +++ b/Pods/Masonry/Masonry/MASConstraint.h @@ -0,0 +1,258 @@ +// +// MASConstraint.h +// Masonry +// +// Created by Jonas Budelmann on 22/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASUtilities.h" + +/** + * Enables Constraints to be created with chainable syntax + * Constraint can represent single NSLayoutConstraint (MASViewConstraint) + * or a group of NSLayoutConstraints (MASComposisteConstraint) + */ +@interface MASConstraint : NSObject + +// Chaining Support + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight + */ +- (MASConstraint * (^)(MASEdgeInsets insets))insets; + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeWidth, NSLayoutAttributeHeight + */ +- (MASConstraint * (^)(CGSize offset))sizeOffset; + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeCenterX, NSLayoutAttributeCenterY + */ +- (MASConstraint * (^)(CGPoint offset))centerOffset; + +/** + * Modifies the NSLayoutConstraint constant + */ +- (MASConstraint * (^)(CGFloat offset))offset; + +/** + * Modifies the NSLayoutConstraint constant based on a value type + */ +- (MASConstraint * (^)(NSValue *value))valueOffset; + +/** + * Sets the NSLayoutConstraint multiplier property + */ +- (MASConstraint * (^)(CGFloat multiplier))multipliedBy; + +/** + * Sets the NSLayoutConstraint multiplier to 1.0/dividedBy + */ +- (MASConstraint * (^)(CGFloat divider))dividedBy; + +/** + * Sets the NSLayoutConstraint priority to a float or MASLayoutPriority + */ +- (MASConstraint * (^)(MASLayoutPriority priority))priority; + +/** + * Sets the NSLayoutConstraint priority to MASLayoutPriorityLow + */ +- (MASConstraint * (^)())priorityLow; + +/** + * Sets the NSLayoutConstraint priority to MASLayoutPriorityMedium + */ +- (MASConstraint * (^)())priorityMedium; + +/** + * Sets the NSLayoutConstraint priority to MASLayoutPriorityHigh + */ +- (MASConstraint * (^)())priorityHigh; + +/** + * Sets the constraint relation to NSLayoutRelationEqual + * returns a block which accepts one of the following: + * MASViewAttribute, UIView, NSValue, NSArray + * see readme for more details. + */ +- (MASConstraint * (^)(id attr))equalTo; + +/** + * Sets the constraint relation to NSLayoutRelationGreaterThanOrEqual + * returns a block which accepts one of the following: + * MASViewAttribute, UIView, NSValue, NSArray + * see readme for more details. + */ +- (MASConstraint * (^)(id attr))greaterThanOrEqualTo; + +/** + * Sets the constraint relation to NSLayoutRelationLessThanOrEqual + * returns a block which accepts one of the following: + * MASViewAttribute, UIView, NSValue, NSArray + * see readme for more details. + */ +- (MASConstraint * (^)(id attr))lessThanOrEqualTo; + +/** + * Optional semantic property which has no effect but improves the readability of constraint + */ +- (MASConstraint *)with; + +/** + * Optional semantic property which has no effect but improves the readability of constraint + */ +- (MASConstraint *)and; + +/** + * Creates a new MASCompositeConstraint with the called attribute and reciever + */ +- (MASConstraint *)left; +- (MASConstraint *)top; +- (MASConstraint *)right; +- (MASConstraint *)bottom; +- (MASConstraint *)leading; +- (MASConstraint *)trailing; +- (MASConstraint *)width; +- (MASConstraint *)height; +- (MASConstraint *)centerX; +- (MASConstraint *)centerY; +- (MASConstraint *)baseline; + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +- (MASConstraint *)firstBaseline; +- (MASConstraint *)lastBaseline; + +#endif + +#if TARGET_OS_IPHONE || TARGET_OS_TV + +- (MASConstraint *)leftMargin; +- (MASConstraint *)rightMargin; +- (MASConstraint *)topMargin; +- (MASConstraint *)bottomMargin; +- (MASConstraint *)leadingMargin; +- (MASConstraint *)trailingMargin; +- (MASConstraint *)centerXWithinMargins; +- (MASConstraint *)centerYWithinMargins; + +#endif + + +/** + * Sets the constraint debug name + */ +- (MASConstraint * (^)(id key))key; + +// NSLayoutConstraint constant Setters +// for use outside of mas_updateConstraints/mas_makeConstraints blocks + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeTop, NSLayoutAttributeLeft, NSLayoutAttributeBottom, NSLayoutAttributeRight + */ +- (void)setInsets:(MASEdgeInsets)insets; + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeWidth, NSLayoutAttributeHeight + */ +- (void)setSizeOffset:(CGSize)sizeOffset; + +/** + * Modifies the NSLayoutConstraint constant, + * only affects MASConstraints in which the first item's NSLayoutAttribute is one of the following + * NSLayoutAttributeCenterX, NSLayoutAttributeCenterY + */ +- (void)setCenterOffset:(CGPoint)centerOffset; + +/** + * Modifies the NSLayoutConstraint constant + */ +- (void)setOffset:(CGFloat)offset; + + +// NSLayoutConstraint Installation support + +#if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) +/** + * Whether or not to go through the animator proxy when modifying the constraint + */ +@property (nonatomic, copy, readonly) MASConstraint *animator; +#endif + +/** + * Activates an NSLayoutConstraint if it's supported by an OS. + * Invokes install otherwise. + */ +- (void)activate; + +/** + * Deactivates previously installed/activated NSLayoutConstraint. + */ +- (void)deactivate; + +/** + * Creates a NSLayoutConstraint and adds it to the appropriate view. + */ +- (void)install; + +/** + * Removes previously installed NSLayoutConstraint + */ +- (void)uninstall; + +@end + + +/** + * Convenience auto-boxing macros for MASConstraint methods. + * + * Defining MAS_SHORTHAND_GLOBALS will turn on auto-boxing for default syntax. + * A potential drawback of this is that the unprefixed macros will appear in global scope. + */ +#define mas_equalTo(...) equalTo(MASBoxValue((__VA_ARGS__))) +#define mas_greaterThanOrEqualTo(...) greaterThanOrEqualTo(MASBoxValue((__VA_ARGS__))) +#define mas_lessThanOrEqualTo(...) lessThanOrEqualTo(MASBoxValue((__VA_ARGS__))) + +#define mas_offset(...) valueOffset(MASBoxValue((__VA_ARGS__))) + + +#ifdef MAS_SHORTHAND_GLOBALS + +#define equalTo(...) mas_equalTo(__VA_ARGS__) +#define greaterThanOrEqualTo(...) mas_greaterThanOrEqualTo(__VA_ARGS__) +#define lessThanOrEqualTo(...) mas_lessThanOrEqualTo(__VA_ARGS__) + +#define offset(...) mas_offset(__VA_ARGS__) + +#endif + + +@interface MASConstraint (AutoboxingSupport) + +/** + * Aliases to corresponding relation methods (for shorthand macros) + * Also needed to aid autocompletion + */ +- (MASConstraint * (^)(id attr))mas_equalTo; +- (MASConstraint * (^)(id attr))mas_greaterThanOrEqualTo; +- (MASConstraint * (^)(id attr))mas_lessThanOrEqualTo; + +/** + * A dummy method to aid autocompletion + */ +- (MASConstraint * (^)(id offset))mas_offset; + +@end diff --git a/Pods/Masonry/Masonry/MASConstraint.m b/Pods/Masonry/Masonry/MASConstraint.m new file mode 100644 index 0000000..f24ec10 --- /dev/null +++ b/Pods/Masonry/Masonry/MASConstraint.m @@ -0,0 +1,292 @@ +// +// MASConstraint.m +// Masonry +// +// Created by Nick Tymchenko on 1/20/14. +// + +#import "MASConstraint.h" +#import "MASConstraint+Private.h" + +#define MASMethodNotImplemented() \ + @throw [NSException exceptionWithName:NSInternalInconsistencyException \ + reason:[NSString stringWithFormat:@"You must override %@ in a subclass.", NSStringFromSelector(_cmd)] \ + userInfo:nil] + +@implementation MASConstraint + +#pragma mark - Init + +- (id)init { + NSAssert(![self isMemberOfClass:[MASConstraint class]], @"MASConstraint is an abstract class, you should not instantiate it directly."); + return [super init]; +} + +#pragma mark - NSLayoutRelation proxies + +- (MASConstraint * (^)(id))equalTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationEqual); + }; +} + +- (MASConstraint * (^)(id))mas_equalTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationEqual); + }; +} + +- (MASConstraint * (^)(id))greaterThanOrEqualTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationGreaterThanOrEqual); + }; +} + +- (MASConstraint * (^)(id))mas_greaterThanOrEqualTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationGreaterThanOrEqual); + }; +} + +- (MASConstraint * (^)(id))lessThanOrEqualTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationLessThanOrEqual); + }; +} + +- (MASConstraint * (^)(id))mas_lessThanOrEqualTo { + return ^id(id attribute) { + return self.equalToWithRelation(attribute, NSLayoutRelationLessThanOrEqual); + }; +} + +#pragma mark - MASLayoutPriority proxies + +- (MASConstraint * (^)())priorityLow { + return ^id{ + self.priority(MASLayoutPriorityDefaultLow); + return self; + }; +} + +- (MASConstraint * (^)())priorityMedium { + return ^id{ + self.priority(MASLayoutPriorityDefaultMedium); + return self; + }; +} + +- (MASConstraint * (^)())priorityHigh { + return ^id{ + self.priority(MASLayoutPriorityDefaultHigh); + return self; + }; +} + +#pragma mark - NSLayoutConstraint constant proxies + +- (MASConstraint * (^)(MASEdgeInsets))insets { + return ^id(MASEdgeInsets insets){ + self.insets = insets; + return self; + }; +} + +- (MASConstraint * (^)(CGSize))sizeOffset { + return ^id(CGSize offset) { + self.sizeOffset = offset; + return self; + }; +} + +- (MASConstraint * (^)(CGPoint))centerOffset { + return ^id(CGPoint offset) { + self.centerOffset = offset; + return self; + }; +} + +- (MASConstraint * (^)(CGFloat))offset { + return ^id(CGFloat offset){ + self.offset = offset; + return self; + }; +} + +- (MASConstraint * (^)(NSValue *value))valueOffset { + return ^id(NSValue *offset) { + NSAssert([offset isKindOfClass:NSValue.class], @"expected an NSValue offset, got: %@", offset); + [self setLayoutConstantWithValue:offset]; + return self; + }; +} + +- (MASConstraint * (^)(id offset))mas_offset { + // Will never be called due to macro + return nil; +} + +#pragma mark - NSLayoutConstraint constant setter + +- (void)setLayoutConstantWithValue:(NSValue *)value { + if ([value isKindOfClass:NSNumber.class]) { + self.offset = [(NSNumber *)value doubleValue]; + } else if (strcmp(value.objCType, @encode(CGPoint)) == 0) { + CGPoint point; + [value getValue:&point]; + self.centerOffset = point; + } else if (strcmp(value.objCType, @encode(CGSize)) == 0) { + CGSize size; + [value getValue:&size]; + self.sizeOffset = size; + } else if (strcmp(value.objCType, @encode(MASEdgeInsets)) == 0) { + MASEdgeInsets insets; + [value getValue:&insets]; + self.insets = insets; + } else { + NSAssert(NO, @"attempting to set layout constant with unsupported value: %@", value); + } +} + +#pragma mark - Semantic properties + +- (MASConstraint *)with { + return self; +} + +- (MASConstraint *)and { + return self; +} + +#pragma mark - Chaining + +- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute __unused)layoutAttribute { + MASMethodNotImplemented(); +} + +- (MASConstraint *)left { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft]; +} + +- (MASConstraint *)top { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTop]; +} + +- (MASConstraint *)right { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRight]; +} + +- (MASConstraint *)bottom { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottom]; +} + +- (MASConstraint *)leading { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeading]; +} + +- (MASConstraint *)trailing { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailing]; +} + +- (MASConstraint *)width { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeWidth]; +} + +- (MASConstraint *)height { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeHeight]; +} + +- (MASConstraint *)centerX { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterX]; +} + +- (MASConstraint *)centerY { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterY]; +} + +- (MASConstraint *)baseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBaseline]; +} + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +- (MASConstraint *)firstBaseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeFirstBaseline]; +} +- (MASConstraint *)lastBaseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLastBaseline]; +} + +#endif + +#if TARGET_OS_IPHONE || TARGET_OS_TV + +- (MASConstraint *)leftMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeftMargin]; +} + +- (MASConstraint *)rightMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRightMargin]; +} + +- (MASConstraint *)topMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTopMargin]; +} + +- (MASConstraint *)bottomMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottomMargin]; +} + +- (MASConstraint *)leadingMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeadingMargin]; +} + +- (MASConstraint *)trailingMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailingMargin]; +} + +- (MASConstraint *)centerXWithinMargins { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterXWithinMargins]; +} + +- (MASConstraint *)centerYWithinMargins { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterYWithinMargins]; +} + +#endif + +#pragma mark - Abstract + +- (MASConstraint * (^)(CGFloat multiplier))multipliedBy { MASMethodNotImplemented(); } + +- (MASConstraint * (^)(CGFloat divider))dividedBy { MASMethodNotImplemented(); } + +- (MASConstraint * (^)(MASLayoutPriority priority))priority { MASMethodNotImplemented(); } + +- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { MASMethodNotImplemented(); } + +- (MASConstraint * (^)(id key))key { MASMethodNotImplemented(); } + +- (void)setInsets:(MASEdgeInsets __unused)insets { MASMethodNotImplemented(); } + +- (void)setSizeOffset:(CGSize __unused)sizeOffset { MASMethodNotImplemented(); } + +- (void)setCenterOffset:(CGPoint __unused)centerOffset { MASMethodNotImplemented(); } + +- (void)setOffset:(CGFloat __unused)offset { MASMethodNotImplemented(); } + +#if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) + +- (MASConstraint *)animator { MASMethodNotImplemented(); } + +#endif + +- (void)activate { MASMethodNotImplemented(); } + +- (void)deactivate { MASMethodNotImplemented(); } + +- (void)install { MASMethodNotImplemented(); } + +- (void)uninstall { MASMethodNotImplemented(); } + +@end diff --git a/Pods/Masonry/Masonry/MASConstraintMaker.h b/Pods/Masonry/Masonry/MASConstraintMaker.h new file mode 100644 index 0000000..8f72b4c --- /dev/null +++ b/Pods/Masonry/Masonry/MASConstraintMaker.h @@ -0,0 +1,146 @@ +// +// MASConstraintBuilder.h +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASConstraint.h" +#import "MASUtilities.h" + +typedef NS_OPTIONS(NSInteger, MASAttribute) { + MASAttributeLeft = 1 << NSLayoutAttributeLeft, + MASAttributeRight = 1 << NSLayoutAttributeRight, + MASAttributeTop = 1 << NSLayoutAttributeTop, + MASAttributeBottom = 1 << NSLayoutAttributeBottom, + MASAttributeLeading = 1 << NSLayoutAttributeLeading, + MASAttributeTrailing = 1 << NSLayoutAttributeTrailing, + MASAttributeWidth = 1 << NSLayoutAttributeWidth, + MASAttributeHeight = 1 << NSLayoutAttributeHeight, + MASAttributeCenterX = 1 << NSLayoutAttributeCenterX, + MASAttributeCenterY = 1 << NSLayoutAttributeCenterY, + MASAttributeBaseline = 1 << NSLayoutAttributeBaseline, + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + + MASAttributeFirstBaseline = 1 << NSLayoutAttributeFirstBaseline, + MASAttributeLastBaseline = 1 << NSLayoutAttributeLastBaseline, + +#endif + +#if TARGET_OS_IPHONE || TARGET_OS_TV + + MASAttributeLeftMargin = 1 << NSLayoutAttributeLeftMargin, + MASAttributeRightMargin = 1 << NSLayoutAttributeRightMargin, + MASAttributeTopMargin = 1 << NSLayoutAttributeTopMargin, + MASAttributeBottomMargin = 1 << NSLayoutAttributeBottomMargin, + MASAttributeLeadingMargin = 1 << NSLayoutAttributeLeadingMargin, + MASAttributeTrailingMargin = 1 << NSLayoutAttributeTrailingMargin, + MASAttributeCenterXWithinMargins = 1 << NSLayoutAttributeCenterXWithinMargins, + MASAttributeCenterYWithinMargins = 1 << NSLayoutAttributeCenterYWithinMargins, + +#endif + +}; + +/** + * Provides factory methods for creating MASConstraints. + * Constraints are collected until they are ready to be installed + * + */ +@interface MASConstraintMaker : NSObject + +/** + * The following properties return a new MASViewConstraint + * with the first item set to the makers associated view and the appropriate MASViewAttribute + */ +@property (nonatomic, strong, readonly) MASConstraint *left; +@property (nonatomic, strong, readonly) MASConstraint *top; +@property (nonatomic, strong, readonly) MASConstraint *right; +@property (nonatomic, strong, readonly) MASConstraint *bottom; +@property (nonatomic, strong, readonly) MASConstraint *leading; +@property (nonatomic, strong, readonly) MASConstraint *trailing; +@property (nonatomic, strong, readonly) MASConstraint *width; +@property (nonatomic, strong, readonly) MASConstraint *height; +@property (nonatomic, strong, readonly) MASConstraint *centerX; +@property (nonatomic, strong, readonly) MASConstraint *centerY; +@property (nonatomic, strong, readonly) MASConstraint *baseline; + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +@property (nonatomic, strong, readonly) MASConstraint *firstBaseline; +@property (nonatomic, strong, readonly) MASConstraint *lastBaseline; + +#endif + +#if TARGET_OS_IPHONE || TARGET_OS_TV + +@property (nonatomic, strong, readonly) MASConstraint *leftMargin; +@property (nonatomic, strong, readonly) MASConstraint *rightMargin; +@property (nonatomic, strong, readonly) MASConstraint *topMargin; +@property (nonatomic, strong, readonly) MASConstraint *bottomMargin; +@property (nonatomic, strong, readonly) MASConstraint *leadingMargin; +@property (nonatomic, strong, readonly) MASConstraint *trailingMargin; +@property (nonatomic, strong, readonly) MASConstraint *centerXWithinMargins; +@property (nonatomic, strong, readonly) MASConstraint *centerYWithinMargins; + +#endif + +/** + * Returns a block which creates a new MASCompositeConstraint with the first item set + * to the makers associated view and children corresponding to the set bits in the + * MASAttribute parameter. Combine multiple attributes via binary-or. + */ +@property (nonatomic, strong, readonly) MASConstraint *(^attributes)(MASAttribute attrs); + +/** + * Creates a MASCompositeConstraint with type MASCompositeConstraintTypeEdges + * which generates the appropriate MASViewConstraint children (top, left, bottom, right) + * with the first item set to the makers associated view + */ +@property (nonatomic, strong, readonly) MASConstraint *edges; + +/** + * Creates a MASCompositeConstraint with type MASCompositeConstraintTypeSize + * which generates the appropriate MASViewConstraint children (width, height) + * with the first item set to the makers associated view + */ +@property (nonatomic, strong, readonly) MASConstraint *size; + +/** + * Creates a MASCompositeConstraint with type MASCompositeConstraintTypeCenter + * which generates the appropriate MASViewConstraint children (centerX, centerY) + * with the first item set to the makers associated view + */ +@property (nonatomic, strong, readonly) MASConstraint *center; + +/** + * Whether or not to check for an existing constraint instead of adding constraint + */ +@property (nonatomic, assign) BOOL updateExisting; + +/** + * Whether or not to remove existing constraints prior to installing + */ +@property (nonatomic, assign) BOOL removeExisting; + +/** + * initialises the maker with a default view + * + * @param view any MASConstrait are created with this view as the first item + * + * @return a new MASConstraintMaker + */ +- (id)initWithView:(MAS_VIEW *)view; + +/** + * Calls install method on any MASConstraints which have been created by this maker + * + * @return an array of all the installed MASConstraints + */ +- (NSArray *)install; + +- (MASConstraint * (^)(dispatch_block_t))group; + +@end diff --git a/Pods/Masonry/Masonry/MASConstraintMaker.m b/Pods/Masonry/Masonry/MASConstraintMaker.m new file mode 100644 index 0000000..6e40a26 --- /dev/null +++ b/Pods/Masonry/Masonry/MASConstraintMaker.m @@ -0,0 +1,273 @@ +// +// MASConstraintBuilder.m +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASConstraintMaker.h" +#import "MASViewConstraint.h" +#import "MASCompositeConstraint.h" +#import "MASConstraint+Private.h" +#import "MASViewAttribute.h" +#import "View+MASAdditions.h" + +@interface MASConstraintMaker () + +@property (nonatomic, weak) MAS_VIEW *view; +@property (nonatomic, strong) NSMutableArray *constraints; + +@end + +@implementation MASConstraintMaker + +- (id)initWithView:(MAS_VIEW *)view { + self = [super init]; + if (!self) return nil; + + self.view = view; + self.constraints = NSMutableArray.new; + + return self; +} + +- (NSArray *)install { + if (self.removeExisting) { + NSArray *installedConstraints = [MASViewConstraint installedConstraintsForView:self.view]; + for (MASConstraint *constraint in installedConstraints) { + [constraint uninstall]; + } + } + NSArray *constraints = self.constraints.copy; + for (MASConstraint *constraint in constraints) { + constraint.updateExisting = self.updateExisting; + [constraint install]; + } + [self.constraints removeAllObjects]; + return constraints; +} + +#pragma mark - MASConstraintDelegate + +- (void)constraint:(MASConstraint *)constraint shouldBeReplacedWithConstraint:(MASConstraint *)replacementConstraint { + NSUInteger index = [self.constraints indexOfObject:constraint]; + NSAssert(index != NSNotFound, @"Could not find constraint %@", constraint); + [self.constraints replaceObjectAtIndex:index withObject:replacementConstraint]; +} + +- (MASConstraint *)constraint:(MASConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { + MASViewAttribute *viewAttribute = [[MASViewAttribute alloc] initWithView:self.view layoutAttribute:layoutAttribute]; + MASViewConstraint *newConstraint = [[MASViewConstraint alloc] initWithFirstViewAttribute:viewAttribute]; + if ([constraint isKindOfClass:MASViewConstraint.class]) { + //replace with composite constraint + NSArray *children = @[constraint, newConstraint]; + MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children]; + compositeConstraint.delegate = self; + [self constraint:constraint shouldBeReplacedWithConstraint:compositeConstraint]; + return compositeConstraint; + } + if (!constraint) { + newConstraint.delegate = self; + [self.constraints addObject:newConstraint]; + } + return newConstraint; +} + +- (MASConstraint *)addConstraintWithAttributes:(MASAttribute)attrs { + __unused MASAttribute anyAttribute = (MASAttributeLeft | MASAttributeRight | MASAttributeTop | MASAttributeBottom | MASAttributeLeading + | MASAttributeTrailing | MASAttributeWidth | MASAttributeHeight | MASAttributeCenterX + | MASAttributeCenterY | MASAttributeBaseline +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + | MASAttributeFirstBaseline | MASAttributeLastBaseline +#endif +#if TARGET_OS_IPHONE || TARGET_OS_TV + | MASAttributeLeftMargin | MASAttributeRightMargin | MASAttributeTopMargin | MASAttributeBottomMargin + | MASAttributeLeadingMargin | MASAttributeTrailingMargin | MASAttributeCenterXWithinMargins + | MASAttributeCenterYWithinMargins +#endif + ); + + NSAssert((attrs & anyAttribute) != 0, @"You didn't pass any attribute to make.attributes(...)"); + + NSMutableArray *attributes = [NSMutableArray array]; + + if (attrs & MASAttributeLeft) [attributes addObject:self.view.mas_left]; + if (attrs & MASAttributeRight) [attributes addObject:self.view.mas_right]; + if (attrs & MASAttributeTop) [attributes addObject:self.view.mas_top]; + if (attrs & MASAttributeBottom) [attributes addObject:self.view.mas_bottom]; + if (attrs & MASAttributeLeading) [attributes addObject:self.view.mas_leading]; + if (attrs & MASAttributeTrailing) [attributes addObject:self.view.mas_trailing]; + if (attrs & MASAttributeWidth) [attributes addObject:self.view.mas_width]; + if (attrs & MASAttributeHeight) [attributes addObject:self.view.mas_height]; + if (attrs & MASAttributeCenterX) [attributes addObject:self.view.mas_centerX]; + if (attrs & MASAttributeCenterY) [attributes addObject:self.view.mas_centerY]; + if (attrs & MASAttributeBaseline) [attributes addObject:self.view.mas_baseline]; + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + + if (attrs & MASAttributeFirstBaseline) [attributes addObject:self.view.mas_firstBaseline]; + if (attrs & MASAttributeLastBaseline) [attributes addObject:self.view.mas_lastBaseline]; + +#endif + +#if TARGET_OS_IPHONE || TARGET_OS_TV + + if (attrs & MASAttributeLeftMargin) [attributes addObject:self.view.mas_leftMargin]; + if (attrs & MASAttributeRightMargin) [attributes addObject:self.view.mas_rightMargin]; + if (attrs & MASAttributeTopMargin) [attributes addObject:self.view.mas_topMargin]; + if (attrs & MASAttributeBottomMargin) [attributes addObject:self.view.mas_bottomMargin]; + if (attrs & MASAttributeLeadingMargin) [attributes addObject:self.view.mas_leadingMargin]; + if (attrs & MASAttributeTrailingMargin) [attributes addObject:self.view.mas_trailingMargin]; + if (attrs & MASAttributeCenterXWithinMargins) [attributes addObject:self.view.mas_centerXWithinMargins]; + if (attrs & MASAttributeCenterYWithinMargins) [attributes addObject:self.view.mas_centerYWithinMargins]; + +#endif + + NSMutableArray *children = [NSMutableArray arrayWithCapacity:attributes.count]; + + for (MASViewAttribute *a in attributes) { + [children addObject:[[MASViewConstraint alloc] initWithFirstViewAttribute:a]]; + } + + MASCompositeConstraint *constraint = [[MASCompositeConstraint alloc] initWithChildren:children]; + constraint.delegate = self; + [self.constraints addObject:constraint]; + return constraint; +} + +#pragma mark - standard Attributes + +- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { + return [self constraint:nil addConstraintWithLayoutAttribute:layoutAttribute]; +} + +- (MASConstraint *)left { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft]; +} + +- (MASConstraint *)top { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTop]; +} + +- (MASConstraint *)right { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRight]; +} + +- (MASConstraint *)bottom { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottom]; +} + +- (MASConstraint *)leading { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeading]; +} + +- (MASConstraint *)trailing { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailing]; +} + +- (MASConstraint *)width { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeWidth]; +} + +- (MASConstraint *)height { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeHeight]; +} + +- (MASConstraint *)centerX { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterX]; +} + +- (MASConstraint *)centerY { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterY]; +} + +- (MASConstraint *)baseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBaseline]; +} + +- (MASConstraint *(^)(MASAttribute))attributes { + return ^(MASAttribute attrs){ + return [self addConstraintWithAttributes:attrs]; + }; +} + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +- (MASConstraint *)firstBaseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeFirstBaseline]; +} + +- (MASConstraint *)lastBaseline { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLastBaseline]; +} + +#endif + + +#if TARGET_OS_IPHONE || TARGET_OS_TV + +- (MASConstraint *)leftMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeftMargin]; +} + +- (MASConstraint *)rightMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeRightMargin]; +} + +- (MASConstraint *)topMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTopMargin]; +} + +- (MASConstraint *)bottomMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeBottomMargin]; +} + +- (MASConstraint *)leadingMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeadingMargin]; +} + +- (MASConstraint *)trailingMargin { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeTrailingMargin]; +} + +- (MASConstraint *)centerXWithinMargins { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterXWithinMargins]; +} + +- (MASConstraint *)centerYWithinMargins { + return [self addConstraintWithLayoutAttribute:NSLayoutAttributeCenterYWithinMargins]; +} + +#endif + + +#pragma mark - composite Attributes + +- (MASConstraint *)edges { + return [self addConstraintWithAttributes:MASAttributeTop | MASAttributeLeft | MASAttributeRight | MASAttributeBottom]; +} + +- (MASConstraint *)size { + return [self addConstraintWithAttributes:MASAttributeWidth | MASAttributeHeight]; +} + +- (MASConstraint *)center { + return [self addConstraintWithAttributes:MASAttributeCenterX | MASAttributeCenterY]; +} + +#pragma mark - grouping + +- (MASConstraint *(^)(dispatch_block_t group))group { + return ^id(dispatch_block_t group) { + NSInteger previousCount = self.constraints.count; + group(); + + NSArray *children = [self.constraints subarrayWithRange:NSMakeRange(previousCount, self.constraints.count - previousCount)]; + MASCompositeConstraint *constraint = [[MASCompositeConstraint alloc] initWithChildren:children]; + constraint.delegate = self; + return constraint; + }; +} + +@end diff --git a/Pods/Masonry/Masonry/MASLayoutConstraint.h b/Pods/Masonry/Masonry/MASLayoutConstraint.h new file mode 100644 index 0000000..699041c --- /dev/null +++ b/Pods/Masonry/Masonry/MASLayoutConstraint.h @@ -0,0 +1,22 @@ +// +// MASLayoutConstraint.h +// Masonry +// +// Created by Jonas Budelmann on 3/08/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "MASUtilities.h" + +/** + * When you are debugging or printing the constraints attached to a view this subclass + * makes it easier to identify which constraints have been created via Masonry + */ +@interface MASLayoutConstraint : NSLayoutConstraint + +/** + * a key to associate with this constraint + */ +@property (nonatomic, strong) id mas_key; + +@end diff --git a/Pods/Masonry/Masonry/MASLayoutConstraint.m b/Pods/Masonry/Masonry/MASLayoutConstraint.m new file mode 100644 index 0000000..3483f02 --- /dev/null +++ b/Pods/Masonry/Masonry/MASLayoutConstraint.m @@ -0,0 +1,13 @@ +// +// MASLayoutConstraint.m +// Masonry +// +// Created by Jonas Budelmann on 3/08/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "MASLayoutConstraint.h" + +@implementation MASLayoutConstraint + +@end diff --git a/Pods/Masonry/Masonry/MASUtilities.h b/Pods/Masonry/Masonry/MASUtilities.h new file mode 100644 index 0000000..1dbfd93 --- /dev/null +++ b/Pods/Masonry/Masonry/MASUtilities.h @@ -0,0 +1,136 @@ +// +// MASUtilities.h +// Masonry +// +// Created by Jonas Budelmann on 19/08/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import + + + +#if TARGET_OS_IPHONE || TARGET_OS_TV + + #import + #define MAS_VIEW UIView + #define MAS_VIEW_CONTROLLER UIViewController + #define MASEdgeInsets UIEdgeInsets + + typedef UILayoutPriority MASLayoutPriority; + static const MASLayoutPriority MASLayoutPriorityRequired = UILayoutPriorityRequired; + static const MASLayoutPriority MASLayoutPriorityDefaultHigh = UILayoutPriorityDefaultHigh; + static const MASLayoutPriority MASLayoutPriorityDefaultMedium = 500; + static const MASLayoutPriority MASLayoutPriorityDefaultLow = UILayoutPriorityDefaultLow; + static const MASLayoutPriority MASLayoutPriorityFittingSizeLevel = UILayoutPriorityFittingSizeLevel; + +#elif TARGET_OS_MAC + + #import + #define MAS_VIEW NSView + #define MASEdgeInsets NSEdgeInsets + + typedef NSLayoutPriority MASLayoutPriority; + static const MASLayoutPriority MASLayoutPriorityRequired = NSLayoutPriorityRequired; + static const MASLayoutPriority MASLayoutPriorityDefaultHigh = NSLayoutPriorityDefaultHigh; + static const MASLayoutPriority MASLayoutPriorityDragThatCanResizeWindow = NSLayoutPriorityDragThatCanResizeWindow; + static const MASLayoutPriority MASLayoutPriorityDefaultMedium = 501; + static const MASLayoutPriority MASLayoutPriorityWindowSizeStayPut = NSLayoutPriorityWindowSizeStayPut; + static const MASLayoutPriority MASLayoutPriorityDragThatCannotResizeWindow = NSLayoutPriorityDragThatCannotResizeWindow; + static const MASLayoutPriority MASLayoutPriorityDefaultLow = NSLayoutPriorityDefaultLow; + static const MASLayoutPriority MASLayoutPriorityFittingSizeCompression = NSLayoutPriorityFittingSizeCompression; + +#endif + +/** + * Allows you to attach keys to objects matching the variable names passed. + * + * view1.mas_key = @"view1", view2.mas_key = @"view2"; + * + * is equivalent to: + * + * MASAttachKeys(view1, view2); + */ +#define MASAttachKeys(...) \ + { \ + NSDictionary *keyPairs = NSDictionaryOfVariableBindings(__VA_ARGS__); \ + for (id key in keyPairs.allKeys) { \ + id obj = keyPairs[key]; \ + NSAssert([obj respondsToSelector:@selector(setMas_key:)], \ + @"Cannot attach mas_key to %@", obj); \ + [obj setMas_key:key]; \ + } \ + } + +/** + * Used to create object hashes + * Based on http://www.mikeash.com/pyblog/friday-qa-2010-06-18-implementing-equality-and-hashing.html + */ +#define MAS_NSUINT_BIT (CHAR_BIT * sizeof(NSUInteger)) +#define MAS_NSUINTROTATE(val, howmuch) ((((NSUInteger)val) << howmuch) | (((NSUInteger)val) >> (MAS_NSUINT_BIT - howmuch))) + +/** + * Given a scalar or struct value, wraps it in NSValue + * Based on EXPObjectify: https://github.com/specta/expecta + */ +static inline id _MASBoxValue(const char *type, ...) { + va_list v; + va_start(v, type); + id obj = nil; + if (strcmp(type, @encode(id)) == 0) { + id actual = va_arg(v, id); + obj = actual; + } else if (strcmp(type, @encode(CGPoint)) == 0) { + CGPoint actual = (CGPoint)va_arg(v, CGPoint); + obj = [NSValue value:&actual withObjCType:type]; + } else if (strcmp(type, @encode(CGSize)) == 0) { + CGSize actual = (CGSize)va_arg(v, CGSize); + obj = [NSValue value:&actual withObjCType:type]; + } else if (strcmp(type, @encode(MASEdgeInsets)) == 0) { + MASEdgeInsets actual = (MASEdgeInsets)va_arg(v, MASEdgeInsets); + obj = [NSValue value:&actual withObjCType:type]; + } else if (strcmp(type, @encode(double)) == 0) { + double actual = (double)va_arg(v, double); + obj = [NSNumber numberWithDouble:actual]; + } else if (strcmp(type, @encode(float)) == 0) { + float actual = (float)va_arg(v, double); + obj = [NSNumber numberWithFloat:actual]; + } else if (strcmp(type, @encode(int)) == 0) { + int actual = (int)va_arg(v, int); + obj = [NSNumber numberWithInt:actual]; + } else if (strcmp(type, @encode(long)) == 0) { + long actual = (long)va_arg(v, long); + obj = [NSNumber numberWithLong:actual]; + } else if (strcmp(type, @encode(long long)) == 0) { + long long actual = (long long)va_arg(v, long long); + obj = [NSNumber numberWithLongLong:actual]; + } else if (strcmp(type, @encode(short)) == 0) { + short actual = (short)va_arg(v, int); + obj = [NSNumber numberWithShort:actual]; + } else if (strcmp(type, @encode(char)) == 0) { + char actual = (char)va_arg(v, int); + obj = [NSNumber numberWithChar:actual]; + } else if (strcmp(type, @encode(bool)) == 0) { + bool actual = (bool)va_arg(v, int); + obj = [NSNumber numberWithBool:actual]; + } else if (strcmp(type, @encode(unsigned char)) == 0) { + unsigned char actual = (unsigned char)va_arg(v, unsigned int); + obj = [NSNumber numberWithUnsignedChar:actual]; + } else if (strcmp(type, @encode(unsigned int)) == 0) { + unsigned int actual = (unsigned int)va_arg(v, unsigned int); + obj = [NSNumber numberWithUnsignedInt:actual]; + } else if (strcmp(type, @encode(unsigned long)) == 0) { + unsigned long actual = (unsigned long)va_arg(v, unsigned long); + obj = [NSNumber numberWithUnsignedLong:actual]; + } else if (strcmp(type, @encode(unsigned long long)) == 0) { + unsigned long long actual = (unsigned long long)va_arg(v, unsigned long long); + obj = [NSNumber numberWithUnsignedLongLong:actual]; + } else if (strcmp(type, @encode(unsigned short)) == 0) { + unsigned short actual = (unsigned short)va_arg(v, unsigned int); + obj = [NSNumber numberWithUnsignedShort:actual]; + } + va_end(v); + return obj; +} + +#define MASBoxValue(value) _MASBoxValue(@encode(__typeof__((value))), (value)) diff --git a/Pods/Masonry/Masonry/MASViewAttribute.h b/Pods/Masonry/Masonry/MASViewAttribute.h new file mode 100644 index 0000000..f8eb700 --- /dev/null +++ b/Pods/Masonry/Masonry/MASViewAttribute.h @@ -0,0 +1,49 @@ +// +// MASAttribute.h +// Masonry +// +// Created by Jonas Budelmann on 21/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASUtilities.h" + +/** + * An immutable tuple which stores the view and the related NSLayoutAttribute. + * Describes part of either the left or right hand side of a constraint equation + */ +@interface MASViewAttribute : NSObject + +/** + * The view which the reciever relates to. Can be nil if item is not a view. + */ +@property (nonatomic, weak, readonly) MAS_VIEW *view; + +/** + * The item which the reciever relates to. + */ +@property (nonatomic, weak, readonly) id item; + +/** + * The attribute which the reciever relates to + */ +@property (nonatomic, assign, readonly) NSLayoutAttribute layoutAttribute; + +/** + * Convenience initializer. + */ +- (id)initWithView:(MAS_VIEW *)view layoutAttribute:(NSLayoutAttribute)layoutAttribute; + +/** + * The designated initializer. + */ +- (id)initWithView:(MAS_VIEW *)view item:(id)item layoutAttribute:(NSLayoutAttribute)layoutAttribute; + +/** + * Determine whether the layoutAttribute is a size attribute + * + * @return YES if layoutAttribute is equal to NSLayoutAttributeWidth or NSLayoutAttributeHeight + */ +- (BOOL)isSizeAttribute; + +@end diff --git a/Pods/Masonry/Masonry/MASViewAttribute.m b/Pods/Masonry/Masonry/MASViewAttribute.m new file mode 100644 index 0000000..7131025 --- /dev/null +++ b/Pods/Masonry/Masonry/MASViewAttribute.m @@ -0,0 +1,46 @@ +// +// MASAttribute.m +// Masonry +// +// Created by Jonas Budelmann on 21/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASViewAttribute.h" + +@implementation MASViewAttribute + +- (id)initWithView:(MAS_VIEW *)view layoutAttribute:(NSLayoutAttribute)layoutAttribute { + self = [self initWithView:view item:view layoutAttribute:layoutAttribute]; + return self; +} + +- (id)initWithView:(MAS_VIEW *)view item:(id)item layoutAttribute:(NSLayoutAttribute)layoutAttribute { + self = [super init]; + if (!self) return nil; + + _view = view; + _item = item; + _layoutAttribute = layoutAttribute; + + return self; +} + +- (BOOL)isSizeAttribute { + return self.layoutAttribute == NSLayoutAttributeWidth + || self.layoutAttribute == NSLayoutAttributeHeight; +} + +- (BOOL)isEqual:(MASViewAttribute *)viewAttribute { + if ([viewAttribute isKindOfClass:self.class]) { + return self.view == viewAttribute.view + && self.layoutAttribute == viewAttribute.layoutAttribute; + } + return [super isEqual:viewAttribute]; +} + +- (NSUInteger)hash { + return MAS_NSUINTROTATE([self.view hash], MAS_NSUINT_BIT / 2) ^ self.layoutAttribute; +} + +@end diff --git a/Pods/Masonry/Masonry/MASViewConstraint.h b/Pods/Masonry/Masonry/MASViewConstraint.h new file mode 100644 index 0000000..5c78f7a --- /dev/null +++ b/Pods/Masonry/Masonry/MASViewConstraint.h @@ -0,0 +1,48 @@ +// +// MASConstraint.h +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASViewAttribute.h" +#import "MASConstraint.h" +#import "MASLayoutConstraint.h" +#import "MASUtilities.h" + +/** + * A single constraint. + * Contains the attributes neccessary for creating a NSLayoutConstraint and adding it to the appropriate view + */ +@interface MASViewConstraint : MASConstraint + +/** + * First item/view and first attribute of the NSLayoutConstraint + */ +@property (nonatomic, strong, readonly) MASViewAttribute *firstViewAttribute; + +/** + * Second item/view and second attribute of the NSLayoutConstraint + */ +@property (nonatomic, strong, readonly) MASViewAttribute *secondViewAttribute; + +/** + * initialises the MASViewConstraint with the first part of the equation + * + * @param firstViewAttribute view.mas_left, view.mas_width etc. + * + * @return a new view constraint + */ +- (id)initWithFirstViewAttribute:(MASViewAttribute *)firstViewAttribute; + +/** + * Returns all MASViewConstraints installed with this view as a first item. + * + * @param view A view to retrieve constraints for. + * + * @return An array of MASViewConstraints. + */ ++ (NSArray *)installedConstraintsForView:(MAS_VIEW *)view; + +@end diff --git a/Pods/Masonry/Masonry/MASViewConstraint.m b/Pods/Masonry/Masonry/MASViewConstraint.m new file mode 100644 index 0000000..84a801e --- /dev/null +++ b/Pods/Masonry/Masonry/MASViewConstraint.m @@ -0,0 +1,397 @@ +// +// MASConstraint.m +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASViewConstraint.h" +#import "MASConstraint+Private.h" +#import "MASCompositeConstraint.h" +#import "MASLayoutConstraint.h" +#import "View+MASAdditions.h" +#import + +@interface MAS_VIEW (MASConstraints) + +@property (nonatomic, readonly) NSMutableSet *mas_installedConstraints; + +@end + +@implementation MAS_VIEW (MASConstraints) + +static char kInstalledConstraintsKey; + +- (NSMutableSet *)mas_installedConstraints { + NSMutableSet *constraints = objc_getAssociatedObject(self, &kInstalledConstraintsKey); + if (!constraints) { + constraints = [NSMutableSet set]; + objc_setAssociatedObject(self, &kInstalledConstraintsKey, constraints, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return constraints; +} + +@end + + +@interface MASViewConstraint () + +@property (nonatomic, strong, readwrite) MASViewAttribute *secondViewAttribute; +@property (nonatomic, weak) MAS_VIEW *installedView; +@property (nonatomic, weak) MASLayoutConstraint *layoutConstraint; +@property (nonatomic, assign) NSLayoutRelation layoutRelation; +@property (nonatomic, assign) MASLayoutPriority layoutPriority; +@property (nonatomic, assign) CGFloat layoutMultiplier; +@property (nonatomic, assign) CGFloat layoutConstant; +@property (nonatomic, assign) BOOL hasLayoutRelation; +@property (nonatomic, strong) id mas_key; +@property (nonatomic, assign) BOOL useAnimator; + +@end + +@implementation MASViewConstraint + +- (id)initWithFirstViewAttribute:(MASViewAttribute *)firstViewAttribute { + self = [super init]; + if (!self) return nil; + + _firstViewAttribute = firstViewAttribute; + self.layoutPriority = MASLayoutPriorityRequired; + self.layoutMultiplier = 1; + + return self; +} + +#pragma mark - NSCoping + +- (id)copyWithZone:(NSZone __unused *)zone { + MASViewConstraint *constraint = [[MASViewConstraint alloc] initWithFirstViewAttribute:self.firstViewAttribute]; + constraint.layoutConstant = self.layoutConstant; + constraint.layoutRelation = self.layoutRelation; + constraint.layoutPriority = self.layoutPriority; + constraint.layoutMultiplier = self.layoutMultiplier; + constraint.delegate = self.delegate; + return constraint; +} + +#pragma mark - Public + ++ (NSArray *)installedConstraintsForView:(MAS_VIEW *)view { + return [view.mas_installedConstraints allObjects]; +} + +#pragma mark - Private + +- (void)setLayoutConstant:(CGFloat)layoutConstant { + _layoutConstant = layoutConstant; + +#if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) + if (self.useAnimator) { + [self.layoutConstraint.animator setConstant:layoutConstant]; + } else { + self.layoutConstraint.constant = layoutConstant; + } +#else + self.layoutConstraint.constant = layoutConstant; +#endif +} + +- (void)setLayoutRelation:(NSLayoutRelation)layoutRelation { + _layoutRelation = layoutRelation; + self.hasLayoutRelation = YES; +} + +- (BOOL)supportsActiveProperty { + return [self.layoutConstraint respondsToSelector:@selector(isActive)]; +} + +- (BOOL)isActive { + BOOL active = YES; + if ([self supportsActiveProperty]) { + active = [self.layoutConstraint isActive]; + } + + return active; +} + +- (BOOL)hasBeenInstalled { + return (self.layoutConstraint != nil) && [self isActive]; +} + +- (void)setSecondViewAttribute:(id)secondViewAttribute { + if ([secondViewAttribute isKindOfClass:NSValue.class]) { + [self setLayoutConstantWithValue:secondViewAttribute]; + } else if ([secondViewAttribute isKindOfClass:MAS_VIEW.class]) { + _secondViewAttribute = [[MASViewAttribute alloc] initWithView:secondViewAttribute layoutAttribute:self.firstViewAttribute.layoutAttribute]; + } else if ([secondViewAttribute isKindOfClass:MASViewAttribute.class]) { + _secondViewAttribute = secondViewAttribute; + } else { + NSAssert(NO, @"attempting to add unsupported attribute: %@", secondViewAttribute); + } +} + +#pragma mark - NSLayoutConstraint multiplier proxies + +- (MASConstraint * (^)(CGFloat))multipliedBy { + return ^id(CGFloat multiplier) { + NSAssert(!self.hasBeenInstalled, + @"Cannot modify constraint multiplier after it has been installed"); + + self.layoutMultiplier = multiplier; + return self; + }; +} + + +- (MASConstraint * (^)(CGFloat))dividedBy { + return ^id(CGFloat divider) { + NSAssert(!self.hasBeenInstalled, + @"Cannot modify constraint multiplier after it has been installed"); + + self.layoutMultiplier = 1.0/divider; + return self; + }; +} + +#pragma mark - MASLayoutPriority proxy + +- (MASConstraint * (^)(MASLayoutPriority))priority { + return ^id(MASLayoutPriority priority) { + NSAssert(!self.hasBeenInstalled, + @"Cannot modify constraint priority after it has been installed"); + + self.layoutPriority = priority; + return self; + }; +} + +#pragma mark - NSLayoutRelation proxy + +- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { + return ^id(id attribute, NSLayoutRelation relation) { + if ([attribute isKindOfClass:NSArray.class]) { + NSAssert(!self.hasLayoutRelation, @"Redefinition of constraint relation"); + NSMutableArray *children = NSMutableArray.new; + for (id attr in attribute) { + MASViewConstraint *viewConstraint = [self copy]; + viewConstraint.layoutRelation = relation; + viewConstraint.secondViewAttribute = attr; + [children addObject:viewConstraint]; + } + MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children]; + compositeConstraint.delegate = self.delegate; + [self.delegate constraint:self shouldBeReplacedWithConstraint:compositeConstraint]; + return compositeConstraint; + } else { + NSAssert(!self.hasLayoutRelation || self.layoutRelation == relation && [attribute isKindOfClass:NSValue.class], @"Redefinition of constraint relation"); + self.layoutRelation = relation; + self.secondViewAttribute = attribute; + return self; + } + }; +} + +#pragma mark - Semantic properties + +- (MASConstraint *)with { + return self; +} + +- (MASConstraint *)and { + return self; +} + +#pragma mark - attribute chaining + +- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute { + NSAssert(!self.hasLayoutRelation, @"Attributes should be chained before defining the constraint relation"); + + return [self.delegate constraint:self addConstraintWithLayoutAttribute:layoutAttribute]; +} + +#pragma mark - Animator proxy + +#if TARGET_OS_MAC && !(TARGET_OS_IPHONE || TARGET_OS_TV) + +- (MASConstraint *)animator { + self.useAnimator = YES; + return self; +} + +#endif + +#pragma mark - debug helpers + +- (MASConstraint * (^)(id))key { + return ^id(id key) { + self.mas_key = key; + return self; + }; +} + +#pragma mark - NSLayoutConstraint constant setters + +- (void)setInsets:(MASEdgeInsets)insets { + NSLayoutAttribute layoutAttribute = self.firstViewAttribute.layoutAttribute; + switch (layoutAttribute) { + case NSLayoutAttributeLeft: + case NSLayoutAttributeLeading: + self.layoutConstant = insets.left; + break; + case NSLayoutAttributeTop: + self.layoutConstant = insets.top; + break; + case NSLayoutAttributeBottom: + self.layoutConstant = -insets.bottom; + break; + case NSLayoutAttributeRight: + case NSLayoutAttributeTrailing: + self.layoutConstant = -insets.right; + break; + default: + break; + } +} + +- (void)setOffset:(CGFloat)offset { + self.layoutConstant = offset; +} + +- (void)setSizeOffset:(CGSize)sizeOffset { + NSLayoutAttribute layoutAttribute = self.firstViewAttribute.layoutAttribute; + switch (layoutAttribute) { + case NSLayoutAttributeWidth: + self.layoutConstant = sizeOffset.width; + break; + case NSLayoutAttributeHeight: + self.layoutConstant = sizeOffset.height; + break; + default: + break; + } +} + +- (void)setCenterOffset:(CGPoint)centerOffset { + NSLayoutAttribute layoutAttribute = self.firstViewAttribute.layoutAttribute; + switch (layoutAttribute) { + case NSLayoutAttributeCenterX: + self.layoutConstant = centerOffset.x; + break; + case NSLayoutAttributeCenterY: + self.layoutConstant = centerOffset.y; + break; + default: + break; + } +} + +#pragma mark - MASConstraint + +- (void)activate { + [self install]; +} + +- (void)deactivate { + [self uninstall]; +} + +- (void)install { + if (self.hasBeenInstalled) { + return; + } + + if ([self supportsActiveProperty] && self.layoutConstraint) { + self.layoutConstraint.active = YES; + [self.firstViewAttribute.view.mas_installedConstraints addObject:self]; + return; + } + + MAS_VIEW *firstLayoutItem = self.firstViewAttribute.item; + NSLayoutAttribute firstLayoutAttribute = self.firstViewAttribute.layoutAttribute; + MAS_VIEW *secondLayoutItem = self.secondViewAttribute.item; + NSLayoutAttribute secondLayoutAttribute = self.secondViewAttribute.layoutAttribute; + + // alignment attributes must have a secondViewAttribute + // therefore we assume that is refering to superview + // eg make.left.equalTo(@10) + if (!self.firstViewAttribute.isSizeAttribute && !self.secondViewAttribute) { + secondLayoutItem = self.firstViewAttribute.view.superview; + secondLayoutAttribute = firstLayoutAttribute; + } + + MASLayoutConstraint *layoutConstraint + = [MASLayoutConstraint constraintWithItem:firstLayoutItem + attribute:firstLayoutAttribute + relatedBy:self.layoutRelation + toItem:secondLayoutItem + attribute:secondLayoutAttribute + multiplier:self.layoutMultiplier + constant:self.layoutConstant]; + + layoutConstraint.priority = self.layoutPriority; + layoutConstraint.mas_key = self.mas_key; + + if (self.secondViewAttribute.view) { + MAS_VIEW *closestCommonSuperview = [self.firstViewAttribute.view mas_closestCommonSuperview:self.secondViewAttribute.view]; + NSAssert(closestCommonSuperview, + @"couldn't find a common superview for %@ and %@", + self.firstViewAttribute.view, self.secondViewAttribute.view); + self.installedView = closestCommonSuperview; + } else if (self.firstViewAttribute.isSizeAttribute) { + self.installedView = self.firstViewAttribute.view; + } else { + self.installedView = self.firstViewAttribute.view.superview; + } + + + MASLayoutConstraint *existingConstraint = nil; + if (self.updateExisting) { + existingConstraint = [self layoutConstraintSimilarTo:layoutConstraint]; + } + if (existingConstraint) { + // just update the constant + existingConstraint.constant = layoutConstraint.constant; + self.layoutConstraint = existingConstraint; + } else { + [self.installedView addConstraint:layoutConstraint]; + self.layoutConstraint = layoutConstraint; + [firstLayoutItem.mas_installedConstraints addObject:self]; + } +} + +- (MASLayoutConstraint *)layoutConstraintSimilarTo:(MASLayoutConstraint *)layoutConstraint { + // check if any constraints are the same apart from the only mutable property constant + + // go through constraints in reverse as we do not want to match auto-resizing or interface builder constraints + // and they are likely to be added first. + for (NSLayoutConstraint *existingConstraint in self.installedView.constraints.reverseObjectEnumerator) { + if (![existingConstraint isKindOfClass:MASLayoutConstraint.class]) continue; + if (existingConstraint.firstItem != layoutConstraint.firstItem) continue; + if (existingConstraint.secondItem != layoutConstraint.secondItem) continue; + if (existingConstraint.firstAttribute != layoutConstraint.firstAttribute) continue; + if (existingConstraint.secondAttribute != layoutConstraint.secondAttribute) continue; + if (existingConstraint.relation != layoutConstraint.relation) continue; + if (existingConstraint.multiplier != layoutConstraint.multiplier) continue; + if (existingConstraint.priority != layoutConstraint.priority) continue; + + return (id)existingConstraint; + } + return nil; +} + +- (void)uninstall { + if ([self supportsActiveProperty]) { + self.layoutConstraint.active = NO; + [self.firstViewAttribute.view.mas_installedConstraints removeObject:self]; + return; + } + + [self.installedView removeConstraint:self.layoutConstraint]; + self.layoutConstraint = nil; + self.installedView = nil; + + [self.firstViewAttribute.view.mas_installedConstraints removeObject:self]; +} + +@end diff --git a/Pods/Masonry/Masonry/Masonry.h b/Pods/Masonry/Masonry/Masonry.h new file mode 100644 index 0000000..d1bd579 --- /dev/null +++ b/Pods/Masonry/Masonry/Masonry.h @@ -0,0 +1,29 @@ +// +// Masonry.h +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import + +//! Project version number for Masonry. +FOUNDATION_EXPORT double MasonryVersionNumber; + +//! Project version string for Masonry. +FOUNDATION_EXPORT const unsigned char MasonryVersionString[]; + +#import "MASUtilities.h" +#import "View+MASAdditions.h" +#import "View+MASShorthandAdditions.h" +#import "ViewController+MASAdditions.h" +#import "NSArray+MASAdditions.h" +#import "NSArray+MASShorthandAdditions.h" +#import "MASConstraint.h" +#import "MASCompositeConstraint.h" +#import "MASViewAttribute.h" +#import "MASViewConstraint.h" +#import "MASConstraintMaker.h" +#import "MASLayoutConstraint.h" +#import "NSLayoutConstraint+MASDebugAdditions.h" diff --git a/Pods/Masonry/Masonry/NSArray+MASAdditions.h b/Pods/Masonry/Masonry/NSArray+MASAdditions.h new file mode 100644 index 0000000..83be23d --- /dev/null +++ b/Pods/Masonry/Masonry/NSArray+MASAdditions.h @@ -0,0 +1,72 @@ +// +// NSArray+MASAdditions.h +// +// +// Created by Daniel Hammond on 11/26/13. +// +// + +#import "MASUtilities.h" +#import "MASConstraintMaker.h" +#import "MASViewAttribute.h" + +typedef NS_ENUM(NSUInteger, MASAxisType) { + MASAxisTypeHorizontal, + MASAxisTypeVertical +}; + +@interface NSArray (MASAdditions) + +/** + * Creates a MASConstraintMaker with each view in the callee. + * Any constraints defined are added to the view or the appropriate superview once the block has finished executing on each view + * + * @param block scope within which you can build up the constraints which you wish to apply to each view. + * + * @return Array of created MASConstraints + */ +- (NSArray *)mas_makeConstraints:(void (^)(MASConstraintMaker *make))block; + +/** + * Creates a MASConstraintMaker with each view in the callee. + * Any constraints defined are added to each view or the appropriate superview once the block has finished executing on each view. + * If an existing constraint exists then it will be updated instead. + * + * @param block scope within which you can build up the constraints which you wish to apply to each view. + * + * @return Array of created/updated MASConstraints + */ +- (NSArray *)mas_updateConstraints:(void (^)(MASConstraintMaker *make))block; + +/** + * Creates a MASConstraintMaker with each view in the callee. + * Any constraints defined are added to each view or the appropriate superview once the block has finished executing on each view. + * All constraints previously installed for the views will be removed. + * + * @param block scope within which you can build up the constraints which you wish to apply to each view. + * + * @return Array of created/updated MASConstraints + */ +- (NSArray *)mas_remakeConstraints:(void (^)(MASConstraintMaker *make))block; + +/** + * distribute with fixed spacing + * + * @param axisType which axis to distribute items along + * @param fixedSpacing the spacing between each item + * @param leadSpacing the spacing before the first item and the container + * @param tailSpacing the spacing after the last item and the container + */ +- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedSpacing:(CGFloat)fixedSpacing leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing; + +/** + * distribute with fixed item size + * + * @param axisType which axis to distribute items along + * @param fixedItemLength the fixed length of each item + * @param leadSpacing the spacing before the first item and the container + * @param tailSpacing the spacing after the last item and the container + */ +- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedItemLength:(CGFloat)fixedItemLength leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing; + +@end diff --git a/Pods/Masonry/Masonry/NSArray+MASAdditions.m b/Pods/Masonry/Masonry/NSArray+MASAdditions.m new file mode 100644 index 0000000..831d8cd --- /dev/null +++ b/Pods/Masonry/Masonry/NSArray+MASAdditions.m @@ -0,0 +1,162 @@ +// +// NSArray+MASAdditions.m +// +// +// Created by Daniel Hammond on 11/26/13. +// +// + +#import "NSArray+MASAdditions.h" +#import "View+MASAdditions.h" + +@implementation NSArray (MASAdditions) + +- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block { + NSMutableArray *constraints = [NSMutableArray array]; + for (MAS_VIEW *view in self) { + NSAssert([view isKindOfClass:[MAS_VIEW class]], @"All objects in the array must be views"); + [constraints addObjectsFromArray:[view mas_makeConstraints:block]]; + } + return constraints; +} + +- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block { + NSMutableArray *constraints = [NSMutableArray array]; + for (MAS_VIEW *view in self) { + NSAssert([view isKindOfClass:[MAS_VIEW class]], @"All objects in the array must be views"); + [constraints addObjectsFromArray:[view mas_updateConstraints:block]]; + } + return constraints; +} + +- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block { + NSMutableArray *constraints = [NSMutableArray array]; + for (MAS_VIEW *view in self) { + NSAssert([view isKindOfClass:[MAS_VIEW class]], @"All objects in the array must be views"); + [constraints addObjectsFromArray:[view mas_remakeConstraints:block]]; + } + return constraints; +} + +- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedSpacing:(CGFloat)fixedSpacing leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing { + if (self.count < 2) { + NSAssert(self.count>1,@"views to distribute need to bigger than one"); + return; + } + + MAS_VIEW *tempSuperView = [self mas_commonSuperviewOfViews]; + if (axisType == MASAxisTypeHorizontal) { + MAS_VIEW *prev; + for (int i = 0; i < self.count; i++) { + MAS_VIEW *v = self[i]; + [v mas_makeConstraints:^(MASConstraintMaker *make) { + if (prev) { + make.width.equalTo(prev); + make.left.equalTo(prev.mas_right).offset(fixedSpacing); + if (i == self.count - 1) {//last one + make.right.equalTo(tempSuperView).offset(-tailSpacing); + } + } + else {//first one + make.left.equalTo(tempSuperView).offset(leadSpacing); + } + + }]; + prev = v; + } + } + else { + MAS_VIEW *prev; + for (int i = 0; i < self.count; i++) { + MAS_VIEW *v = self[i]; + [v mas_makeConstraints:^(MASConstraintMaker *make) { + if (prev) { + make.height.equalTo(prev); + make.top.equalTo(prev.mas_bottom).offset(fixedSpacing); + if (i == self.count - 1) {//last one + make.bottom.equalTo(tempSuperView).offset(-tailSpacing); + } + } + else {//first one + make.top.equalTo(tempSuperView).offset(leadSpacing); + } + + }]; + prev = v; + } + } +} + +- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedItemLength:(CGFloat)fixedItemLength leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing { + if (self.count < 2) { + NSAssert(self.count>1,@"views to distribute need to bigger than one"); + return; + } + + MAS_VIEW *tempSuperView = [self mas_commonSuperviewOfViews]; + if (axisType == MASAxisTypeHorizontal) { + MAS_VIEW *prev; + for (int i = 0; i < self.count; i++) { + MAS_VIEW *v = self[i]; + [v mas_makeConstraints:^(MASConstraintMaker *make) { + make.width.equalTo(@(fixedItemLength)); + if (prev) { + if (i == self.count - 1) {//last one + make.right.equalTo(tempSuperView).offset(-tailSpacing); + } + else { + CGFloat offset = (1-(i/((CGFloat)self.count-1)))*(fixedItemLength+leadSpacing)-i*tailSpacing/(((CGFloat)self.count-1)); + make.right.equalTo(tempSuperView).multipliedBy(i/((CGFloat)self.count-1)).with.offset(offset); + } + } + else {//first one + make.left.equalTo(tempSuperView).offset(leadSpacing); + } + }]; + prev = v; + } + } + else { + MAS_VIEW *prev; + for (int i = 0; i < self.count; i++) { + MAS_VIEW *v = self[i]; + [v mas_makeConstraints:^(MASConstraintMaker *make) { + make.height.equalTo(@(fixedItemLength)); + if (prev) { + if (i == self.count - 1) {//last one + make.bottom.equalTo(tempSuperView).offset(-tailSpacing); + } + else { + CGFloat offset = (1-(i/((CGFloat)self.count-1)))*(fixedItemLength+leadSpacing)-i*tailSpacing/(((CGFloat)self.count-1)); + make.bottom.equalTo(tempSuperView).multipliedBy(i/((CGFloat)self.count-1)).with.offset(offset); + } + } + else {//first one + make.top.equalTo(tempSuperView).offset(leadSpacing); + } + }]; + prev = v; + } + } +} + +- (MAS_VIEW *)mas_commonSuperviewOfViews +{ + MAS_VIEW *commonSuperview = nil; + MAS_VIEW *previousView = nil; + for (id object in self) { + if ([object isKindOfClass:[MAS_VIEW class]]) { + MAS_VIEW *view = (MAS_VIEW *)object; + if (previousView) { + commonSuperview = [view mas_closestCommonSuperview:commonSuperview]; + } else { + commonSuperview = view; + } + previousView = view; + } + } + NSAssert(commonSuperview, @"Can't constrain views that do not share a common superview. Make sure that all the views in this array have been added into the same view hierarchy."); + return commonSuperview; +} + +@end diff --git a/Pods/Masonry/Masonry/NSArray+MASShorthandAdditions.h b/Pods/Masonry/Masonry/NSArray+MASShorthandAdditions.h new file mode 100644 index 0000000..8b47369 --- /dev/null +++ b/Pods/Masonry/Masonry/NSArray+MASShorthandAdditions.h @@ -0,0 +1,41 @@ +// +// NSArray+MASShorthandAdditions.h +// Masonry +// +// Created by Jonas Budelmann on 22/07/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "NSArray+MASAdditions.h" + +#ifdef MAS_SHORTHAND + +/** + * Shorthand array additions without the 'mas_' prefixes, + * only enabled if MAS_SHORTHAND is defined + */ +@interface NSArray (MASShorthandAdditions) + +- (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *make))block; +- (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *make))block; +- (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *make))block; + +@end + +@implementation NSArray (MASShorthandAdditions) + +- (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *))block { + return [self mas_makeConstraints:block]; +} + +- (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *))block { + return [self mas_updateConstraints:block]; +} + +- (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *))block { + return [self mas_remakeConstraints:block]; +} + +@end + +#endif diff --git a/Pods/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.h b/Pods/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.h new file mode 100644 index 0000000..1279b4f --- /dev/null +++ b/Pods/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.h @@ -0,0 +1,16 @@ +// +// NSLayoutConstraint+MASDebugAdditions.h +// Masonry +// +// Created by Jonas Budelmann on 3/08/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "MASUtilities.h" + +/** + * makes debug and log output of NSLayoutConstraints more readable + */ +@interface NSLayoutConstraint (MASDebugAdditions) + +@end diff --git a/Pods/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.m b/Pods/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.m new file mode 100644 index 0000000..3569cf8 --- /dev/null +++ b/Pods/Masonry/Masonry/NSLayoutConstraint+MASDebugAdditions.m @@ -0,0 +1,146 @@ +// +// NSLayoutConstraint+MASDebugAdditions.m +// Masonry +// +// Created by Jonas Budelmann on 3/08/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "NSLayoutConstraint+MASDebugAdditions.h" +#import "MASConstraint.h" +#import "MASLayoutConstraint.h" + +@implementation NSLayoutConstraint (MASDebugAdditions) + +#pragma mark - description maps + ++ (NSDictionary *)layoutRelationDescriptionsByValue { + static dispatch_once_t once; + static NSDictionary *descriptionMap; + dispatch_once(&once, ^{ + descriptionMap = @{ + @(NSLayoutRelationEqual) : @"==", + @(NSLayoutRelationGreaterThanOrEqual) : @">=", + @(NSLayoutRelationLessThanOrEqual) : @"<=", + }; + }); + return descriptionMap; +} + ++ (NSDictionary *)layoutAttributeDescriptionsByValue { + static dispatch_once_t once; + static NSDictionary *descriptionMap; + dispatch_once(&once, ^{ + descriptionMap = @{ + @(NSLayoutAttributeTop) : @"top", + @(NSLayoutAttributeLeft) : @"left", + @(NSLayoutAttributeBottom) : @"bottom", + @(NSLayoutAttributeRight) : @"right", + @(NSLayoutAttributeLeading) : @"leading", + @(NSLayoutAttributeTrailing) : @"trailing", + @(NSLayoutAttributeWidth) : @"width", + @(NSLayoutAttributeHeight) : @"height", + @(NSLayoutAttributeCenterX) : @"centerX", + @(NSLayoutAttributeCenterY) : @"centerY", + @(NSLayoutAttributeBaseline) : @"baseline", + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + @(NSLayoutAttributeFirstBaseline) : @"firstBaseline", + @(NSLayoutAttributeLastBaseline) : @"lastBaseline", +#endif + +#if TARGET_OS_IPHONE || TARGET_OS_TV + @(NSLayoutAttributeLeftMargin) : @"leftMargin", + @(NSLayoutAttributeRightMargin) : @"rightMargin", + @(NSLayoutAttributeTopMargin) : @"topMargin", + @(NSLayoutAttributeBottomMargin) : @"bottomMargin", + @(NSLayoutAttributeLeadingMargin) : @"leadingMargin", + @(NSLayoutAttributeTrailingMargin) : @"trailingMargin", + @(NSLayoutAttributeCenterXWithinMargins) : @"centerXWithinMargins", + @(NSLayoutAttributeCenterYWithinMargins) : @"centerYWithinMargins", +#endif + + }; + + }); + return descriptionMap; +} + + ++ (NSDictionary *)layoutPriorityDescriptionsByValue { + static dispatch_once_t once; + static NSDictionary *descriptionMap; + dispatch_once(&once, ^{ +#if TARGET_OS_IPHONE || TARGET_OS_TV + descriptionMap = @{ + @(MASLayoutPriorityDefaultHigh) : @"high", + @(MASLayoutPriorityDefaultLow) : @"low", + @(MASLayoutPriorityDefaultMedium) : @"medium", + @(MASLayoutPriorityRequired) : @"required", + @(MASLayoutPriorityFittingSizeLevel) : @"fitting size", + }; +#elif TARGET_OS_MAC + descriptionMap = @{ + @(MASLayoutPriorityDefaultHigh) : @"high", + @(MASLayoutPriorityDragThatCanResizeWindow) : @"drag can resize window", + @(MASLayoutPriorityDefaultMedium) : @"medium", + @(MASLayoutPriorityWindowSizeStayPut) : @"window size stay put", + @(MASLayoutPriorityDragThatCannotResizeWindow) : @"drag cannot resize window", + @(MASLayoutPriorityDefaultLow) : @"low", + @(MASLayoutPriorityFittingSizeCompression) : @"fitting size", + @(MASLayoutPriorityRequired) : @"required", + }; +#endif + }); + return descriptionMap; +} + +#pragma mark - description override + ++ (NSString *)descriptionForObject:(id)obj { + if ([obj respondsToSelector:@selector(mas_key)] && [obj mas_key]) { + return [NSString stringWithFormat:@"%@:%@", [obj class], [obj mas_key]]; + } + return [NSString stringWithFormat:@"%@:%p", [obj class], obj]; +} + +- (NSString *)description { + NSMutableString *description = [[NSMutableString alloc] initWithString:@"<"]; + + [description appendString:[self.class descriptionForObject:self]]; + + [description appendFormat:@" %@", [self.class descriptionForObject:self.firstItem]]; + if (self.firstAttribute != NSLayoutAttributeNotAnAttribute) { + [description appendFormat:@".%@", self.class.layoutAttributeDescriptionsByValue[@(self.firstAttribute)]]; + } + + [description appendFormat:@" %@", self.class.layoutRelationDescriptionsByValue[@(self.relation)]]; + + if (self.secondItem) { + [description appendFormat:@" %@", [self.class descriptionForObject:self.secondItem]]; + } + if (self.secondAttribute != NSLayoutAttributeNotAnAttribute) { + [description appendFormat:@".%@", self.class.layoutAttributeDescriptionsByValue[@(self.secondAttribute)]]; + } + + if (self.multiplier != 1) { + [description appendFormat:@" * %g", self.multiplier]; + } + + if (self.secondAttribute == NSLayoutAttributeNotAnAttribute) { + [description appendFormat:@" %g", self.constant]; + } else { + if (self.constant) { + [description appendFormat:@" %@ %g", (self.constant < 0 ? @"-" : @"+"), ABS(self.constant)]; + } + } + + if (self.priority != MASLayoutPriorityRequired) { + [description appendFormat:@" ^%@", self.class.layoutPriorityDescriptionsByValue[@(self.priority)] ?: [NSNumber numberWithDouble:self.priority]]; + } + + [description appendString:@">"]; + return description; +} + +@end diff --git a/Pods/Masonry/Masonry/View+MASAdditions.h b/Pods/Masonry/Masonry/View+MASAdditions.h new file mode 100644 index 0000000..ab1e8ae --- /dev/null +++ b/Pods/Masonry/Masonry/View+MASAdditions.h @@ -0,0 +1,101 @@ +// +// UIView+MASAdditions.h +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "MASUtilities.h" +#import "MASConstraintMaker.h" +#import "MASViewAttribute.h" + +/** + * Provides constraint maker block + * and convience methods for creating MASViewAttribute which are view + NSLayoutAttribute pairs + */ +@interface MAS_VIEW (MASAdditions) + +/** + * following properties return a new MASViewAttribute with current view and appropriate NSLayoutAttribute + */ +@property (nonatomic, strong, readonly) MASViewAttribute *mas_left; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_top; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_right; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottom; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_leading; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_trailing; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_width; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_height; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_centerX; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_centerY; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_baseline; +@property (nonatomic, strong, readonly) MASViewAttribute *(^mas_attribute)(NSLayoutAttribute attr); + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +@property (nonatomic, strong, readonly) MASViewAttribute *mas_firstBaseline; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_lastBaseline; + +#endif + +#if TARGET_OS_IPHONE || TARGET_OS_TV + +@property (nonatomic, strong, readonly) MASViewAttribute *mas_leftMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_rightMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_topMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_leadingMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_trailingMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_centerXWithinMargins; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_centerYWithinMargins; + +#endif + +/** + * a key to associate with this view + */ +@property (nonatomic, strong) id mas_key; + +/** + * Finds the closest common superview between this view and another view + * + * @param view other view + * + * @return returns nil if common superview could not be found + */ +- (instancetype)mas_closestCommonSuperview:(MAS_VIEW *)view; + +/** + * Creates a MASConstraintMaker with the callee view. + * Any constraints defined are added to the view or the appropriate superview once the block has finished executing + * + * @param block scope within which you can build up the constraints which you wish to apply to the view. + * + * @return Array of created MASConstraints + */ +- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block; + +/** + * Creates a MASConstraintMaker with the callee view. + * Any constraints defined are added to the view or the appropriate superview once the block has finished executing. + * If an existing constraint exists then it will be updated instead. + * + * @param block scope within which you can build up the constraints which you wish to apply to the view. + * + * @return Array of created/updated MASConstraints + */ +- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block; + +/** + * Creates a MASConstraintMaker with the callee view. + * Any constraints defined are added to the view or the appropriate superview once the block has finished executing. + * All constraints previously installed for the view will be removed. + * + * @param block scope within which you can build up the constraints which you wish to apply to the view. + * + * @return Array of created/updated MASConstraints + */ +- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block; + +@end diff --git a/Pods/Masonry/Masonry/View+MASAdditions.m b/Pods/Masonry/Masonry/View+MASAdditions.m new file mode 100644 index 0000000..b53b68d --- /dev/null +++ b/Pods/Masonry/Masonry/View+MASAdditions.m @@ -0,0 +1,166 @@ +// +// UIView+MASAdditions.m +// Masonry +// +// Created by Jonas Budelmann on 20/07/13. +// Copyright (c) 2013 cloudling. All rights reserved. +// + +#import "View+MASAdditions.h" +#import + +@implementation MAS_VIEW (MASAdditions) + +- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block { + self.translatesAutoresizingMaskIntoConstraints = NO; + MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; + block(constraintMaker); + return [constraintMaker install]; +} + +- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *))block { + self.translatesAutoresizingMaskIntoConstraints = NO; + MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; + constraintMaker.updateExisting = YES; + block(constraintMaker); + return [constraintMaker install]; +} + +- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block { + self.translatesAutoresizingMaskIntoConstraints = NO; + MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; + constraintMaker.removeExisting = YES; + block(constraintMaker); + return [constraintMaker install]; +} + +#pragma mark - NSLayoutAttribute properties + +- (MASViewAttribute *)mas_left { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeft]; +} + +- (MASViewAttribute *)mas_top { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTop]; +} + +- (MASViewAttribute *)mas_right { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeRight]; +} + +- (MASViewAttribute *)mas_bottom { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeBottom]; +} + +- (MASViewAttribute *)mas_leading { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeading]; +} + +- (MASViewAttribute *)mas_trailing { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTrailing]; +} + +- (MASViewAttribute *)mas_width { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeWidth]; +} + +- (MASViewAttribute *)mas_height { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeHeight]; +} + +- (MASViewAttribute *)mas_centerX { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterX]; +} + +- (MASViewAttribute *)mas_centerY { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterY]; +} + +- (MASViewAttribute *)mas_baseline { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeBaseline]; +} + +- (MASViewAttribute *(^)(NSLayoutAttribute))mas_attribute +{ + return ^(NSLayoutAttribute attr) { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:attr]; + }; +} + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +- (MASViewAttribute *)mas_firstBaseline { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeFirstBaseline]; +} +- (MASViewAttribute *)mas_lastBaseline { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLastBaseline]; +} + +#endif + +#if TARGET_OS_IPHONE || TARGET_OS_TV + +- (MASViewAttribute *)mas_leftMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeftMargin]; +} + +- (MASViewAttribute *)mas_rightMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeRightMargin]; +} + +- (MASViewAttribute *)mas_topMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTopMargin]; +} + +- (MASViewAttribute *)mas_bottomMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeBottomMargin]; +} + +- (MASViewAttribute *)mas_leadingMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeadingMargin]; +} + +- (MASViewAttribute *)mas_trailingMargin { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTrailingMargin]; +} + +- (MASViewAttribute *)mas_centerXWithinMargins { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterXWithinMargins]; +} + +- (MASViewAttribute *)mas_centerYWithinMargins { + return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeCenterYWithinMargins]; +} + +#endif + +#pragma mark - associated properties + +- (id)mas_key { + return objc_getAssociatedObject(self, @selector(mas_key)); +} + +- (void)setMas_key:(id)key { + objc_setAssociatedObject(self, @selector(mas_key), key, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - heirachy + +- (instancetype)mas_closestCommonSuperview:(MAS_VIEW *)view { + MAS_VIEW *closestCommonSuperview = nil; + + MAS_VIEW *secondViewSuperview = view; + while (!closestCommonSuperview && secondViewSuperview) { + MAS_VIEW *firstViewSuperview = self; + while (!closestCommonSuperview && firstViewSuperview) { + if (secondViewSuperview == firstViewSuperview) { + closestCommonSuperview = secondViewSuperview; + } + firstViewSuperview = firstViewSuperview.superview; + } + secondViewSuperview = secondViewSuperview.superview; + } + return closestCommonSuperview; +} + +@end diff --git a/Pods/Masonry/Masonry/View+MASShorthandAdditions.h b/Pods/Masonry/Masonry/View+MASShorthandAdditions.h new file mode 100644 index 0000000..0446056 --- /dev/null +++ b/Pods/Masonry/Masonry/View+MASShorthandAdditions.h @@ -0,0 +1,115 @@ +// +// UIView+MASShorthandAdditions.h +// Masonry +// +// Created by Jonas Budelmann on 22/07/13. +// Copyright (c) 2013 Jonas Budelmann. All rights reserved. +// + +#import "View+MASAdditions.h" + +#ifdef MAS_SHORTHAND + +/** + * Shorthand view additions without the 'mas_' prefixes, + * only enabled if MAS_SHORTHAND is defined + */ +@interface MAS_VIEW (MASShorthandAdditions) + +@property (nonatomic, strong, readonly) MASViewAttribute *left; +@property (nonatomic, strong, readonly) MASViewAttribute *top; +@property (nonatomic, strong, readonly) MASViewAttribute *right; +@property (nonatomic, strong, readonly) MASViewAttribute *bottom; +@property (nonatomic, strong, readonly) MASViewAttribute *leading; +@property (nonatomic, strong, readonly) MASViewAttribute *trailing; +@property (nonatomic, strong, readonly) MASViewAttribute *width; +@property (nonatomic, strong, readonly) MASViewAttribute *height; +@property (nonatomic, strong, readonly) MASViewAttribute *centerX; +@property (nonatomic, strong, readonly) MASViewAttribute *centerY; +@property (nonatomic, strong, readonly) MASViewAttribute *baseline; +@property (nonatomic, strong, readonly) MASViewAttribute *(^attribute)(NSLayoutAttribute attr); + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +@property (nonatomic, strong, readonly) MASViewAttribute *firstBaseline; +@property (nonatomic, strong, readonly) MASViewAttribute *lastBaseline; + +#endif + +#if TARGET_OS_IPHONE || TARGET_OS_TV + +@property (nonatomic, strong, readonly) MASViewAttribute *leftMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *rightMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *topMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *bottomMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *leadingMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *trailingMargin; +@property (nonatomic, strong, readonly) MASViewAttribute *centerXWithinMargins; +@property (nonatomic, strong, readonly) MASViewAttribute *centerYWithinMargins; + +#endif + +- (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *make))block; +- (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *make))block; +- (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *make))block; + +@end + +#define MAS_ATTR_FORWARD(attr) \ +- (MASViewAttribute *)attr { \ + return [self mas_##attr]; \ +} + +@implementation MAS_VIEW (MASShorthandAdditions) + +MAS_ATTR_FORWARD(top); +MAS_ATTR_FORWARD(left); +MAS_ATTR_FORWARD(bottom); +MAS_ATTR_FORWARD(right); +MAS_ATTR_FORWARD(leading); +MAS_ATTR_FORWARD(trailing); +MAS_ATTR_FORWARD(width); +MAS_ATTR_FORWARD(height); +MAS_ATTR_FORWARD(centerX); +MAS_ATTR_FORWARD(centerY); +MAS_ATTR_FORWARD(baseline); + +#if (__IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (__TV_OS_VERSION_MIN_REQUIRED >= 9000) || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + +MAS_ATTR_FORWARD(firstBaseline); +MAS_ATTR_FORWARD(lastBaseline); + +#endif + +#if TARGET_OS_IPHONE || TARGET_OS_TV + +MAS_ATTR_FORWARD(leftMargin); +MAS_ATTR_FORWARD(rightMargin); +MAS_ATTR_FORWARD(topMargin); +MAS_ATTR_FORWARD(bottomMargin); +MAS_ATTR_FORWARD(leadingMargin); +MAS_ATTR_FORWARD(trailingMargin); +MAS_ATTR_FORWARD(centerXWithinMargins); +MAS_ATTR_FORWARD(centerYWithinMargins); + +#endif + +- (MASViewAttribute *(^)(NSLayoutAttribute))attribute { + return [self mas_attribute]; +} + +- (NSArray *)makeConstraints:(void(^)(MASConstraintMaker *))block { + return [self mas_makeConstraints:block]; +} + +- (NSArray *)updateConstraints:(void(^)(MASConstraintMaker *))block { + return [self mas_updateConstraints:block]; +} + +- (NSArray *)remakeConstraints:(void(^)(MASConstraintMaker *))block { + return [self mas_remakeConstraints:block]; +} + +@end + +#endif diff --git a/Pods/Masonry/Masonry/ViewController+MASAdditions.h b/Pods/Masonry/Masonry/ViewController+MASAdditions.h new file mode 100644 index 0000000..79fd1fa --- /dev/null +++ b/Pods/Masonry/Masonry/ViewController+MASAdditions.h @@ -0,0 +1,30 @@ +// +// UIViewController+MASAdditions.h +// Masonry +// +// Created by Craig Siemens on 2015-06-23. +// +// + +#import "MASUtilities.h" +#import "MASConstraintMaker.h" +#import "MASViewAttribute.h" + +#ifdef MAS_VIEW_CONTROLLER + +@interface MAS_VIEW_CONTROLLER (MASAdditions) + +/** + * following properties return a new MASViewAttribute with appropriate UILayoutGuide and NSLayoutAttribute + */ +@property (nonatomic, strong, readonly) MASViewAttribute *mas_topLayoutGuide; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomLayoutGuide; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_topLayoutGuideTop; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_topLayoutGuideBottom; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomLayoutGuideTop; +@property (nonatomic, strong, readonly) MASViewAttribute *mas_bottomLayoutGuideBottom; + + +@end + +#endif diff --git a/Pods/Masonry/Masonry/ViewController+MASAdditions.m b/Pods/Masonry/Masonry/ViewController+MASAdditions.m new file mode 100644 index 0000000..2f5139f --- /dev/null +++ b/Pods/Masonry/Masonry/ViewController+MASAdditions.m @@ -0,0 +1,39 @@ +// +// UIViewController+MASAdditions.m +// Masonry +// +// Created by Craig Siemens on 2015-06-23. +// +// + +#import "ViewController+MASAdditions.h" + +#ifdef MAS_VIEW_CONTROLLER + +@implementation MAS_VIEW_CONTROLLER (MASAdditions) + +- (MASViewAttribute *)mas_topLayoutGuide { + return [[MASViewAttribute alloc] initWithView:self.view item:self.topLayoutGuide layoutAttribute:NSLayoutAttributeBottom]; +} +- (MASViewAttribute *)mas_topLayoutGuideTop { + return [[MASViewAttribute alloc] initWithView:self.view item:self.topLayoutGuide layoutAttribute:NSLayoutAttributeTop]; +} +- (MASViewAttribute *)mas_topLayoutGuideBottom { + return [[MASViewAttribute alloc] initWithView:self.view item:self.topLayoutGuide layoutAttribute:NSLayoutAttributeBottom]; +} + +- (MASViewAttribute *)mas_bottomLayoutGuide { + return [[MASViewAttribute alloc] initWithView:self.view item:self.bottomLayoutGuide layoutAttribute:NSLayoutAttributeTop]; +} +- (MASViewAttribute *)mas_bottomLayoutGuideTop { + return [[MASViewAttribute alloc] initWithView:self.view item:self.bottomLayoutGuide layoutAttribute:NSLayoutAttributeTop]; +} +- (MASViewAttribute *)mas_bottomLayoutGuideBottom { + return [[MASViewAttribute alloc] initWithView:self.view item:self.bottomLayoutGuide layoutAttribute:NSLayoutAttributeBottom]; +} + + + +@end + +#endif diff --git a/Pods/Masonry/README.md b/Pods/Masonry/README.md new file mode 100644 index 0000000..2b59a48 --- /dev/null +++ b/Pods/Masonry/README.md @@ -0,0 +1,409 @@ +#Masonry [![Build Status](https://travis-ci.org/SnapKit/Masonry.svg?branch=master)](https://travis-ci.org/SnapKit/Masonry) [![Coverage Status](https://img.shields.io/coveralls/SnapKit/Masonry.svg?style=flat-square)](https://coveralls.io/r/SnapKit/Masonry) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) ![Pod Version](https://img.shields.io/cocoapods/v/Masonry.svg?style=flat) + +**Masonry is still actively maintained, we are committed to fixing bugs and merging good quality PRs from the wider community. However if you're using Swift in your project, we recommend using [SnapKit](https://github.com/SnapKit/SnapKit) as it provides better type safety with a simpler API.** + +Masonry is a light-weight layout framework which wraps AutoLayout with a nicer syntax. Masonry has its own layout DSL which provides a chainable way of describing your NSLayoutConstraints which results in layout code that is more concise and readable. +Masonry supports iOS and Mac OS X. + +For examples take a look at the **Masonry iOS Examples** project in the Masonry workspace. You will need to run `pod install` after downloading. + +## What's wrong with NSLayoutConstraints? + +Under the hood Auto Layout is a powerful and flexible way of organising and laying out your views. However creating constraints from code is verbose and not very descriptive. +Imagine a simple example in which you want to have a view fill its superview but inset by 10 pixels on every side +```obj-c +UIView *superview = self.view; + +UIView *view1 = [[UIView alloc] init]; +view1.translatesAutoresizingMaskIntoConstraints = NO; +view1.backgroundColor = [UIColor greenColor]; +[superview addSubview:view1]; + +UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10); + +[superview addConstraints:@[ + + //view1 constraints + [NSLayoutConstraint constraintWithItem:view1 + attribute:NSLayoutAttributeTop + relatedBy:NSLayoutRelationEqual + toItem:superview + attribute:NSLayoutAttributeTop + multiplier:1.0 + constant:padding.top], + + [NSLayoutConstraint constraintWithItem:view1 + attribute:NSLayoutAttributeLeft + relatedBy:NSLayoutRelationEqual + toItem:superview + attribute:NSLayoutAttributeLeft + multiplier:1.0 + constant:padding.left], + + [NSLayoutConstraint constraintWithItem:view1 + attribute:NSLayoutAttributeBottom + relatedBy:NSLayoutRelationEqual + toItem:superview + attribute:NSLayoutAttributeBottom + multiplier:1.0 + constant:-padding.bottom], + + [NSLayoutConstraint constraintWithItem:view1 + attribute:NSLayoutAttributeRight + relatedBy:NSLayoutRelationEqual + toItem:superview + attribute:NSLayoutAttributeRight + multiplier:1 + constant:-padding.right], + + ]]; +``` +Even with such a simple example the code needed is quite verbose and quickly becomes unreadable when you have more than 2 or 3 views. +Another option is to use Visual Format Language (VFL), which is a bit less long winded. +However the ASCII type syntax has its own pitfalls and its also a bit harder to animate as `NSLayoutConstraint constraintsWithVisualFormat:` returns an array. + +## Prepare to meet your Maker! + +Heres the same constraints created using MASConstraintMaker + +```obj-c +UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10); + +[view1 mas_makeConstraints:^(MASConstraintMaker *make) { + make.top.equalTo(superview.mas_top).with.offset(padding.top); //with is an optional semantic filler + make.left.equalTo(superview.mas_left).with.offset(padding.left); + make.bottom.equalTo(superview.mas_bottom).with.offset(-padding.bottom); + make.right.equalTo(superview.mas_right).with.offset(-padding.right); +}]; +``` +Or even shorter + +```obj-c +[view1 mas_makeConstraints:^(MASConstraintMaker *make) { + make.edges.equalTo(superview).with.insets(padding); +}]; +``` + +Also note in the first example we had to add the constraints to the superview `[superview addConstraints:...`. +Masonry however will automagically add constraints to the appropriate view. + +Masonry will also call `view1.translatesAutoresizingMaskIntoConstraints = NO;` for you. + +## Not all things are created equal + +> `.equalTo` equivalent to **NSLayoutRelationEqual** + +> `.lessThanOrEqualTo` equivalent to **NSLayoutRelationLessThanOrEqual** + +> `.greaterThanOrEqualTo` equivalent to **NSLayoutRelationGreaterThanOrEqual** + +These three equality constraints accept one argument which can be any of the following: + +#### 1. MASViewAttribute + +```obj-c +make.centerX.lessThanOrEqualTo(view2.mas_left); +``` + +MASViewAttribute | NSLayoutAttribute +------------------------- | -------------------------- +view.mas_left | NSLayoutAttributeLeft +view.mas_right | NSLayoutAttributeRight +view.mas_top | NSLayoutAttributeTop +view.mas_bottom | NSLayoutAttributeBottom +view.mas_leading | NSLayoutAttributeLeading +view.mas_trailing | NSLayoutAttributeTrailing +view.mas_width | NSLayoutAttributeWidth +view.mas_height | NSLayoutAttributeHeight +view.mas_centerX | NSLayoutAttributeCenterX +view.mas_centerY | NSLayoutAttributeCenterY +view.mas_baseline | NSLayoutAttributeBaseline + +#### 2. UIView/NSView + +if you want view.left to be greater than or equal to label.left : +```obj-c +//these two constraints are exactly the same +make.left.greaterThanOrEqualTo(label); +make.left.greaterThanOrEqualTo(label.mas_left); +``` + +#### 3. NSNumber + +Auto Layout allows width and height to be set to constant values. +if you want to set view to have a minimum and maximum width you could pass a number to the equality blocks: +```obj-c +//width >= 200 && width <= 400 +make.width.greaterThanOrEqualTo(@200); +make.width.lessThanOrEqualTo(@400) +``` + +However Auto Layout does not allow alignment attributes such as left, right, centerY etc to be set to constant values. +So if you pass a NSNumber for these attributes Masonry will turn these into constraints relative to the view’s superview ie: +```obj-c +//creates view.left = view.superview.left + 10 +make.left.lessThanOrEqualTo(@10) +``` + +Instead of using NSNumber, you can use primitives and structs to build your constraints, like so: +```obj-c +make.top.mas_equalTo(42); +make.height.mas_equalTo(20); +make.size.mas_equalTo(CGSizeMake(50, 100)); +make.edges.mas_equalTo(UIEdgeInsetsMake(10, 0, 10, 0)); +make.left.mas_equalTo(view).mas_offset(UIEdgeInsetsMake(10, 0, 10, 0)); +``` + +By default, macros which support [autoboxing](https://en.wikipedia.org/wiki/Autoboxing#Autoboxing) are prefixed with `mas_`. Unprefixed versions are available by defining `MAS_SHORTHAND_GLOBALS` before importing Masonry. + +#### 4. NSArray + +An array of a mixture of any of the previous types +```obj-c +make.height.equalTo(@[view1.mas_height, view2.mas_height]); +make.height.equalTo(@[view1, view2]); +make.left.equalTo(@[view1, @100, view3.right]); +```` + +## Learn to prioritize + +> `.priority` allows you to specify an exact priority + +> `.priorityHigh` equivalent to **UILayoutPriorityDefaultHigh** + +> `.priorityMedium` is half way between high and low + +> `.priorityLow` equivalent to **UILayoutPriorityDefaultLow** + +Priorities are can be tacked on to the end of a constraint chain like so: +```obj-c +make.left.greaterThanOrEqualTo(label.mas_left).with.priorityLow(); + +make.top.equalTo(label.mas_top).with.priority(600); +``` + +## Composition, composition, composition + +Masonry also gives you a few convenience methods which create multiple constraints at the same time. These are called MASCompositeConstraints + +#### edges + +```obj-c +// make top, left, bottom, right equal view2 +make.edges.equalTo(view2); + +// make top = superview.top + 5, left = superview.left + 10, +// bottom = superview.bottom - 15, right = superview.right - 20 +make.edges.equalTo(superview).insets(UIEdgeInsetsMake(5, 10, 15, 20)) +``` + +#### size + +```obj-c +// make width and height greater than or equal to titleLabel +make.size.greaterThanOrEqualTo(titleLabel) + +// make width = superview.width + 100, height = superview.height - 50 +make.size.equalTo(superview).sizeOffset(CGSizeMake(100, -50)) +``` + +#### center +```obj-c +// make centerX and centerY = button1 +make.center.equalTo(button1) + +// make centerX = superview.centerX - 5, centerY = superview.centerY + 10 +make.center.equalTo(superview).centerOffset(CGPointMake(-5, 10)) +``` + +You can chain view attributes for increased readability: + +```obj-c +// All edges but the top should equal those of the superview +make.left.right.and.bottom.equalTo(superview); +make.top.equalTo(otherView); +``` + +## Hold on for dear life + +Sometimes you need modify existing constraints in order to animate or remove/replace constraints. +In Masonry there are a few different approaches to updating constraints. + +#### 1. References +You can hold on to a reference of a particular constraint by assigning the result of a constraint make expression to a local variable or a class property. +You could also reference multiple constraints by storing them away in an array. + +```obj-c +// in public/private interface +@property (nonatomic, strong) MASConstraint *topConstraint; + +... + +// when making constraints +[view1 mas_makeConstraints:^(MASConstraintMaker *make) { + self.topConstraint = make.top.equalTo(superview.mas_top).with.offset(padding.top); + make.left.equalTo(superview.mas_left).with.offset(padding.left); +}]; + +... +// then later you can call +[self.topConstraint uninstall]; +``` + +#### 2. mas_updateConstraints +Alternatively if you are only updating the constant value of the constraint you can use the convience method `mas_updateConstraints` instead of `mas_makeConstraints` + +```obj-c +// this is Apple's recommended place for adding/updating constraints +// this method can get called multiple times in response to setNeedsUpdateConstraints +// which can be called by UIKit internally or in your code if you need to trigger an update to your constraints +- (void)updateConstraints { + [self.growingButton mas_updateConstraints:^(MASConstraintMaker *make) { + make.center.equalTo(self); + make.width.equalTo(@(self.buttonSize.width)).priorityLow(); + make.height.equalTo(@(self.buttonSize.height)).priorityLow(); + make.width.lessThanOrEqualTo(self); + make.height.lessThanOrEqualTo(self); + }]; + + //according to apple super should be called at end of method + [super updateConstraints]; +} +``` + +### 3. mas_remakeConstraints +`mas_updateConstraints` is useful for updating a set of constraints, but doing anything beyond updating constant values can get exhausting. That's where `mas_remakeConstraints` comes in. + +`mas_remakeConstraints` is similar to `mas_updateConstraints`, but instead of updating constant values, it will remove all of its constraints before installing them again. This lets you provide different constraints without having to keep around references to ones which you want to remove. + +```obj-c +- (void)changeButtonPosition { + [self.button mas_remakeConstraints:^(MASConstraintMaker *make) { + make.size.equalTo(self.buttonSize); + + if (topLeft) { + make.top.and.left.offset(10); + } else { + make.bottom.and.right.offset(-10); + } + }]; +} +``` + +You can find more detailed examples of all three approaches in the **Masonry iOS Examples** project. + +## When the ^&*!@ hits the fan! + +Laying out your views doesn't always goto plan. So when things literally go pear shaped, you don't want to be looking at console output like this: + +```obj-c +Unable to simultaneously satisfy constraints.....blah blah blah.... +( + "=5000)]>", + "", + "", + "" +) + +Will attempt to recover by breaking constraint +=5000)]> +``` + +Masonry adds a category to NSLayoutConstraint which overrides the default implementation of `- (NSString *)description`. +Now you can give meaningful names to views and constraints, and also easily pick out the constraints created by Masonry. + +which means your console output can now look like this: + +```obj-c +Unable to simultaneously satisfy constraints......blah blah blah.... +( + "", + "= 5000>", + "", + "" +) + +Will attempt to recover by breaking constraint += 5000> +``` + +For an example of how to set this up take a look at the **Masonry iOS Examples** project in the Masonry workspace. + +## Where should I create my constraints? + +```objc +@implementation DIYCustomView + +- (id)init { + self = [super init]; + if (!self) return nil; + + // --- Create your views here --- + self.button = [[UIButton alloc] init]; + + return self; +} + +// tell UIKit that you are using AutoLayout ++ (BOOL)requiresConstraintBasedLayout { + return YES; +} + +// this is Apple's recommended place for adding/updating constraints +- (void)updateConstraints { + + // --- remake/update constraints here + [self.button remakeConstraints:^(MASConstraintMaker *make) { + make.width.equalTo(@(self.buttonSize.width)); + make.height.equalTo(@(self.buttonSize.height)); + }]; + + //according to apple super should be called at end of method + [super updateConstraints]; +} + +- (void)didTapButton:(UIButton *)button { + // --- Do your changes ie change variables that affect your layout etc --- + self.buttonSize = CGSize(200, 200); + + // tell constraints they need updating + [self setNeedsUpdateConstraints]; +} + +@end +``` + +## Installation +Use the [orsome](http://www.youtube.com/watch?v=YaIZF8uUTtk) [CocoaPods](http://github.com/CocoaPods/CocoaPods). + +In your Podfile +>`pod 'Masonry'` + +If you want to use masonry without all those pesky 'mas_' prefixes. Add #define MAS_SHORTHAND to your prefix.pch before importing Masonry +>`#define MAS_SHORTHAND` + +Get busy Masoning +>`#import "Masonry.h"` + +## Code Snippets + +Copy the included code snippets to ``~/Library/Developer/Xcode/UserData/CodeSnippets`` to write your masonry blocks at lightning speed! + +`mas_make` -> `[ mas_makeConstraints:^(MASConstraintMaker *make){}];` + +`mas_update` -> `[ mas_updateConstraints:^(MASConstraintMaker *make){}];` + +`mas_remake` -> `[ mas_remakeConstraints:^(MASConstraintMaker *make){}];` + +## Features +* Not limited to subset of Auto Layout. Anything NSLayoutConstraint can do, Masonry can do too! +* Great debug support, give your views and constraints meaningful names. +* Constraints read like sentences. +* No crazy macro magic. Masonry won't pollute the global namespace with macros. +* Not string or dictionary based and hence you get compile time checking. + +## TODO +* Eye candy +* Mac example project +* More tests and examples + diff --git a/Pods/NJKWebViewProgress/LICENSE b/Pods/NJKWebViewProgress/LICENSE new file mode 100644 index 0000000..903fc84 --- /dev/null +++ b/Pods/NJKWebViewProgress/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013 Satoshi Asano + +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/Pods/NJKWebViewProgress/NJKWebViewProgress/NJKWebViewProgress.h b/Pods/NJKWebViewProgress/NJKWebViewProgress/NJKWebViewProgress.h new file mode 100644 index 0000000..1770c28 --- /dev/null +++ b/Pods/NJKWebViewProgress/NJKWebViewProgress/NJKWebViewProgress.h @@ -0,0 +1,35 @@ +// +// NJKWebViewProgress.h +// +// Created by Satoshi Aasano on 4/20/13. +// Copyright (c) 2013 Satoshi Asano. All rights reserved. +// + +#import + +#undef njk_weak +#if __has_feature(objc_arc_weak) +#define njk_weak weak +#else +#define njk_weak unsafe_unretained +#endif + +extern const float NJKInitialProgressValue; +extern const float NJKInteractiveProgressValue; +extern const float NJKFinalProgressValue; + +typedef void (^NJKWebViewProgressBlock)(float progress); +@protocol NJKWebViewProgressDelegate; +@interface NJKWebViewProgress : NSObject +@property (nonatomic, njk_weak) idprogressDelegate; +@property (nonatomic, njk_weak) idwebViewProxyDelegate; +@property (nonatomic, copy) NJKWebViewProgressBlock progressBlock; +@property (nonatomic, readonly) float progress; // 0.0..1.0 + +- (void)reset; +@end + +@protocol NJKWebViewProgressDelegate +- (void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress; +@end + diff --git a/Pods/NJKWebViewProgress/NJKWebViewProgress/NJKWebViewProgress.m b/Pods/NJKWebViewProgress/NJKWebViewProgress/NJKWebViewProgress.m new file mode 100644 index 0000000..9c8bdaa --- /dev/null +++ b/Pods/NJKWebViewProgress/NJKWebViewProgress/NJKWebViewProgress.m @@ -0,0 +1,204 @@ +// +// NJKWebViewProgress.m +// +// Created by Satoshi Aasano on 4/20/13. +// Copyright (c) 2013 Satoshi Asano. All rights reserved. +// + +#import "NJKWebViewProgress.h" + +NSString *completeRPCURL = @"webviewprogressproxy:///complete"; + +const float NJKInitialProgressValue = 0.1f; +const float NJKInteractiveProgressValue = 0.5f; +const float NJKFinalProgressValue = 0.9f; + +@implementation NJKWebViewProgress +{ + NSUInteger _loadingCount; + NSUInteger _maxLoadCount; + NSURL *_currentURL; + BOOL _interactive; +} + +- (id)init +{ + self = [super init]; + if (self) { + _maxLoadCount = _loadingCount = 0; + _interactive = NO; + } + return self; +} + +- (void)startProgress +{ + if (_progress < NJKInitialProgressValue) { + [self setProgress:NJKInitialProgressValue]; + } +} + +- (void)incrementProgress +{ + float progress = self.progress; + float maxProgress = _interactive ? NJKFinalProgressValue : NJKInteractiveProgressValue; + float remainPercent = (float)_loadingCount / (float)_maxLoadCount; + float increment = (maxProgress - progress) * remainPercent; + progress += increment; + progress = fmin(progress, maxProgress); + [self setProgress:progress]; +} + +- (void)completeProgress +{ + [self setProgress:1.0]; +} + +- (void)setProgress:(float)progress +{ + // progress should be incremental only + if (progress > _progress || progress == 0) { + _progress = progress; + if ([_progressDelegate respondsToSelector:@selector(webViewProgress:updateProgress:)]) { + [_progressDelegate webViewProgress:self updateProgress:progress]; + } + if (_progressBlock) { + _progressBlock(progress); + } + } +} + +- (void)reset +{ + _maxLoadCount = _loadingCount = 0; + _interactive = NO; + [self setProgress:0.0]; +} + +#pragma mark - +#pragma mark UIWebViewDelegate + +- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType +{ + if ([request.URL.absoluteString isEqualToString:completeRPCURL]) { + [self completeProgress]; + return NO; + } + + BOOL ret = YES; + if ([_webViewProxyDelegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) { + ret = [_webViewProxyDelegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType]; + } + + BOOL isFragmentJump = NO; + if (request.URL.fragment) { + NSString *nonFragmentURL = [request.URL.absoluteString stringByReplacingOccurrencesOfString:[@"#" stringByAppendingString:request.URL.fragment] withString:@""]; + isFragmentJump = [nonFragmentURL isEqualToString:webView.request.URL.absoluteString]; + } + + BOOL isTopLevelNavigation = [request.mainDocumentURL isEqual:request.URL]; + + BOOL isHTTP = [request.URL.scheme isEqualToString:@"http"] || [request.URL.scheme isEqualToString:@"https"]; + if (ret && !isFragmentJump && isHTTP && isTopLevelNavigation) { + _currentURL = request.URL; + [self reset]; + } + return ret; +} + +- (void)webViewDidStartLoad:(UIWebView *)webView +{ + if ([_webViewProxyDelegate respondsToSelector:@selector(webViewDidStartLoad:)]) { + [_webViewProxyDelegate webViewDidStartLoad:webView]; + } + + _loadingCount++; + _maxLoadCount = fmax(_maxLoadCount, _loadingCount); + + [self startProgress]; +} + +- (void)webViewDidFinishLoad:(UIWebView *)webView +{ + if ([_webViewProxyDelegate respondsToSelector:@selector(webViewDidFinishLoad:)]) { + [_webViewProxyDelegate webViewDidFinishLoad:webView]; + } + + _loadingCount--; + [self incrementProgress]; + + NSString *readyState = [webView stringByEvaluatingJavaScriptFromString:@"document.readyState"]; + + BOOL interactive = [readyState isEqualToString:@"interactive"]; + if (interactive) { + _interactive = YES; + NSString *waitForCompleteJS = [NSString stringWithFormat:@"window.addEventListener('load',function() { var iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = '%@'; document.body.appendChild(iframe); }, false);", completeRPCURL]; + [webView stringByEvaluatingJavaScriptFromString:waitForCompleteJS]; + } + + BOOL isNotRedirect = _currentURL && [_currentURL isEqual:webView.request.mainDocumentURL]; + BOOL complete = [readyState isEqualToString:@"complete"]; + if (complete && isNotRedirect) { + [self completeProgress]; + } +} + +- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error +{ + if ([_webViewProxyDelegate respondsToSelector:@selector(webView:didFailLoadWithError:)]) { + [_webViewProxyDelegate webView:webView didFailLoadWithError:error]; + } + + _loadingCount--; + [self incrementProgress]; + + NSString *readyState = [webView stringByEvaluatingJavaScriptFromString:@"document.readyState"]; + + BOOL interactive = [readyState isEqualToString:@"interactive"]; + if (interactive) { + _interactive = YES; + NSString *waitForCompleteJS = [NSString stringWithFormat:@"window.addEventListener('load',function() { var iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = '%@'; document.body.appendChild(iframe); }, false);", completeRPCURL]; + [webView stringByEvaluatingJavaScriptFromString:waitForCompleteJS]; + } + + BOOL isNotRedirect = _currentURL && [_currentURL isEqual:webView.request.mainDocumentURL]; + BOOL complete = [readyState isEqualToString:@"complete"]; + if (complete && isNotRedirect) { + [self completeProgress]; + } +} + +#pragma mark - +#pragma mark Method Forwarding +// for future UIWebViewDelegate impl + +- (BOOL)respondsToSelector:(SEL)aSelector +{ + if ( [super respondsToSelector:aSelector] ) + return YES; + + if ([self.webViewProxyDelegate respondsToSelector:aSelector]) + return YES; + + return NO; +} + +- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector +{ + NSMethodSignature *signature = [super methodSignatureForSelector:selector]; + if(!signature) { + if([_webViewProxyDelegate respondsToSelector:selector]) { + return [(NSObject *)_webViewProxyDelegate methodSignatureForSelector:selector]; + } + } + return signature; +} + +- (void)forwardInvocation:(NSInvocation*)invocation +{ + if ([_webViewProxyDelegate respondsToSelector:[invocation selector]]) { + [invocation invokeWithTarget:_webViewProxyDelegate]; + } +} + +@end diff --git a/Pods/NJKWebViewProgress/NJKWebViewProgress/NJKWebViewProgressView.h b/Pods/NJKWebViewProgress/NJKWebViewProgress/NJKWebViewProgressView.h new file mode 100644 index 0000000..0f7a2ad --- /dev/null +++ b/Pods/NJKWebViewProgress/NJKWebViewProgress/NJKWebViewProgressView.h @@ -0,0 +1,21 @@ +// +// NJKWebViewProgressView.h +// iOS 7 Style WebView Progress Bar +// +// Created by Satoshi Aasano on 11/16/13. +// Copyright (c) 2013 Satoshi Asano. All rights reserved. +// + +#import + +@interface NJKWebViewProgressView : UIView +@property (nonatomic) float progress; + +@property (nonatomic) UIView *progressBarView; +@property (nonatomic) NSTimeInterval barAnimationDuration; // default 0.1 +@property (nonatomic) NSTimeInterval fadeAnimationDuration; // default 0.27 +@property (nonatomic) NSTimeInterval fadeOutDelay; // default 0.1 + +- (void)setProgress:(float)progress animated:(BOOL)animated; + +@end diff --git a/Pods/NJKWebViewProgress/NJKWebViewProgress/NJKWebViewProgressView.m b/Pods/NJKWebViewProgress/NJKWebViewProgress/NJKWebViewProgressView.m new file mode 100644 index 0000000..bf9fe67 --- /dev/null +++ b/Pods/NJKWebViewProgress/NJKWebViewProgress/NJKWebViewProgressView.m @@ -0,0 +1,75 @@ +// +// NJKWebViewProgressView.m +// +// Created by Satoshi Aasanoon 11/16/13. +// Copyright (c) 2013 Satoshi Asano. All rights reserved. +// + +#import "NJKWebViewProgressView.h" + +@implementation NJKWebViewProgressView + +- (id)initWithFrame:(CGRect)frame +{ + self = [super initWithFrame:frame]; + if (self) { + [self configureViews]; + } + return self; +} + +- (void)awakeFromNib +{ + [super awakeFromNib]; + [self configureViews]; +} + +-(void)configureViews +{ + self.userInteractionEnabled = NO; + self.autoresizingMask = UIViewAutoresizingFlexibleWidth; + _progressBarView = [[UIView alloc] initWithFrame:self.bounds]; + _progressBarView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight; + UIColor *tintColor = [UIColor colorWithRed:22.f / 255.f green:126.f / 255.f blue:251.f / 255.f alpha:1.0]; // iOS7 Safari bar color + if ([UIApplication.sharedApplication.delegate.window respondsToSelector:@selector(setTintColor:)] && UIApplication.sharedApplication.delegate.window.tintColor) { + tintColor = UIApplication.sharedApplication.delegate.window.tintColor; + } + _progressBarView.backgroundColor = tintColor; + [self addSubview:_progressBarView]; + + _barAnimationDuration = 0.27f; + _fadeAnimationDuration = 0.27f; + _fadeOutDelay = 0.1f; +} + +-(void)setProgress:(float)progress +{ + [self setProgress:progress animated:NO]; +} + +- (void)setProgress:(float)progress animated:(BOOL)animated +{ + BOOL isGrowing = progress > 0.0; + [UIView animateWithDuration:(isGrowing && animated) ? _barAnimationDuration : 0.0 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{ + CGRect frame = _progressBarView.frame; + frame.size.width = progress * self.bounds.size.width; + _progressBarView.frame = frame; + } completion:nil]; + + if (progress >= 1.0) { + [UIView animateWithDuration:animated ? _fadeAnimationDuration : 0.0 delay:_fadeOutDelay options:UIViewAnimationOptionCurveEaseInOut animations:^{ + _progressBarView.alpha = 0.0; + } completion:^(BOOL completed){ + CGRect frame = _progressBarView.frame; + frame.size.width = 0; + _progressBarView.frame = frame; + }]; + } + else { + [UIView animateWithDuration:animated ? _fadeAnimationDuration : 0.0 delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{ + _progressBarView.alpha = 1.0; + } completion:nil]; + } +} + +@end diff --git a/Pods/NJKWebViewProgress/README.md b/Pods/NJKWebViewProgress/README.md new file mode 100644 index 0000000..d8c445b --- /dev/null +++ b/Pods/NJKWebViewProgress/README.md @@ -0,0 +1,66 @@ +# NJKWebViewProgress +NJKWebViewProgress is a progress interface library for UIWebView. Currently, UIWebView doesn't have official progress interface. You can implement progress bar for your in-app browser using this module. + +iOS ScreenShot 1 + +NJKWebViewProgress doesn't use CocoaTouch's private methods. It's AppStore safe. + +# Used in Production +- [Yahoo! JAPAN](https://itunes.apple.com/app/yahoo!-japan/id299147843?mt=8) +- [Facebook](https://itunes.apple.com/app/facebook/id284882215?mt=8‎) + +# Requirements +- iOS 4.3 or later +- ARC + +# Usage +Instance `NJKWebViewProgress` and set `UIWebViewDelegate`. If you set `webViewProxyDelegate`, `NJKWebViewProgress` should perform as a proxy object. + +```objc +_progressProxy = [[NJKWebViewProgress alloc] init]; // instance variable +webView.delegate = _progressProxy; +_progressProxy.webViewProxyDelegate = self; +_progressProxy.progressDelegate = self; +``` + +When UIWebView start loading, `NJKWebViewProgress` call delegate method and block with progress. +```objc +-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress +{ + [progressView setProgress:progress animated:NO]; +} +``` + +```objc +progressProxy.progressBlock = ^(float progress) { + [progressView setProgress:progress animated:NO]; +}; +``` + +You can determine the current state of the document by comparing the `progress` value to one of the provided constants: + +```objc +-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress +{ + if (progress == NJKInteractiveProgressValue) { + // The web view has finished parsing the document, + // but is still loading sub-resources + } +} +``` + +This repository contains iOS 7 Safari style bar `NJKWebViewProgressView`. You can choose `NJKWebViewProgressView`, `UIProgressView` or your custom bar. + +# Install +## CocoaPods + +``` +pod 'NJKWebViewProgress' +``` + +# License +[Apache]: http://www.apache.org/licenses/LICENSE-2.0 +[MIT]: http://www.opensource.org/licenses/mit-license.php +[GPL]: http://www.gnu.org/licenses/gpl.html +[BSD]: http://opensource.org/licenses/bsd-license.php +[MIT license][MIT]. diff --git a/Pods/Pods.xcodeproj/project.pbxproj b/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000..f99e39b --- /dev/null +++ b/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,4051 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 009C79BE88C2F4C986644CD3E0B088C2 /* JSONModelClassProperty.h in Headers */ = {isa = PBXBuildFile; fileRef = E10C0C2DBA4DAE58B1ED06F7FAE8C22E /* JSONModelClassProperty.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 02307CD9BE8AB7050090F7CE6AA1C4E8 /* YTKKeyValueStore.m in Sources */ = {isa = PBXBuildFile; fileRef = 2CE1C92FCE95492CB6C334FDB10A3525 /* YTKKeyValueStore.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 02A0ADD96B43A9970DD5C7C6BAEAB761 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */; }; + 04A7D6AADAB213CE7D26F8EAD2F87536 /* MASUtilities.h in Headers */ = {isa = PBXBuildFile; fileRef = 26C0262CE054672814BFFD41BA3DE3AC /* MASUtilities.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 04F3BBE71B24770E40CC66A993AD85D1 /* AFSecurityPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = 12F1549F9D1FEC79B40E50D906C6E8CC /* AFSecurityPolicy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0648973667FB537BDC3ABFA9F3AD2ED8 /* IQBarButtonItem.h in Headers */ = {isa = PBXBuildFile; fileRef = ECEDCC8EF733B2FA85A2559FD547A300 /* IQBarButtonItem.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 06697BBB6E6D73B5F021E6DACAC5DE45 /* JSONAPI.m in Sources */ = {isa = PBXBuildFile; fileRef = 03E771AC05A23295139B2FB92DE413D1 /* JSONAPI.m */; }; + 068EF598E554EC57038ACFB89CC2C47A /* View+MASAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 0DE0B076A96500EE0326A01598C25CD9 /* View+MASAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 06FF2586AE76FBBCBF8171F98255D8CB /* IQUIScrollView+Additions.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DCB8E007F3B05111DC4769E7EA077D9 /* IQUIScrollView+Additions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 07159A933B3C47A02FE2B2744ABAAC89 /* MJRefreshStateHeader.m in Sources */ = {isa = PBXBuildFile; fileRef = 82AD1D80CEB504366F098535F8C51A1C /* MJRefreshStateHeader.m */; }; + 091D17D5D8F832D28546A72B788CF0AE /* MASViewConstraint.h in Headers */ = {isa = PBXBuildFile; fileRef = 0023881B652D74804B040D7DA24C1D05 /* MASViewConstraint.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 09EC74E4AFC1D5951D1F80094D06969A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */; }; + 09FD31B5AA4FD8F5D8691D0A3ACF1A6B /* NSData+ImageContentType.m in Sources */ = {isa = PBXBuildFile; fileRef = 4015BC1E8D9C87DAAE2DA773CDA1439F /* NSData+ImageContentType.m */; }; + 0A1E34B4A27DCD62A914F3B028A07E6C /* UIView+MJExtension.m in Sources */ = {isa = PBXBuildFile; fileRef = 3A0319B9CF8094FC585EF6B82C4B2DA8 /* UIView+MJExtension.m */; }; + 0ABD694709F6B146E908A254CDF1A968 /* UIImage+GIF.h in Headers */ = {isa = PBXBuildFile; fileRef = 0A3B12D0C0FC24CB5EEC1457E32FC6BF /* UIImage+GIF.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0ACBBA158F4635FAE16AB5456ABADCA4 /* UIButton+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 90670E1F67061B599C126301C1A3C2D0 /* UIButton+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0AF48B0ADAD7D4F5A2CB22075A3F5FEC /* NSObject+LKDBHelper.h in Headers */ = {isa = PBXBuildFile; fileRef = D7AAFFA73849C31AECBF14C1EF8A1803 /* NSObject+LKDBHelper.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0B1C5725C7BE03D622114275D6FD6EFA /* JSONModelError.m in Sources */ = {isa = PBXBuildFile; fileRef = C47485FA05B8E0C83A44515FDF510F25 /* JSONModelError.m */; }; + 0B53B4188A47FECDD7E1798EAB8B6B9D /* SDWebImageCodersManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 997A2F2BD5D2ACC81541F8F909D4E847 /* SDWebImageCodersManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0CAD81FA7346928A75DFA501EDF7A678 /* SDImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 77F995714B12945BE98FB29DB7AABBA0 /* SDImageCache.m */; }; + 0DB2E34289D18AA9810609ADCCBFA181 /* IQBarButtonItem.m in Sources */ = {isa = PBXBuildFile; fileRef = 336B4CC378FCC45D7E43E8E330E67E1B /* IQBarButtonItem.m */; }; + 0DCFD83A6149FC0514890A5ED67047B5 /* NJKWebViewProgress-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 68C17CA9F7C67D59F90F34E65B93D62E /* NJKWebViewProgress-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0EFB524EFDF2F8712A2F5067817A672E /* UIScrollView+MJRefresh.h in Headers */ = {isa = PBXBuildFile; fileRef = 3C3A79FA17ABD84F81F1074C87C73E34 /* UIScrollView+MJRefresh.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0F3CEE11E6552204415ED069B86372BC /* UIView+WebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 67B406F183DB1F705B966496FF984505 /* UIView+WebCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0F3DF5C3BEFCC9838B53C37735B414BE /* NSLayoutConstraint+MASDebugAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = D62B3C1698127F67086E6858CE18DE57 /* NSLayoutConstraint+MASDebugAdditions.m */; }; + 0FDB2B4F75591851F0F119EAE70B3F63 /* NSLayoutConstraint+MASDebugAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B8D6BCD909A41774E16030943339AEB /* NSLayoutConstraint+MASDebugAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0FDFFDFAF40F6A37B8911FA7C57428CB /* LKDBHelper.h in Headers */ = {isa = PBXBuildFile; fileRef = 5F98DCFCF300EBC97C2A16DCF1294D7F /* LKDBHelper.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 101F836F887C01B45F4DCF351EBC28D1 /* MJRefreshBackNormalFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = 43E2B344D60B305F452C5EFEB124C107 /* MJRefreshBackNormalFooter.m */; }; + 106D6F89336E06DBE4E973818BD887AA /* SocketRocket.h in Headers */ = {isa = PBXBuildFile; fileRef = F39CD7FEBA3936962AFCB24609CFA605 /* SocketRocket.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 13D87E1D99CFD98771E8066E6FF832CD /* IQUIViewController+Additions.h in Headers */ = {isa = PBXBuildFile; fileRef = B9F50AA966B1D80C51332499B80A5CFA /* IQUIViewController+Additions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 13DEE8E5A10BE2160E85D5B339446521 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */; }; + 14479278EA90F38247811468ADD8EBB7 /* IQKeyboardManager.h in Headers */ = {isa = PBXBuildFile; fileRef = AE26C6DD2E39EE7DC6BF9724F70BD49F /* IQKeyboardManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 148E57B8B5F299475BF5877A2EA6E7C1 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2C5FBC24791EAE0728C65D6F9B9912B2 /* QuartzCore.framework */; }; + 1563D7F05577852DD479C1BA3CFC24CC /* NJKWebViewProgress-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 147C7A5F29B419F15BD11AE9B4D6E40F /* NJKWebViewProgress-dummy.m */; }; + 15F6265FCE0955CDB4967F7306407D67 /* UIWebView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = D4D98F9C1B4313133F8617D4703C0673 /* UIWebView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1624AFE5A1732E1D58AB884329EB4C94 /* UIImageView+HighlightedWebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 5569AA726D3D85E6DF8895BAAE8DEBDF /* UIImageView+HighlightedWebCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 16831E5AE64E97E9BD8FA96E93C8DF19 /* SRWebSocket.h in Headers */ = {isa = PBXBuildFile; fileRef = 80EBC7AC78ACE04DDC3E429CC36690EB /* SRWebSocket.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 17F033046E658F3BFD0011DCB768CF54 /* MJRefreshBackNormalFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = 72E7FF6F0D74FA6229F49C74AD38E9D2 /* MJRefreshBackNormalFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 182956A69F1B4571D23008AD8C160B3E /* SDWebImageFrame.h in Headers */ = {isa = PBXBuildFile; fileRef = 7A2DE5C636CB7384C70AE55DEBC248F7 /* SDWebImageFrame.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1843E6DF520A5EFE9C83C38E18578E42 /* MJRefreshAutoStateFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = 95F6A7B21DB909CA345A47903CB4D39A /* MJRefreshAutoStateFooter.m */; }; + 19119F01A87FAA55D45B4F11F33B7B3E /* LKDBHelper.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D870611B8793D878F9166BF6ACFCAFB /* LKDBHelper.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 1ED505CC385A149F4DF8F4B94BA4FC0B /* MJRefreshBackStateFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = D23E765E4467A1A7780E0DA185FD0871 /* MJRefreshBackStateFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 22554065FA07F1BFE5308A685394CB12 /* FMDatabaseQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = 95A1ADBB90DEADD3CC0BB6D927F30DBA /* FMDatabaseQueue.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2524EC4EF024A6C067A0FA082084CFB5 /* MJRefreshBackStateFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = E45AFFE407A50EB7A6C9911EA9DA835A /* MJRefreshBackStateFooter.m */; }; + 2854C9B1086758BD2B6681206B6759B4 /* ViewController+MASAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 218DE19B389EE5088E7040712F0704B3 /* ViewController+MASAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 28D57235593277A82B18D9E2B3B4B5ED /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DD9F8097FDD26C1A767654BEFDB692CC /* UIKit.framework */; }; + 291C24EA8B69C1738694B0729ED3ADA4 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DD9F8097FDD26C1A767654BEFDB692CC /* UIKit.framework */; }; + 2AFB0AFA2138181E162CD00669D87FE3 /* JSONModelError.h in Headers */ = {isa = PBXBuildFile; fileRef = 84190D645A029D929576CE3874A30E53 /* JSONModelError.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2B0AD5F72C574005D53D512A8F8E2800 /* FMDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 167E9F1BB5C566ED575F9AFA45711349 /* FMDB.framework */; }; + 2B66A577AE7687E6001469BF9F99CA5B /* ImageIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0ABED0039D2F20276FEA3153C100C8EA /* ImageIO.framework */; }; + 2C5EA66B987D887948303DB77AF68D61 /* NSObject+LKModel.m in Sources */ = {isa = PBXBuildFile; fileRef = 94FEA07F421E380A35B094F7568EAF10 /* NSObject+LKModel.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 2CEA12D52F3F7AC0669C99A157E19F62 /* MJRefreshBackGifFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = 3C2E772FF38560DBD9204DA3173B1368 /* MJRefreshBackGifFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2D170EDC2BE147629AF7D661BCDBD2AF /* NSImage+WebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = A1984BDF5C4B9F316463CFAE01F131B6 /* NSImage+WebCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2D407C6492BC569F5361B9210C89A19C /* IQKeyboardManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 65DC0A6004D8CA989364A1123D836695 /* IQKeyboardManager.m */; }; + 2E2BA6CBA0D6349BF6CF9E13753D5DBD /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */; }; + 327E1782C89B350FDE631F3CACD4C8A2 /* UIImageView+HighlightedWebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 86B4DD8A5BE1003157681F47B9A06D90 /* UIImageView+HighlightedWebCache.m */; }; + 3345805C0D8E8D0726F7E5981DA61A5F /* UIWebView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = D7AE865D229ADE1C34958B1CED9B69F9 /* UIWebView+AFNetworking.m */; }; + 3376AE1663C14F1926F04D4FE0225E97 /* SDWebImageTransition.m in Sources */ = {isa = PBXBuildFile; fileRef = EF647DB47CA8072604B32A11D318121C /* SDWebImageTransition.m */; }; + 344DB99F8332029C0391F08B6D0E425C /* MJRefreshAutoNormalFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = 339D6D016535F8109AC998611978456D /* MJRefreshAutoNormalFooter.m */; }; + 347945A5FC349A6E31AC7E3403E2CDE5 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */; }; + 35D685CF7C6F73A65AD3DD99674CA78F /* MJRefresh.h in Headers */ = {isa = PBXBuildFile; fileRef = AD7E0507C28D6B5E81792E2F089A883B /* MJRefresh.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3619E77A8EC11571EE9F32921DAC0C89 /* IQKeyboardReturnKeyHandler.h in Headers */ = {isa = PBXBuildFile; fileRef = 22262DD61DBB977FA2942AD0D070C595 /* IQKeyboardReturnKeyHandler.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 36E344E5B627E04368ECC96338E17F26 /* JSONModel-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 4A9D286E65BE10630D2D01808B376E3F /* JSONModel-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 37F097E2269EF1BD238AD7449D796445 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = 69C00A3ED643BFA7CBFB31DC4CB6E601 /* FMDatabase.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 37F6913EE3CD6EB8715086F0C9F6A823 /* JSONValueTransformer.m in Sources */ = {isa = PBXBuildFile; fileRef = 1B2D027604F0FD4DDC858BCB8413D135 /* JSONValueTransformer.m */; }; + 37FD169854FF4B397051998D611F152A /* JSONModel.h in Headers */ = {isa = PBXBuildFile; fileRef = B2A3E53B989849FAD2CD8B551234827B /* JSONModel.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3829CBCC3598DB13C2AD3B7383D1F24A /* MJRefreshFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = 4D7894D466D10E51479750206920F843 /* MJRefreshFooter.m */; }; + 38A1AC3A26C93B53FCD959E136990990 /* UIImage+MultiFormat.h in Headers */ = {isa = PBXBuildFile; fileRef = 7FD3A5585C7A6F8C8EBD39C59F4BCF02 /* UIImage+MultiFormat.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 38E0CD63021889EE46E1A6B9FA0415F5 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DD9F8097FDD26C1A767654BEFDB692CC /* UIKit.framework */; }; + 39120D78F1F32B35C353A9EBA0149B45 /* SDWebImageManager.m in Sources */ = {isa = PBXBuildFile; fileRef = EF2886493D8197A42561F3F3282F8612 /* SDWebImageManager.m */; }; + 39530A48FC40F64E8B08B45AD5555D0A /* SDWebImageCompat.h in Headers */ = {isa = PBXBuildFile; fileRef = E299BD8696B2E375B3B2FB48F530F119 /* SDWebImageCompat.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 39A98121DA410F19CE5F46E280F22179 /* SDWebImageDownloaderOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = 671B1C68838C43D897AF46AADD606C4A /* SDWebImageDownloaderOperation.m */; }; + 3ACB80ACD4B743F9EAD47339F10594A0 /* Toast-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9B608913B805E97D3B45F563A37ABCEB /* Toast-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3C9E113B7712442B4BCB59AB7EEC2085 /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 105F2F5DE7034DDDB46A5FF6C1257C53 /* AFURLResponseSerialization.m */; }; + 3DDB894364CEC991E61B04E9036D6D54 /* AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = EF729ACD28BC9F84101647D920D4287D /* AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3E43906B70EB01C06F3AE17008B853B9 /* FMResultSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 60DE6EFB52862BBD769E650DE1A53D87 /* FMResultSet.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 40A6216FC50B4540584DA1C45F98F9FD /* JSONModelClassProperty.m in Sources */ = {isa = PBXBuildFile; fileRef = 270737E79A641CBC04762BA9F997CE18 /* JSONModelClassProperty.m */; }; + 40E6B7A671DFD76170156328D995546B /* NJKWebViewProgress.m in Sources */ = {isa = PBXBuildFile; fileRef = B4DF3C7BB807E1348544AA2900CC9BCC /* NJKWebViewProgress.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 41BA2631080F7FE9052001D51A5104E7 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */; }; + 431C76067CB09B1FC0E4DD5AEA6B540A /* IQUIScrollView+Additions.m in Sources */ = {isa = PBXBuildFile; fileRef = F75D7F8DB268EAE736A191EE0B8F9761 /* IQUIScrollView+Additions.m */; }; + 432FA22864D148EBD4CB22F55AB68004 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */; }; + 43E74DBE8C8D7F79A45B9344D2D2D1BD /* SDWebImageCoderHelper.h in Headers */ = {isa = PBXBuildFile; fileRef = 1F3542CD47C057D6C551C30C3B46D2DB /* SDWebImageCoderHelper.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 457ACF9150DCF9AF445B129CC9678FB6 /* Masonry-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 8CB53A6BCAB7A1F76E7F79652415A592 /* Masonry-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 48B6FAC56A1A05850F229702C850CDB1 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2C5FBC24791EAE0728C65D6F9B9912B2 /* QuartzCore.framework */; }; + 48EEC19D6C3DCAD43836914B8D0F1EB9 /* SDWebImage-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 29C6CB0E4CB91AB0517A62CA7D3D4C95 /* SDWebImage-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4985E014269593640635A8DBD75DA450 /* NSObject+LKModel.h in Headers */ = {isa = PBXBuildFile; fileRef = E8317B8AC22FB1696D93176C5E5DD172 /* NSObject+LKModel.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4AA21F40697CB42D7D219ACEDE4FBFCF /* AFAutoPurgingImageCache.h in Headers */ = {isa = PBXBuildFile; fileRef = D0BBA864722B591909F62D13DC4EEB0D /* AFAutoPurgingImageCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4AA3A9FC9AAD94C226CA975946C9395B /* UIRefreshControl+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 2368EA7094707071EF9EB1847081B539 /* UIRefreshControl+AFNetworking.m */; }; + 4B8BFD0889A2513D7BAB9D582C077810 /* TTTAttributedLabel.h in Headers */ = {isa = PBXBuildFile; fileRef = B597ABA83FF34D41BD88B02629DFF141 /* TTTAttributedLabel.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4BA2F37913AFB59DC45A84CA29AAB2F8 /* UITableView+FDKeyedHeightCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 22C882FD98CA446EFA39A29BFF94A28B /* UITableView+FDKeyedHeightCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4C321BA8844AA4C44D4416CC6948DF2B /* AFNetworking-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 422402DD22D498220638075EF90B07A3 /* AFNetworking-dummy.m */; }; + 4C5DA96F7CAC26975EEEBD7450FF214D /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = B5FB7DF227C9ADBFB34C1E276FF37EAA /* AFURLSessionManager.m */; }; + 4CC5EC830A89C3CB7F53C52CDF13CF81 /* UIView+Toast.h in Headers */ = {isa = PBXBuildFile; fileRef = 7567613ABCFDCEBA938593A0036C32A9 /* UIView+Toast.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4D4F2050654580FE1F1D5F4F82CEDDB8 /* MASConstraint+Private.h in Headers */ = {isa = PBXBuildFile; fileRef = 417E2E632AF904B3B32155C62F0B19DC /* MASConstraint+Private.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4EB17293737C717D12298CFFE6A67514 /* JSONAPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 43189891007DC8B214462EE40E661B70 /* JSONAPI.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 53514C9A8CBD604E5DE2ABFFB322C3AE /* SDWebImageTransition.h in Headers */ = {isa = PBXBuildFile; fileRef = F66E969B978843AD18F5745FC07B3C9B /* SDWebImageTransition.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 538E922BA03E8B2C147BF047ED195DF4 /* SDAnimatedImageRep.h in Headers */ = {isa = PBXBuildFile; fileRef = 6631EE01B7EC6B5EF820B3874307CCE0 /* SDAnimatedImageRep.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 53BDF81D0A52EA526D597A5C5B139D7F /* MASCompositeConstraint.m in Sources */ = {isa = PBXBuildFile; fileRef = 673F2354B6D1C0F8E9955046A21D6A4B /* MASCompositeConstraint.m */; }; + 5423F7BB578AF69EEFD339909261F01E /* SDImageCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 8CDF9E3C2D2416AC7550ED950AB0CC88 /* SDImageCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 57E9B041CC1D8988C38DDC97CAEFCD76 /* MBProgressHUD-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 6C18F3E40A6F8667E93BF7E113A19F41 /* MBProgressHUD-dummy.m */; }; + 57FE38F17C0EDD5CF73B2A084A17586E /* JSONHTTPClient.m in Sources */ = {isa = PBXBuildFile; fileRef = DBDB01D83E6928E50B7FF753E107C53A /* JSONHTTPClient.m */; }; + 58388F773008AF671CE67FE1C902E6CB /* JSONKeyMapper.h in Headers */ = {isa = PBXBuildFile; fileRef = EAFD436D5E0537D470329DFCF3A97191 /* JSONKeyMapper.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 58E6E68D10EF3D64522BD267CC1761A6 /* NSBundle+MJRefresh.h in Headers */ = {isa = PBXBuildFile; fileRef = FA61AF596C08910907F9123EEB554A9B /* NSBundle+MJRefresh.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 59F5736C531C7F4C5F79C9EDDACC0B64 /* SDAnimatedImageRep.m in Sources */ = {isa = PBXBuildFile; fileRef = 771FAC488702BC45D9B3E1C95287F985 /* SDAnimatedImageRep.m */; }; + 59F81DE0305CC2AC448D2A3C6B3280A2 /* MASConstraint.m in Sources */ = {isa = PBXBuildFile; fileRef = 30C9D2B8F917B8405C9B54173E51741E /* MASConstraint.m */; }; + 5B9AB2E420B063C994B8295F4EF48E37 /* UIView+WebCacheOperation.m in Sources */ = {isa = PBXBuildFile; fileRef = 49FC022BC0DDF2BFCA610030FC39F8BF /* UIView+WebCacheOperation.m */; }; + 5BC4E3F5EFAE7516C06D8A357407DCAF /* UIImage+ForceDecode.m in Sources */ = {isa = PBXBuildFile; fileRef = C0E318B9FCDDCC5AA2EF7612D8B92B1C /* UIImage+ForceDecode.m */; }; + 5BFE1CC79F693B6218B419AE50B2070E /* AFNetworking-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F898CDF03B802432B5C1BDB6EE59D826 /* AFNetworking-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5E0CA8102FFB7E6CB9B04DF6DEC83AEE /* SDWebImageCoder.h in Headers */ = {isa = PBXBuildFile; fileRef = 4BFD3AE7B418D1AB696243F283ECC7F3 /* SDWebImageCoder.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 5E1468EA73C7741EEC370E4A15167D0E /* YTKKeyValueStore-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 2BB9D5AF91DFC97D964A3278CD65C526 /* YTKKeyValueStore-dummy.m */; }; + 601FD63D1FC6DBB1277966362EE290CD /* Toast-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = E57E4AA31B3259BADDB06AFC1EC7C03E /* Toast-dummy.m */; }; + 6115C3ED460710318D33BBB7375B07A9 /* UIImageView+WebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 5A802226FA114075D3D6409ACCFB1EEA /* UIImageView+WebCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 621B413DAEFE75991251ED378822527C /* MJRefresh-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 7105E6B5675EAB9B1DB66075A38FC383 /* MJRefresh-dummy.m */; }; + 6298B1C2234864DA5ED3B5E6398B95AC /* MJRefresh.bundle in Resources */ = {isa = PBXBuildFile; fileRef = C3ABE0317E38D1EFCDEEDCB80F2C86D8 /* MJRefresh.bundle */; }; + 636BBA734C1A17A734761D674FAE8800 /* MASViewAttribute.h in Headers */ = {isa = PBXBuildFile; fileRef = 0B8497F4D647973F7EF7F63CA4433C95 /* MASViewAttribute.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 639A86F8EDAF569092C61103FFAEA21D /* IQUIView+IQKeyboardToolbar.h in Headers */ = {isa = PBXBuildFile; fileRef = C68E6D01DE9F66C2C15D29D4D81D7DD0 /* IQUIView+IQKeyboardToolbar.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 63BA6FBA10304F4828DE97C0FA63ED9D /* UIProgressView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E836B7746FAE9BCF200AD6092BEA26FA /* UIProgressView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 63F5BA839B931DB6605554B6D4369A0C /* IQUIView+Hierarchy.h in Headers */ = {isa = PBXBuildFile; fileRef = F84E6ED65E201E2FB224E9591458D599 /* IQUIView+Hierarchy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6478B0091202F9429D2A61E30BEDA571 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 47FC8BC593D3C4A9BCFAAB1AD76AC13D /* Security.framework */; }; + 6595C6295B9EBBF40751A376239681FD /* UIProgressView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = FEC5B235D8066671988C356BB8479445 /* UIProgressView+AFNetworking.m */; }; + 65EC43DAB5ACAAEE8F1CE61529A09102 /* YTKKeyValueStore.h in Headers */ = {isa = PBXBuildFile; fileRef = 73EB4D54E40F7146E8F50D99256E3AB6 /* YTKKeyValueStore.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 665B3B037B98D3E3ADB449A43FF14F42 /* IQUITextFieldView+Additions.m in Sources */ = {isa = PBXBuildFile; fileRef = D50758F82022F3137CBA65220EEAE68E /* IQUITextFieldView+Additions.m */; }; + 68168E99337712B83A79810B55602D01 /* NSData+ImageContentType.h in Headers */ = {isa = PBXBuildFile; fileRef = DE6B846782E8125465DD1F586A583755 /* NSData+ImageContentType.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 688E0882DFC8CABA02390F43178CB33F /* IQNSArray+Sort.h in Headers */ = {isa = PBXBuildFile; fileRef = 8CF4ACF01E4CEA3CAE293EF3F4CFB20D /* IQNSArray+Sort.h */; settings = {ATTRIBUTES = (Project, ); }; }; + 6A0B1A0FA7A75C861B9D401D0E8CC95E /* MJRefreshGifHeader.h in Headers */ = {isa = PBXBuildFile; fileRef = CDC9C0D785840A863C238FA9918232BF /* MJRefreshGifHeader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6A30D4D71707D4B4B6033AA5399D35C6 /* Pods-GIGA-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = FD113136C3BE7E4822B80A29F3DC5E42 /* Pods-GIGA-dummy.m */; }; + 6AB8F78680B3470391219F11D51A1DE7 /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = C5201CCF6BAA96A03DE5923F727DC879 /* UIImageView+AFNetworking.m */; }; + 6C23BBF56ED4DCC10CA1765A6736D1F8 /* MASLayoutConstraint.m in Sources */ = {isa = PBXBuildFile; fileRef = 76E253E1BAB6E3A4164B42F93C3B0EE8 /* MASLayoutConstraint.m */; }; + 6D13591A430260C31F6102B30645B5CD /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */; }; + 6E6E8ADF2879B9F6832CE82F2B538366 /* LKDBHelper-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 7EC0F45B5A1A9049F0BA580A2E665024 /* LKDBHelper-dummy.m */; }; + 6F5906B58272E07A0850248867562581 /* JSONModelLib.h in Headers */ = {isa = PBXBuildFile; fileRef = C2916A23C5B0F16555EFB6F4420162BF /* JSONModelLib.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6FAE8BF1BF564D1F2D5F368F8704A6D1 /* UITableView+FDKeyedHeightCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 2127EDE3F7D3FA57134EACCE79E57C4B /* UITableView+FDKeyedHeightCache.m */; }; + 6FF8739ADFFE8465389AF3F0603E6F83 /* LKDBUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 14A57F7FDCD24207067E3E300876540C /* LKDBUtils.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7099E4035C06D3116DA2586EFE563C0B /* AFAutoPurgingImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = A9BD5EC9B66096A214F0369AC4DB24E4 /* AFAutoPurgingImageCache.m */; }; + 71F6D96E3AEAA07389F37E2C4B63C4F6 /* MJRefreshHeader.h in Headers */ = {isa = PBXBuildFile; fileRef = F92F1C168C292C57C28B8CB8572DA418 /* MJRefreshHeader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 72563ADE99DC9E753B27D48B16AA3654 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */; }; + 72EE4A5DC3076CD8C13717D4DAA37DFD /* IQTextView.m in Sources */ = {isa = PBXBuildFile; fileRef = 0FF2FC65CD5737B5207D47B6520D5FC7 /* IQTextView.m */; }; + 73BBDACC22CCA36A6DAAA167AD780BAF /* MASConstraintMaker.m in Sources */ = {isa = PBXBuildFile; fileRef = 9404C50D3CA53F5CBA8FB043A06BFAD6 /* MASConstraintMaker.m */; }; + 756DF24546C7D91459DCADC8F1C98660 /* MASViewConstraint.m in Sources */ = {isa = PBXBuildFile; fileRef = 402AA4AB24F2AD705593DD3FB991387B /* MASViewConstraint.m */; }; + 76C5CEA598337CC1FC825899FF1CDAD9 /* SDWebImageGIFCoder.h in Headers */ = {isa = PBXBuildFile; fileRef = F60AD73AF21127AF807A87155E176BB2 /* SDWebImageGIFCoder.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 772785574BC1059C2913576CBFF3AD17 /* JSONKeyMapper.m in Sources */ = {isa = PBXBuildFile; fileRef = 99E94B95014F639BCEFE5DE77CF86A13 /* JSONKeyMapper.m */; }; + 788BA72F67004504FFDFC670048786B5 /* IQKeyboardManager.bundle in Resources */ = {isa = PBXBuildFile; fileRef = FFFC1D06E09FCB725E5075FB470389CA /* IQKeyboardManager.bundle */; }; + 78AC6714960C42CC866222B6D956EDF6 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 223CC88B609D08C4EA1EC854A8D73AD1 /* CoreGraphics.framework */; }; + 7942D242D079A5710A72B659A54D7E26 /* MJRefreshNormalHeader.h in Headers */ = {isa = PBXBuildFile; fileRef = D1BEE5EFF3DDAAB7DF105B6EE039CC8A /* MJRefreshNormalHeader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7AE9484F09D29428653109D73D4FC488 /* NJKWebViewProgressView.h in Headers */ = {isa = PBXBuildFile; fileRef = 954FBC78E632E1BCD88EEB65027EAEDE /* NJKWebViewProgressView.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7C17BEA6034027310D1D205DB2008CA5 /* MASLayoutConstraint.h in Headers */ = {isa = PBXBuildFile; fileRef = B77606B69936F395DA6F6B9FF330A961 /* MASLayoutConstraint.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7C49A18841060D12A58F92CE62C21F9D /* IQNSArray+Sort.m in Sources */ = {isa = PBXBuildFile; fileRef = 2D47457D3CE1E0737C687DB3E4E896A0 /* IQNSArray+Sort.m */; }; + 7CF3668C8E30DA3CAB92C9C6A8B88B8F /* IQToolbar.h in Headers */ = {isa = PBXBuildFile; fileRef = 00F8BF23D01B2525D48EF9EA2FF41BB9 /* IQToolbar.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7DE362297135870194FA02C34D3135E7 /* TTTAttributedLabel-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 0B7DB276EA29841EF61406CACDDBA7DF /* TTTAttributedLabel-dummy.m */; }; + 7E40D4939F89C4852C4224D6A65E6BD5 /* SDWebImageImageIOCoder.m in Sources */ = {isa = PBXBuildFile; fileRef = A7D9C6AE37D287719040FA3D994C8059 /* SDWebImageImageIOCoder.m */; }; + 7E653E1D9DF593D82DEA20D2340F2C1E /* UIImage+ForceDecode.h in Headers */ = {isa = PBXBuildFile; fileRef = 4FA220EAF4B2366FE3383A5AF8AD3D27 /* UIImage+ForceDecode.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7EFDAA1642FA83DE777CFD086182D5A4 /* MJRefreshAutoGifFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = 886A7A948A578AF0481B05CD6E2FAE30 /* MJRefreshAutoGifFooter.m */; }; + 7F37E7BCFFC785854FD19F23B89C39AE /* UIView+WebCacheOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = 053476A95CBB33D3F007559250E2E712 /* UIView+WebCacheOperation.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7F66E5779B29E0BC17D565DAD7CDEC1B /* JSONHTTPClient.h in Headers */ = {isa = PBXBuildFile; fileRef = 1E49FA87D6265A153A6A377608BF76CF /* JSONHTTPClient.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8060025235D93F30A5F10B412DD0822E /* JSONModel-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 26C29828B683FB67FD6E1E218F63F152 /* JSONModel-dummy.m */; }; + 8069223DDD6D0F2E1A87D8E66966709B /* MJRefreshConst.m in Sources */ = {isa = PBXBuildFile; fileRef = B1A17C97B5BA3258AF5BFA6C4CB10011 /* MJRefreshConst.m */; }; + 8138BA0A46637819E90CE18C773CA9FD /* SRWebSocket.m in Sources */ = {isa = PBXBuildFile; fileRef = F2D330C281F30235A5D8E2C8D8CC7445 /* SRWebSocket.m */; }; + 81ABD96C8FA6FF28CFB2A3A78A6EA560 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F79298FCF0E5B2FCDD163272B33DB5DE /* SystemConfiguration.framework */; }; + 81D12B648C1E782DEC1B2566EE17FB6A /* UIImage+GIF.m in Sources */ = {isa = PBXBuildFile; fileRef = 04AF8FBCCAA5C10FBF5C8D678095B349 /* UIImage+GIF.m */; }; + 85F02B2E2F922F439A12C7CBB077E8DE /* IQKeyboardManager-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 362634D02C8734DCDBB1B3FA29AF2E5A /* IQKeyboardManager-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 86EA527BA1862E06A8E19E0960C66E7E /* UIRefreshControl+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 723FBBA74F07E67C701AE828B5405E83 /* UIRefreshControl+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 87ECA447DB887426665260651B7F147E /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = 918438D2584B201AE3B75ECE63C18CD5 /* FMResultSet.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 88DE7BAB1F4999A5F4B617F44E5FD1D3 /* MASConstraintMaker.h in Headers */ = {isa = PBXBuildFile; fileRef = D3042F160C52C7D88773233C16FADD9D /* MASConstraintMaker.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 89637BFFD180A1E05F04DAF0CF4A6540 /* MobileCoreServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BDA80F5D7B6C75DE56A43090A20E478E /* MobileCoreServices.framework */; }; + 8A1EB96C607F92E8AA20676F9A4BC7D9 /* UIButton+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 95E1101C679649DD67CF310BC7C41D40 /* UIButton+AFNetworking.m */; }; + 8A6EEF68E7625AB66A3A8DED1594F88F /* ViewController+MASAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 9D0303615C02A9FC06E4284A85443DC1 /* ViewController+MASAdditions.m */; }; + 8B855A73B75155FB2C0CB05B54FDDE0D /* UIScrollView+MJRefresh.m in Sources */ = {isa = PBXBuildFile; fileRef = 2027232FAF2C4FD8C62B41D1443F10A8 /* UIScrollView+MJRefresh.m */; }; + 8C2908931C952C7B1801BC7D5D321BED /* UITableView+FDIndexPathHeightCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 08E127FD35CF12E2DFEAE98245B87676 /* UITableView+FDIndexPathHeightCache.m */; }; + 8C9165B82240F78C43F7E7ACFD17612B /* NJKWebViewProgressView.m in Sources */ = {isa = PBXBuildFile; fileRef = 4B3F07A870FB3A3BFB758AD0E1BE2C36 /* NJKWebViewProgressView.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + 8CD45B754192DE834B642975E85257AB /* MASCompositeConstraint.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F239ADCBC9530CFB69A3DBA4606CB39 /* MASCompositeConstraint.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8D9636C74777C684BDF312EE66F8A585 /* AFNetworkReachabilityManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 125D8E7B25DE48B829EF26B5A344B3D0 /* AFNetworkReachabilityManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8DC3FC2342EC2E944B3A3E83E2683130 /* MJRefreshHeader.m in Sources */ = {isa = PBXBuildFile; fileRef = 9271B8514D90DCA03D6343D0CDCE050D /* MJRefreshHeader.m */; }; + 8EF496E24AC25617194114DDB71D5385 /* SDWebImageFrame.m in Sources */ = {isa = PBXBuildFile; fileRef = 350E7464A1D787085E3C8AB20B8D3699 /* SDWebImageFrame.m */; }; + 91D993FDEE2D0C2D3B4047D9E8BEE9BA /* UITableView+FDIndexPathHeightCache.h in Headers */ = {isa = PBXBuildFile; fileRef = 623CEFA44508E2233D6C8BDDC1A723AB /* UITableView+FDIndexPathHeightCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 92126299C232FC474021BADE26F056A4 /* SDWebImageGIFCoder.m in Sources */ = {isa = PBXBuildFile; fileRef = 9BDE845BAEED6040E590CA9903B14998 /* SDWebImageGIFCoder.m */; }; + 939EF882233B22D0321A70F6DADED11F /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 54F3536A4C88BAB5768A5110E968D42E /* AFHTTPSessionManager.m */; }; + 93BF58C19C5E6A78EDAA38855DDDE348 /* NSButton+WebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = C1023377CD29F52DBD86B670EC330990 /* NSButton+WebCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 958FEEE31215AB970371D4CBAEB8A4DC /* IQTitleBarButtonItem.m in Sources */ = {isa = PBXBuildFile; fileRef = D8024B8DF0B73056894292AB56168798 /* IQTitleBarButtonItem.m */; }; + 95A76E599F3448FD0E5C736D98354DA8 /* YTKKeyValueStore-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = EA582EA6A55F892186937BD64F6CA1C5 /* YTKKeyValueStore-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 96E70B43FC04BC99AED1BBD4FB1D7581 /* FMDB-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F64387C5F8EF527B7D20778BEE103274 /* FMDB-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 971255F19D9DC5EEC2566D186FB5A433 /* UITableView+FDTemplateLayoutCell.m in Sources */ = {isa = PBXBuildFile; fileRef = F72E8914E30DFA385018D03B6F117C98 /* UITableView+FDTemplateLayoutCell.m */; }; + 9898B13B5771AC304E096319E72F8098 /* AFCompatibilityMacros.h in Headers */ = {isa = PBXBuildFile; fileRef = DAEB829C6F88208F28EE3BB434586358 /* AFCompatibilityMacros.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 98F19C682AC68E9D2E2052F709F42AF9 /* JSONModel+networking.m in Sources */ = {isa = PBXBuildFile; fileRef = 967FC3D6EE75AAC4E5853A52FC40FBD1 /* JSONModel+networking.m */; }; + 99249B44D65716B5CCA0BFFD5F83062C /* IQTitleBarButtonItem.h in Headers */ = {isa = PBXBuildFile; fileRef = 5AF74F6EDDDBDE1594378798EDC8F75B /* IQTitleBarButtonItem.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9AC1064802A4D107353A87F2B4A963B0 /* AFNetworkActivityIndicatorManager.h in Headers */ = {isa = PBXBuildFile; fileRef = F9D614BEB063937B5BF5775FECFC299E /* AFNetworkActivityIndicatorManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9B8D84996694C541CD3434386E0A081A /* FMDatabasePool.h in Headers */ = {isa = PBXBuildFile; fileRef = C7949A099C444A21B8BF2123F5474A11 /* FMDatabasePool.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9C11A290C9C5866A185A54F1EC04E2BB /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 1E7820BA9423CD0C1D2DAC362014ED4B /* FMDatabaseAdditions.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + A08A8AB356264E248D01F1BC0EF08166 /* Masonry-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 491FD42A9D3970BD3ACF252F98B968EB /* Masonry-dummy.m */; }; + A12A3BC640B690479F345A49C6C48209 /* AFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = F5F9245FC6E3E879D3070CAC3CE9039E /* AFNetworkReachabilityManager.m */; }; + A1B5D80A8998311B8C9043E6942925E6 /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = 9CB6460D14EA9B327CE96B0450FA717B /* FMDatabaseQueue.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + A1BB32FF4BE29C004A13F2E03127E8F1 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 223CC88B609D08C4EA1EC854A8D73AD1 /* CoreGraphics.framework */; }; + A2D9F9EFFDFE9C19DA842E826B06BCEB /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */; }; + A3CE2D718CEB5AC059823178404AF0EF /* IQKeyboardManager-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 951A926C2E402064AFF54E885DEE23D1 /* IQKeyboardManager-dummy.m */; }; + A5382D3EA98D2EB1AD9EDA5F2138F00D /* MJRefreshAutoNormalFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = D4372399A31F995ED53980B44F7B90A0 /* MJRefreshAutoNormalFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A548833BE5FAD40830428F36E77D0F52 /* FMDatabaseAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 94752DBCE44CA942E27A896C7CB73B8D /* FMDatabaseAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A5B069CA1170E03891AC5648DE5CF87D /* UIImageView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 6AD72E84C0BAA5647385371F3B370E7D /* UIImageView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A72D242BEF61E27D6C29092DF4666A4A /* MJRefreshComponent.h in Headers */ = {isa = PBXBuildFile; fileRef = DDAD4BFB56B1F3E882395A34A77631FC /* MJRefreshComponent.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A7370CE9231F9A4927142D79021879EC /* MASViewAttribute.m in Sources */ = {isa = PBXBuildFile; fileRef = B27B051036F118C3C3CD87D2112F68DA /* MASViewAttribute.m */; }; + A77943B15F7CF5151B637808B40DD722 /* LKDBUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = A81B52350911B789957965FA41897580 /* LKDBUtils.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + A91C005A46878C2DB5B6B4A67CC1DDC4 /* SDWebImageCodersManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 7714D1833FFBB408B18F2747E65E5790 /* SDWebImageCodersManager.m */; }; + A9A91BA2015E3033BF4DAD29264D03F0 /* SDWebImageDownloader.h in Headers */ = {isa = PBXBuildFile; fileRef = F63B516844D3BA3C6CC53B029BFB6C1D /* SDWebImageDownloader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AA00DCC0C8174B2D7E48EEC3C768B047 /* MBProgressHUD.m in Sources */ = {isa = PBXBuildFile; fileRef = 272CBD0843CB816395E98BA936E24B87 /* MBProgressHUD.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + AA4959949A290D4B8BE1E31A890D0C80 /* MJRefreshFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = 0995F8AABB71D527DE51897FA8F83BA9 /* MJRefreshFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AAC6DB8270C474C50F5D71DE9BC73382 /* IQTextView.h in Headers */ = {isa = PBXBuildFile; fileRef = EB20094359DE221C41846E960C38BB8B /* IQTextView.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AB2CEAF630532A05339889D5663E1C08 /* TTTAttributedLabel-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 6930C47F6DA9FF53FCC809972D1C2267 /* TTTAttributedLabel-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AC5F946DEC898FE1FE7BA74426FE6A8D /* LKDBHelper-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 732E1114AA44818AFA36C115D6C2E3B3 /* LKDBHelper-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + ACA82B48BEE47C89F7AEE07F4F8B462E /* UIImage+MultiFormat.m in Sources */ = {isa = PBXBuildFile; fileRef = E9B9FF3E9F69E2D04EB243D2A2B0D44A /* UIImage+MultiFormat.m */; }; + AD868043328B2125E27A5DC14D11958F /* UIActivityIndicatorView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6F21509CADAC096896FDF9E0A67980E /* UIActivityIndicatorView+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + ADD011E9ABBD96D70AAA32A4B9ACBD02 /* UIKit+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = 6FD79569D1481B1CCEBC524AE5E2B8C0 /* UIKit+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AF5A5DF8096192FC74E02A3408AADC21 /* Toast.h in Headers */ = {isa = PBXBuildFile; fileRef = B6800D584E4D1A1A19C71F4FD327A635 /* Toast.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B02D91E02099D3C6A2F988C766032176 /* MJRefreshBackFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = 598F5B2A218C7D65218EE2E74A1FAB90 /* MJRefreshBackFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B05BDA89A18DA866355AD804B694F851 /* IQUITextFieldView+Additions.h in Headers */ = {isa = PBXBuildFile; fileRef = 4B4ACAA5FE6E4D692115FD521BCB1287 /* IQUITextFieldView+Additions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B086C8017A694E281B3F30DCCE8FA588 /* AFHTTPSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = AA70955B3AF65BF0DC77A605CF3D7DED /* AFHTTPSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B0E60D4A86434F567D7F9E590161AA7C /* UIView+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = E9CC4C0DA475DA5B31053CF995EC62C0 /* UIView+WebCache.m */; }; + B1C1164914E351C022A5C6637E8599BF /* SDWebImageManager.h in Headers */ = {isa = PBXBuildFile; fileRef = 4A2AF264E571B9997B0965D66283EAA6 /* SDWebImageManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B215AD383364D4C829F4EC9803568809 /* SDWebImageImageIOCoder.h in Headers */ = {isa = PBXBuildFile; fileRef = 957C4EAC3550D522CFC086D33020AF15 /* SDWebImageImageIOCoder.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B21C3C93DAA23B1C331B9326991CDCFC /* IQKeyboardManagerConstantsInternal.h in Headers */ = {isa = PBXBuildFile; fileRef = 6FD513AB29E9316802D99A9C3C9BE9F1 /* IQKeyboardManagerConstantsInternal.h */; settings = {ATTRIBUTES = (Project, ); }; }; + B26E3D1F70F70E23C4EDA96CC327BC1E /* SDWebImageDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = F11F0CB1B9CA018793DBBE97E44883F4 /* SDWebImageDownloader.m */; }; + B44383A3FA435C1E986942C817339302 /* View+MASShorthandAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 6AB8391ABC38E6024FB65A20D3351A17 /* View+MASShorthandAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B46FE8C00C2CDDE0B4790FFD3DC961A4 /* AFImageDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 8C9BAAF1EC72C985C348BCF60EC4D10A /* AFImageDownloader.m */; }; + B646C96E2D7DF54445B3719F800D79E9 /* MBProgressHUD-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 7C92D2200160EED2E09E78F7DC6CAE4A /* MBProgressHUD-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B690948AF82E335069677012C9793C0A /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 47FC8BC593D3C4A9BCFAAB1AD76AC13D /* Security.framework */; }; + B72A7B6970A8E91258D4AC521B86A8B0 /* SDWebImageCoderHelper.m in Sources */ = {isa = PBXBuildFile; fileRef = 54BA54731B31CD6D22D2D59BBE0D5608 /* SDWebImageCoderHelper.m */; }; + BA0711638621C2A47AABFF9E03546893 /* MJRefreshAutoStateFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = 5CF1B2D752E061B673D94FCB8D0E7610 /* MJRefreshAutoStateFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BDB33C3708110C6D755175D1F0A2A70B /* MJRefreshStateHeader.h in Headers */ = {isa = PBXBuildFile; fileRef = D5DA3E8C666672F7C13E27E88DD39873 /* MJRefreshStateHeader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BE342AF4C9583018FBDF18A52FAE927A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */; }; + C0337E1DD3AA7BD36B20A9C92EA3208F /* SDWebImage-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = B0455BB0F27DA9FDF09E6D7A8D38B2D8 /* SDWebImage-dummy.m */; }; + C0A16E00B4BC2D88A7833D5DAED62942 /* NSArray+MASAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = 72E288068C58BB673219CEFB1686BC93 /* NSArray+MASAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C0BD02712FC62F45C60CA65FDCF21D80 /* NSButton+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = BE6A57C1E6EE6E72829EF1A0239DD712 /* NSButton+WebCache.m */; }; + C0F07BA73BBC072EFCABCED3B6D24604 /* TTTAttributedLabel.m in Sources */ = {isa = PBXBuildFile; fileRef = 4CE36714FF24257CBB6D4A43CE11D871 /* TTTAttributedLabel.m */; }; + C12BAA822391D670C53FF0C2299654AD /* AFURLSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = BF83FBC6FB90CE550B6AF3F1CB2F1277 /* AFURLSessionManager.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C257BE809D4C4357A8EB7118960E3143 /* UIActivityIndicatorView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = E7CD153E51D85BD9B97F92233C5BD64F /* UIActivityIndicatorView+AFNetworking.m */; }; + C2B7F4EB405C401EA53023341C05E15E /* IQPreviousNextView.m in Sources */ = {isa = PBXBuildFile; fileRef = EF536E6DCD40B46C2DDB4A7B5CDF9949 /* IQPreviousNextView.m */; }; + C480AC5D32406D4901116FCAC5FB0EB5 /* IQUIViewController+Additions.m in Sources */ = {isa = PBXBuildFile; fileRef = E838CA14206F7C95DDF8E5A291D3845A /* IQUIViewController+Additions.m */; }; + C49ED0BA3BE26C50F202C5ED5FB85573 /* IQKeyboardManagerConstants.h in Headers */ = {isa = PBXBuildFile; fileRef = E7914083BC99732D0EB9526F21C3F14D /* IQKeyboardManagerConstants.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C4AA57B938513DE614A7B90AEF5CD858 /* IQUIView+IQKeyboardToolbar.m in Sources */ = {isa = PBXBuildFile; fileRef = 87D34EBA9583ABA27F69D9C80E8042A8 /* IQUIView+IQKeyboardToolbar.m */; }; + C5BCB61A9B530249DD0CEC33C6E07EB3 /* UITableView+FDTemplateLayoutCell.h in Headers */ = {isa = PBXBuildFile; fileRef = FB184C0EAA6CE1C593837FC6A4C4A7A0 /* UITableView+FDTemplateLayoutCell.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C605A44DF96E7FCACF7D6E37B62F795D /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = 491A04582FFB79FD874AFB04764A6F5C /* FMDatabasePool.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + C6CCF6FAC5899D681F921B1917ECD40E /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */; }; + C8DF22EAFFC2F81B0426E2165AC93E44 /* MASConstraint.h in Headers */ = {isa = PBXBuildFile; fileRef = 35877F4071E71D27BA630FEDB0FE43BA /* MASConstraint.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CA0D37AE5433954573D3E37771CDDBFA /* AFURLResponseSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 0437B58A81D211C5C568BBC32D5ED7EF /* AFURLResponseSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CA1E205A4D3A8515ED42F76C2671F1BA /* IQToolbar.m in Sources */ = {isa = PBXBuildFile; fileRef = 5BC59BC77E65287BF00DC491E679E48C /* IQToolbar.m */; }; + CB8230F8171A44F80B11C0BE0E8420AC /* UITableView+FDTemplateLayoutCellDebug.h in Headers */ = {isa = PBXBuildFile; fileRef = DCF7622A90866CFF5D62183257744DE6 /* UITableView+FDTemplateLayoutCellDebug.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CBA3B98ED2708713025BFD6F244D419F /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2C5FBC24791EAE0728C65D6F9B9912B2 /* QuartzCore.framework */; }; + CC8F9B4A1AC4E276EA8AA4C6F2BF3CD4 /* Masonry.h in Headers */ = {isa = PBXBuildFile; fileRef = ABDEED48273ED3899189469BF754EA64 /* Masonry.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CCB74062CE0F4B8E5B7483599BC398DA /* FMDB.h in Headers */ = {isa = PBXBuildFile; fileRef = 46C1C2B2A4BA6017298CF244B5B46838 /* FMDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CF4EB3350726A86BCCDF5F363C5FCE72 /* IQPreviousNextView.h in Headers */ = {isa = PBXBuildFile; fileRef = E85D699181AA7FA0C2BD301F59B6B2B3 /* IQPreviousNextView.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D02DEBC241C24DEEFDA13C355197A2FB /* UIScrollView+MJExtension.h in Headers */ = {isa = PBXBuildFile; fileRef = D77DAA3898C22DBC2AF3A8D090AC5F67 /* UIScrollView+MJExtension.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D0E7D5B865722A25EC7D91B0FAD8A6CD /* MJRefreshAutoGifFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = 6F0DCAD0FC2007DC95B13AE9D58DB89A /* MJRefreshAutoGifFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D1641F0A353E02D971A2E6C004D4D996 /* LKDB+Mapping.h in Headers */ = {isa = PBXBuildFile; fileRef = 756EBE270AB520A42983575D8062C88C /* LKDB+Mapping.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D16764F0C1C13D1FE859B4EA2B33E474 /* SDWebImagePrefetcher.h in Headers */ = {isa = PBXBuildFile; fileRef = FFFC1118336CE5A0F2379778BD1CBCFE /* SDWebImagePrefetcher.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D206EDC84CE44D5DC711ADD087BC4B17 /* MBProgressHUD.h in Headers */ = {isa = PBXBuildFile; fileRef = CBC3B8F0F4C790990E0EAD42A406FC8E /* MBProgressHUD.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D29CF1B9A1D71268C1F85EA53B32BA24 /* LKDB+Mapping.m in Sources */ = {isa = PBXBuildFile; fileRef = 78B556FE17B6F40F4C14A82F0936900C /* LKDB+Mapping.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + D2AFDC9DBB18F68AD5B7EE3A1A951D68 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */; }; + D46545D206874E3A223372C84F1EA73E /* MJRefreshAutoFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = 1137254611EEC2056578AEB819AA94C3 /* MJRefreshAutoFooter.m */; }; + D4E9B3DE75C23D365E255B6212CB1CB7 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */; }; + D51D64915E3DDF60300CB400C1F49027 /* UIView+Toast.m in Sources */ = {isa = PBXBuildFile; fileRef = 295F052A6A46300AE255CCA9D34FD7AF /* UIView+Toast.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + D54920CE34AFF30F529E61D9459C5006 /* UITableView+FDTemplateLayoutCellDebug.m in Sources */ = {isa = PBXBuildFile; fileRef = 2F9966C0F9F759260F26024DC5F6FCB1 /* UITableView+FDTemplateLayoutCellDebug.m */; }; + D5991941DC41DDDDDACAE0B5D47A4639 /* FMDB-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = C79F418E3B67CEA0D2E4853E93EB61D6 /* FMDB-dummy.m */; }; + D66E78D63935A98894E702D922AA8B91 /* MJRefreshBackGifFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = A03F70F63980CD170CD5750B6B5B2168 /* MJRefreshBackGifFooter.m */; }; + D7814F3ED165AA11096F7B172D35FD5F /* SDWebImagePrefetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 9F3FD02A35657C32B7608DD9E484CD49 /* SDWebImagePrefetcher.m */; }; + D820DE54D6E9E5C85E0F9BF8A399E5EF /* MJRefresh-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 2AE6A655C2E452806506AB901CB710BC /* MJRefresh-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D88C9F75BDFC1CE7034687208D830D81 /* UITableView+FDTemplateLayoutCell-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F42F1412F20D8BA676203B880AC08EE3 /* UITableView+FDTemplateLayoutCell-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D8B1525CB3DFCBD8E5032680530413D9 /* NSArray+MASShorthandAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = CBAE109E687AA08F5504796C0C8AAA94 /* NSArray+MASShorthandAdditions.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D9F2BA4D713DAC2A85CB4A453240EA3E /* MJRefreshAutoFooter.h in Headers */ = {isa = PBXBuildFile; fileRef = 9690628DA2E17BA5835C5D826268D509 /* MJRefreshAutoFooter.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DA6FBCC4512298773ABFFA8A1F8BD972 /* UIImageView+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 454A5B629D064F61E8CD89588ACADB13 /* UIImageView+WebCache.m */; }; + DA75132AF02110EA8FED838245F245B3 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 223CC88B609D08C4EA1EC854A8D73AD1 /* CoreGraphics.framework */; }; + DB55C38E306ED2B647AA6E49486483B7 /* NSObject+LKDBHelper.m in Sources */ = {isa = PBXBuildFile; fileRef = 311DDA855B68C2C82DA3F585C044E5D0 /* NSObject+LKDBHelper.m */; settings = {COMPILER_FLAGS = "-DOS_OBJECT_USE_OBJC=0"; }; }; + DB596BB8F97C2B0A0CA72695B4010141 /* SocketRocket-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 3C0DB12ED7065982F99681E7208B396E /* SocketRocket-dummy.m */; }; + DBD3B4544D8320D0D83479AEB921D088 /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9C52134DD48D89A347BF80B6D47974CD /* CFNetwork.framework */; }; + DE17E4C2C6EADE5D2D531268B1695405 /* UIView+MJExtension.h in Headers */ = {isa = PBXBuildFile; fileRef = F371B6BB584B1CC6193A5B5E7327AD5A /* UIView+MJExtension.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DE83F763EE2F69844D4359D9E80840F2 /* SDWebImageCoder.m in Sources */ = {isa = PBXBuildFile; fileRef = 7475210B8C97452DB2D28FF46AD4B78D /* SDWebImageCoder.m */; }; + DEB92E2DB086E554AEA1DBFA8A9F00D0 /* IQUIView+Hierarchy.m in Sources */ = {isa = PBXBuildFile; fileRef = D935D6502CF164CFEAC6164421D07051 /* IQUIView+Hierarchy.m */; }; + DFA0B0C7EC02135911CACDAFD38BE715 /* JSONValueTransformer.h in Headers */ = {isa = PBXBuildFile; fileRef = 098D4097B035C28D4D42FD43FBEF8C63 /* JSONValueTransformer.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E008B05370128F8FD8B4B627C8C4D4F4 /* SDWebImageOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = B3128EC48EC5433341A281DE78719B72 /* SDWebImageOperation.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E23258A837180BD5EBE5217D1D69909B /* SDWebImageDownloaderOperation.h in Headers */ = {isa = PBXBuildFile; fileRef = 8D0CC50CC4E4ABC5F7473302F3F1B511 /* SDWebImageDownloaderOperation.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E2E95C8112B691A912057A2DCD2B9297 /* SDImageCacheConfig.m in Sources */ = {isa = PBXBuildFile; fileRef = 6E3BCEC765BAFBF7315B2835E33E8AC4 /* SDImageCacheConfig.m */; }; + E39D9A942BCE728467A42C478816966F /* JSONModel.m in Sources */ = {isa = PBXBuildFile; fileRef = 5F39613535A087B430D652C5A35BE82A /* JSONModel.m */; }; + E3C47E114E924D2F331F9A3F122AEE5C /* JSONModel+networking.h in Headers */ = {isa = PBXBuildFile; fileRef = 229EF78EA685C4B19FF8D820077AB1F8 /* JSONModel+networking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E4AC26FB387427964538FA5FCEA4A8A3 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 223CC88B609D08C4EA1EC854A8D73AD1 /* CoreGraphics.framework */; }; + E504492C8894D7522724712EFA67C7D1 /* SDWebImageCompat.m in Sources */ = {isa = PBXBuildFile; fileRef = 33F7C39FC1E079D25B57C66BE636FC39 /* SDWebImageCompat.m */; }; + E57312010AFB591EE37870F65E651EA6 /* MJRefreshNormalHeader.m in Sources */ = {isa = PBXBuildFile; fileRef = 644412ADC146571600D9B79498A3AF6E /* MJRefreshNormalHeader.m */; }; + E5CD5C797956697DDCC98A3EAC7E99E3 /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = AE919D25345375BA78B8CD922B87C8FC /* AFURLRequestSerialization.m */; }; + E624C54E55BFAE88D8EC8492E2B62619 /* UITableView+FDTemplateLayoutCell-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = C5F6388857FDFC150CCD9AEF58FD9078 /* UITableView+FDTemplateLayoutCell-dummy.m */; }; + E72EDE323AC9F92EC8A00A93AC186093 /* NSArray+MASAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 05E0636001879B23805B939764BB941A /* NSArray+MASAdditions.m */; }; + E802560B425A04296159872675948D29 /* IQKeyboardReturnKeyHandler.m in Sources */ = {isa = PBXBuildFile; fileRef = 70FB502773E45F7563AF74BD45F329B0 /* IQKeyboardReturnKeyHandler.m */; }; + E80DB5D9B2D35085282DF057BB540AFE /* MJRefreshBackFooter.m in Sources */ = {isa = PBXBuildFile; fileRef = D59CC779E29EBC0013D1E71D0571D5F5 /* MJRefreshBackFooter.m */; }; + E82991D928C3CFEDC23555B3F2CB017D /* SDImageCacheConfig.h in Headers */ = {isa = PBXBuildFile; fileRef = 3B60C061E6AF24D5ABF4219ABB4D7F9C /* SDImageCacheConfig.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E8DAB555F27A1AF5B02B19282B609B8E /* NSImage+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = B3746F3DB8A767202DDD4F8D8A9E522E /* NSImage+WebCache.m */; }; + EA23726556D213DB485BD1791C7164CF /* AFNetworkActivityIndicatorManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 0F034245E549B8FD80F5294F722A39F5 /* AFNetworkActivityIndicatorManager.m */; }; + EBA34A3FBF57D5834C2EC4722210066A /* Pods-GIGA-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 4333DE13F7B28D62D7251611E26C7D1F /* Pods-GIGA-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + EBEB72F80DCD10DEB82BF5F856D467FD /* MJRefreshConst.h in Headers */ = {isa = PBXBuildFile; fileRef = 37C4D86D5BC795F8CC7265B8FC971950 /* MJRefreshConst.h */; settings = {ATTRIBUTES = (Public, ); }; }; + ECBA1F4D70AF4600563FD39112D5997B /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */; }; + ECD71FC38CCAFD1ACC2E546FAAEC0D60 /* SocketRocket-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = AE211004837DB758CC532F2DBA59761F /* SocketRocket-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F1199E40BF416FC1ACA2DDCD7B2E23A1 /* UIImage+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = BC724DAEA419916CD03249BD222F8124 /* UIImage+AFNetworking.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F11FAB91014130EE233A3429439D38D7 /* FMDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = E26447099EDFE24E2B1AF730E232EB27 /* FMDatabase.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F26CD9A1DF452688BF3C98BBA9090F92 /* AFURLRequestSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = 9224D1F9357D1822DC11BB7D3C5CA29B /* AFURLRequestSerialization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F2EFDC17C03449A9A15E26464453103F /* NJKWebViewProgress.h in Headers */ = {isa = PBXBuildFile; fileRef = EB5A22B7F55187B0C899BDE644913E34 /* NJKWebViewProgress.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F30950E63F3D8D6C07FFB50C5971116E /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = 2764D65BCE489D3C4CED132E012A1434 /* AFSecurityPolicy.m */; }; + F38B93D66E5151DC14AA52242858DDCB /* FMDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 167E9F1BB5C566ED575F9AFA45711349 /* FMDB.framework */; }; + F3FBCDC1B575D58AD9F78DA4AF687438 /* UIButton+WebCache.h in Headers */ = {isa = PBXBuildFile; fileRef = D6A5BFBE51D80535DEA9FCDD8E232F54 /* UIButton+WebCache.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F4A57F7C1F8184A6DDEABB07FA6D7083 /* NSBundle+MJRefresh.m in Sources */ = {isa = PBXBuildFile; fileRef = 1A77B18130425F1D9F7A7DDDB6553192 /* NSBundle+MJRefresh.m */; }; + F4B3E44D5D2F6508BC1BB35A9FBDEC70 /* View+MASAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 555E43817D41A5303D4F6306F7FA062E /* View+MASAdditions.m */; }; + F53E65E5CA956894846C5A6969536F83 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */; }; + F54879EEAE223E90AC9674197E6B1ADE /* AFImageDownloader.h in Headers */ = {isa = PBXBuildFile; fileRef = 0AB0C00E8C3E7BA94AF01A2DD16F0620 /* AFImageDownloader.h */; settings = {ATTRIBUTES = (Public, ); }; }; + F68EA720B0ED1BF96CEBF07977A1C0A2 /* MJRefreshComponent.m in Sources */ = {isa = PBXBuildFile; fileRef = 359C930B2349FAEDE0BC33F8CBD77171 /* MJRefreshComponent.m */; }; + FA0124E4B3FEA15F037A936E569EBAEF /* UIButton+WebCache.m in Sources */ = {isa = PBXBuildFile; fileRef = A06DE5502BE4BF7357DB2DF5A8BA5207 /* UIButton+WebCache.m */; }; + FA194D9EFAB084FD2FF27BF01F7B30DD /* CoreText.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7B66A6C8F7C747D007AEDA080245D186 /* CoreText.framework */; }; + FB9C6242B11049E2F1062D04565E568D /* UIScrollView+MJExtension.m in Sources */ = {isa = PBXBuildFile; fileRef = 64BCE5A336C9FAB2ED7600867B5FBA97 /* UIScrollView+MJExtension.m */; }; + FD31283E2A43955C5BA6FA9008EE8D7C /* MJRefreshGifHeader.m in Sources */ = {isa = PBXBuildFile; fileRef = 865509F3D52113ED76312034BC65B7C6 /* MJRefreshGifHeader.m */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 0624AA154FDA56AB497466DC03BB55B6 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 5CC70589280C1B49544760FFD838E2A4; + remoteInfo = TTTAttributedLabel; + }; + 07FD3E22A9DD4A1B99981D75716BD3AE /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = E14A62900910444707A5504D25EC98DC; + remoteInfo = MJRefresh; + }; + 10C19AB1817BEF22435DC5055DE4F0F4 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 6B1714E816AE794962516E2ECBB40A5A; + remoteInfo = MBProgressHUD; + }; + 12C08506A8A26019CD1B7D866E2D9AE0 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = E16D87E1F5CFFF8F722CF5A492B046B9; + remoteInfo = Toast; + }; + 14399779F1E76914D37F4F6C523906BB /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = DC3688684BF42A20A8998F31DDA51A49; + remoteInfo = JSONModel; + }; + 23CDBC7F0F0884CFA75FBBEF10D3B03D /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = F4160500DCEA3DA3E93FBA579E88CA0A; + remoteInfo = AFNetworking; + }; + 43E5D6A14DFB2BB82D0E18797207D59C /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 95BEAA384CB15B77BDF7ACD211017BBF; + remoteInfo = "UITableView+FDTemplateLayoutCell"; + }; + 448C316EBC342AEAB86CA07E51B7CCEB /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = BC65E926DB84B0281E512834BE47D80A; + remoteInfo = SDWebImage; + }; + 79CCAC30E08937B11F101E7A789BF6A9 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 37E3F76B9AB64BE59F26C42C0DB02B51; + remoteInfo = SocketRocket; + }; + 8A906A446E3695C9C80C35AF0D8D128A /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 251BAD17812F7EBF6532EACF66F941C3; + remoteInfo = FMDB; + }; + 90FC23568A2780CCB2D594FAE3F3B4B3 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 826EFF975442065A54A0B2D3103EE6A4; + remoteInfo = NJKWebViewProgress; + }; + C250CB5A26266169FD4E1B35C6267674 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = D52144DE9D7255DE912490FF5A806573; + remoteInfo = Masonry; + }; + C3C1D0DAF595497F4E217F601FF28DE8 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 251BAD17812F7EBF6532EACF66F941C3; + remoteInfo = FMDB; + }; + D16DEB882FB3ACDF2B1D59F84EB72924 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = CCA9C33B127D6C859A3F8AFBEFCBABF0; + remoteInfo = LKDBHelper; + }; + D55D2D92CB19AF61F08790B384A513E0 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = D55833EC3DE9EBD9B329CAEB983D5A9D; + remoteInfo = IQKeyboardManager; + }; + F9DD1D0D243D5BA994B993C063F16F85 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = CF1D6BC4AC3FC60A30FB00811CF01999; + remoteInfo = YTKKeyValueStore; + }; + FDFB12CC87933DAABA8E177FE069CD99 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 251BAD17812F7EBF6532EACF66F941C3; + remoteInfo = FMDB; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 0023881B652D74804B040D7DA24C1D05 /* MASViewConstraint.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MASViewConstraint.h; path = Masonry/MASViewConstraint.h; sourceTree = ""; }; + 00F8BF23D01B2525D48EF9EA2FF41BB9 /* IQToolbar.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = IQToolbar.h; path = IQKeyboardManager/IQToolbar/IQToolbar.h; sourceTree = ""; }; + 03E771AC05A23295139B2FB92DE413D1 /* JSONAPI.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = JSONAPI.m; path = JSONModel/JSONModelNetworking/JSONAPI.m; sourceTree = ""; }; + 0437B58A81D211C5C568BBC32D5ED7EF /* AFURLResponseSerialization.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFURLResponseSerialization.h; path = AFNetworking/AFURLResponseSerialization.h; sourceTree = ""; }; + 04AF8FBCCAA5C10FBF5C8D678095B349 /* UIImage+GIF.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImage+GIF.m"; path = "SDWebImage/UIImage+GIF.m"; sourceTree = ""; }; + 053476A95CBB33D3F007559250E2E712 /* UIView+WebCacheOperation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+WebCacheOperation.h"; path = "SDWebImage/UIView+WebCacheOperation.h"; sourceTree = ""; }; + 053BB0597C8AADB4758AD482E0A510B0 /* FMDB.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = FMDB.xcconfig; sourceTree = ""; }; + 05E0636001879B23805B939764BB941A /* NSArray+MASAdditions.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSArray+MASAdditions.m"; path = "Masonry/NSArray+MASAdditions.m"; sourceTree = ""; }; + 0712B6EB2B50F748C0C18FF36D97B3DF /* AFNetworking.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = AFNetworking.xcconfig; sourceTree = ""; }; + 08E127FD35CF12E2DFEAE98245B87676 /* UITableView+FDIndexPathHeightCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UITableView+FDIndexPathHeightCache.m"; path = "Classes/UITableView+FDIndexPathHeightCache.m"; sourceTree = ""; }; + 0934BA64BE003DD5F14A699685132128 /* UITableView+FDTemplateLayoutCell.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "UITableView+FDTemplateLayoutCell.modulemap"; sourceTree = ""; }; + 098D4097B035C28D4D42FD43FBEF8C63 /* JSONValueTransformer.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = JSONValueTransformer.h; path = JSONModel/JSONModelTransformations/JSONValueTransformer.h; sourceTree = ""; }; + 0995F8AABB71D527DE51897FA8F83BA9 /* MJRefreshFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshFooter.h; path = MJRefresh/Base/MJRefreshFooter.h; sourceTree = ""; }; + 0A3B12D0C0FC24CB5EEC1457E32FC6BF /* UIImage+GIF.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImage+GIF.h"; path = "SDWebImage/UIImage+GIF.h"; sourceTree = ""; }; + 0A9C84FF7695F4A1769FBD2619ECC029 /* MJRefresh-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "MJRefresh-prefix.pch"; sourceTree = ""; }; + 0AB0C00E8C3E7BA94AF01A2DD16F0620 /* AFImageDownloader.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFImageDownloader.h; path = "UIKit+AFNetworking/AFImageDownloader.h"; sourceTree = ""; }; + 0ABED0039D2F20276FEA3153C100C8EA /* ImageIO.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = ImageIO.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/ImageIO.framework; sourceTree = DEVELOPER_DIR; }; + 0B7DB276EA29841EF61406CACDDBA7DF /* TTTAttributedLabel-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "TTTAttributedLabel-dummy.m"; sourceTree = ""; }; + 0B8497F4D647973F7EF7F63CA4433C95 /* MASViewAttribute.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MASViewAttribute.h; path = Masonry/MASViewAttribute.h; sourceTree = ""; }; + 0D6854C9307CDCC712B55D7EC927935E /* Masonry.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Masonry.framework; path = Masonry.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 0DE0B076A96500EE0326A01598C25CD9 /* View+MASAdditions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "View+MASAdditions.h"; path = "Masonry/View+MASAdditions.h"; sourceTree = ""; }; + 0DE0E0C75D4EFF8E1F1A6897C860EC33 /* Masonry.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Masonry.xcconfig; sourceTree = ""; }; + 0F034245E549B8FD80F5294F722A39F5 /* AFNetworkActivityIndicatorManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFNetworkActivityIndicatorManager.m; path = "UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m"; sourceTree = ""; }; + 0FF2FC65CD5737B5207D47B6520D5FC7 /* IQTextView.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = IQTextView.m; path = IQKeyboardManager/IQTextView/IQTextView.m; sourceTree = ""; }; + 105F2F5DE7034DDDB46A5FF6C1257C53 /* AFURLResponseSerialization.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFURLResponseSerialization.m; path = AFNetworking/AFURLResponseSerialization.m; sourceTree = ""; }; + 10E8184A26C2F3665BEE0311F178C96E /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 1137254611EEC2056578AEB819AA94C3 /* MJRefreshAutoFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshAutoFooter.m; path = MJRefresh/Base/MJRefreshAutoFooter.m; sourceTree = ""; }; + 125D8E7B25DE48B829EF26B5A344B3D0 /* AFNetworkReachabilityManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFNetworkReachabilityManager.h; path = AFNetworking/AFNetworkReachabilityManager.h; sourceTree = ""; }; + 1268983E6F23E528A8D0D9A8615131B6 /* AFNetworking.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = AFNetworking.modulemap; sourceTree = ""; }; + 12F1549F9D1FEC79B40E50D906C6E8CC /* AFSecurityPolicy.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFSecurityPolicy.h; path = AFNetworking/AFSecurityPolicy.h; sourceTree = ""; }; + 147C7A5F29B419F15BD11AE9B4D6E40F /* NJKWebViewProgress-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "NJKWebViewProgress-dummy.m"; sourceTree = ""; }; + 14A57F7FDCD24207067E3E300876540C /* LKDBUtils.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LKDBUtils.h; path = LKDBHelper/Helper/LKDBUtils.h; sourceTree = ""; }; + 167E9F1BB5C566ED575F9AFA45711349 /* FMDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = FMDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 17979012F15292B8E646C3D69BB45763 /* SocketRocket.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SocketRocket.xcconfig; sourceTree = ""; }; + 1A438A62B6C02EC44F5039151E9F9A71 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 1A77B18130425F1D9F7A7DDDB6553192 /* NSBundle+MJRefresh.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSBundle+MJRefresh.m"; path = "MJRefresh/NSBundle+MJRefresh.m"; sourceTree = ""; }; + 1A7BD38C15C083C8004AF81AE4248CFF /* Masonry-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Masonry-prefix.pch"; sourceTree = ""; }; + 1B2D027604F0FD4DDC858BCB8413D135 /* JSONValueTransformer.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = JSONValueTransformer.m; path = JSONModel/JSONModelTransformations/JSONValueTransformer.m; sourceTree = ""; }; + 1DB7026C750DB559A03CDBE2742DC1B3 /* Pods_GIGA.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_GIGA.framework; path = "Pods-GIGA.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 1E49FA87D6265A153A6A377608BF76CF /* JSONHTTPClient.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = JSONHTTPClient.h; path = JSONModel/JSONModelNetworking/JSONHTTPClient.h; sourceTree = ""; }; + 1E7820BA9423CD0C1D2DAC362014ED4B /* FMDatabaseAdditions.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FMDatabaseAdditions.m; path = src/fmdb/FMDatabaseAdditions.m; sourceTree = ""; }; + 1F3542CD47C057D6C551C30C3B46D2DB /* SDWebImageCoderHelper.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageCoderHelper.h; path = SDWebImage/SDWebImageCoderHelper.h; sourceTree = ""; }; + 2027232FAF2C4FD8C62B41D1443F10A8 /* UIScrollView+MJRefresh.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIScrollView+MJRefresh.m"; path = "MJRefresh/UIScrollView+MJRefresh.m"; sourceTree = ""; }; + 207C7B70CDF9CB324605A2DE508A6A07 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 2127EDE3F7D3FA57134EACCE79E57C4B /* UITableView+FDKeyedHeightCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UITableView+FDKeyedHeightCache.m"; path = "Classes/UITableView+FDKeyedHeightCache.m"; sourceTree = ""; }; + 218B6E61733A5B9138CB4D0815133580 /* Pods-GIGA.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-GIGA.debug.xcconfig"; sourceTree = ""; }; + 218DE19B389EE5088E7040712F0704B3 /* ViewController+MASAdditions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "ViewController+MASAdditions.h"; path = "Masonry/ViewController+MASAdditions.h"; sourceTree = ""; }; + 22262DD61DBB977FA2942AD0D070C595 /* IQKeyboardReturnKeyHandler.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = IQKeyboardReturnKeyHandler.h; path = IQKeyboardManager/IQKeyboardReturnKeyHandler.h; sourceTree = ""; }; + 223CC88B609D08C4EA1EC854A8D73AD1 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/CoreGraphics.framework; sourceTree = DEVELOPER_DIR; }; + 229EF78EA685C4B19FF8D820077AB1F8 /* JSONModel+networking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "JSONModel+networking.h"; path = "JSONModel/JSONModelNetworking/JSONModel+networking.h"; sourceTree = ""; }; + 22C882FD98CA446EFA39A29BFF94A28B /* UITableView+FDKeyedHeightCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UITableView+FDKeyedHeightCache.h"; path = "Classes/UITableView+FDKeyedHeightCache.h"; sourceTree = ""; }; + 2312E64F77FC628042C95F6F42AC9204 /* MJRefresh.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = MJRefresh.framework; path = MJRefresh.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 2368EA7094707071EF9EB1847081B539 /* UIRefreshControl+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIRefreshControl+AFNetworking.m"; path = "UIKit+AFNetworking/UIRefreshControl+AFNetworking.m"; sourceTree = ""; }; + 26C0262CE054672814BFFD41BA3DE3AC /* MASUtilities.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MASUtilities.h; path = Masonry/MASUtilities.h; sourceTree = ""; }; + 26C29828B683FB67FD6E1E218F63F152 /* JSONModel-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "JSONModel-dummy.m"; sourceTree = ""; }; + 270737E79A641CBC04762BA9F997CE18 /* JSONModelClassProperty.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = JSONModelClassProperty.m; path = JSONModel/JSONModel/JSONModelClassProperty.m; sourceTree = ""; }; + 272CBD0843CB816395E98BA936E24B87 /* MBProgressHUD.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = MBProgressHUD.m; sourceTree = ""; }; + 2764D65BCE489D3C4CED132E012A1434 /* AFSecurityPolicy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFSecurityPolicy.m; path = AFNetworking/AFSecurityPolicy.m; sourceTree = ""; }; + 295F052A6A46300AE255CCA9D34FD7AF /* UIView+Toast.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+Toast.m"; path = "Toast/UIView+Toast.m"; sourceTree = ""; }; + 29BE32503E41FD5479AAF41A8A089CFD /* Masonry.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Masonry.modulemap; sourceTree = ""; }; + 29C6CB0E4CB91AB0517A62CA7D3D4C95 /* SDWebImage-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SDWebImage-umbrella.h"; sourceTree = ""; }; + 2AE6A655C2E452806506AB901CB710BC /* MJRefresh-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "MJRefresh-umbrella.h"; sourceTree = ""; }; + 2B1A51FCBEFB476684647C57EDFB6E27 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 2BB9D5AF91DFC97D964A3278CD65C526 /* YTKKeyValueStore-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "YTKKeyValueStore-dummy.m"; sourceTree = ""; }; + 2C5FBC24791EAE0728C65D6F9B9912B2 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/QuartzCore.framework; sourceTree = DEVELOPER_DIR; }; + 2CE1C92FCE95492CB6C334FDB10A3525 /* YTKKeyValueStore.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = YTKKeyValueStore.m; path = YTKKeyValueStore/YTKKeyValueStore.m; sourceTree = ""; }; + 2D47457D3CE1E0737C687DB3E4E896A0 /* IQNSArray+Sort.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "IQNSArray+Sort.m"; path = "IQKeyboardManager/Categories/IQNSArray+Sort.m"; sourceTree = ""; }; + 2DCB8E007F3B05111DC4769E7EA077D9 /* IQUIScrollView+Additions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "IQUIScrollView+Additions.h"; path = "IQKeyboardManager/Categories/IQUIScrollView+Additions.h"; sourceTree = ""; }; + 2F239ADCBC9530CFB69A3DBA4606CB39 /* MASCompositeConstraint.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MASCompositeConstraint.h; path = Masonry/MASCompositeConstraint.h; sourceTree = ""; }; + 2F9966C0F9F759260F26024DC5F6FCB1 /* UITableView+FDTemplateLayoutCellDebug.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UITableView+FDTemplateLayoutCellDebug.m"; path = "Classes/UITableView+FDTemplateLayoutCellDebug.m"; sourceTree = ""; }; + 30C9D2B8F917B8405C9B54173E51741E /* MASConstraint.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MASConstraint.m; path = Masonry/MASConstraint.m; sourceTree = ""; }; + 30D477DB1A599E055F88B89589F278A7 /* YTKKeyValueStore.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = YTKKeyValueStore.modulemap; sourceTree = ""; }; + 311DDA855B68C2C82DA3F585C044E5D0 /* NSObject+LKDBHelper.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSObject+LKDBHelper.m"; path = "LKDBHelper/Helper/NSObject+LKDBHelper.m"; sourceTree = ""; }; + 336B4CC378FCC45D7E43E8E330E67E1B /* IQBarButtonItem.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = IQBarButtonItem.m; path = IQKeyboardManager/IQToolbar/IQBarButtonItem.m; sourceTree = ""; }; + 339D6D016535F8109AC998611978456D /* MJRefreshAutoNormalFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshAutoNormalFooter.m; path = MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.m; sourceTree = ""; }; + 33F7C39FC1E079D25B57C66BE636FC39 /* SDWebImageCompat.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageCompat.m; path = SDWebImage/SDWebImageCompat.m; sourceTree = ""; }; + 342C32AD5BF61779D426BDA9F82DEDE5 /* JSONModel.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = JSONModel.framework; path = JSONModel.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 350E7464A1D787085E3C8AB20B8D3699 /* SDWebImageFrame.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageFrame.m; path = SDWebImage/SDWebImageFrame.m; sourceTree = ""; }; + 35877F4071E71D27BA630FEDB0FE43BA /* MASConstraint.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MASConstraint.h; path = Masonry/MASConstraint.h; sourceTree = ""; }; + 359C930B2349FAEDE0BC33F8CBD77171 /* MJRefreshComponent.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshComponent.m; path = MJRefresh/Base/MJRefreshComponent.m; sourceTree = ""; }; + 362634D02C8734DCDBB1B3FA29AF2E5A /* IQKeyboardManager-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "IQKeyboardManager-umbrella.h"; sourceTree = ""; }; + 36D82CC8DDDDD9C3AA54A9368D31C3B7 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 37C4D86D5BC795F8CC7265B8FC971950 /* MJRefreshConst.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshConst.h; path = MJRefresh/MJRefreshConst.h; sourceTree = ""; }; + 38D4A17D513EE0A59F71025AE92894BB /* libjcore-ios-1.2.2.a */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = archive.ar; path = "libjcore-ios-1.2.2.a"; sourceTree = ""; }; + 39CB9D0EBDE904E619E327F0B49A9062 /* MJRefresh.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = MJRefresh.xcconfig; sourceTree = ""; }; + 3A0319B9CF8094FC585EF6B82C4B2DA8 /* UIView+MJExtension.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+MJExtension.m"; path = "MJRefresh/UIView+MJExtension.m"; sourceTree = ""; }; + 3B60C061E6AF24D5ABF4219ABB4D7F9C /* SDImageCacheConfig.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageCacheConfig.h; path = SDWebImage/SDImageCacheConfig.h; sourceTree = ""; }; + 3C0DB12ED7065982F99681E7208B396E /* SocketRocket-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SocketRocket-dummy.m"; sourceTree = ""; }; + 3C2E772FF38560DBD9204DA3173B1368 /* MJRefreshBackGifFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshBackGifFooter.h; path = MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.h; sourceTree = ""; }; + 3C3A79FA17ABD84F81F1074C87C73E34 /* UIScrollView+MJRefresh.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIScrollView+MJRefresh.h"; path = "MJRefresh/UIScrollView+MJRefresh.h"; sourceTree = ""; }; + 4015BC1E8D9C87DAAE2DA773CDA1439F /* NSData+ImageContentType.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSData+ImageContentType.m"; path = "SDWebImage/NSData+ImageContentType.m"; sourceTree = ""; }; + 402AA4AB24F2AD705593DD3FB991387B /* MASViewConstraint.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MASViewConstraint.m; path = Masonry/MASViewConstraint.m; sourceTree = ""; }; + 417E2E632AF904B3B32155C62F0B19DC /* MASConstraint+Private.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "MASConstraint+Private.h"; path = "Masonry/MASConstraint+Private.h"; sourceTree = ""; }; + 422402DD22D498220638075EF90B07A3 /* AFNetworking-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "AFNetworking-dummy.m"; sourceTree = ""; }; + 43189891007DC8B214462EE40E661B70 /* JSONAPI.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = JSONAPI.h; path = JSONModel/JSONModelNetworking/JSONAPI.h; sourceTree = ""; }; + 4333DE13F7B28D62D7251611E26C7D1F /* Pods-GIGA-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-GIGA-umbrella.h"; sourceTree = ""; }; + 43BCA2F852A7750CEC56CEC17939F15A /* FMDB-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "FMDB-prefix.pch"; sourceTree = ""; }; + 43E2B344D60B305F452C5EFEB124C107 /* MJRefreshBackNormalFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshBackNormalFooter.m; path = MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.m; sourceTree = ""; }; + 453E45CF34A191D43B74674E7A90FBD7 /* MJRefresh.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = MJRefresh.modulemap; sourceTree = ""; }; + 454A5B629D064F61E8CD89588ACADB13 /* UIImageView+WebCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImageView+WebCache.m"; path = "SDWebImage/UIImageView+WebCache.m"; sourceTree = ""; }; + 46C1C2B2A4BA6017298CF244B5B46838 /* FMDB.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FMDB.h; path = src/fmdb/FMDB.h; sourceTree = ""; }; + 46D5F33AFF37B1C04CBDE88EF04B11A3 /* MBProgressHUD.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = MBProgressHUD.xcconfig; sourceTree = ""; }; + 4738089B8361F3D3AB1BCED704498464 /* MBProgressHUD.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = MBProgressHUD.framework; path = MBProgressHUD.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 47FC8BC593D3C4A9BCFAAB1AD76AC13D /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/Security.framework; sourceTree = DEVELOPER_DIR; }; + 4828CBF98C8FA0FD91EC3A44854FF58F /* NJKWebViewProgress-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "NJKWebViewProgress-prefix.pch"; sourceTree = ""; }; + 491A04582FFB79FD874AFB04764A6F5C /* FMDatabasePool.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FMDatabasePool.m; path = src/fmdb/FMDatabasePool.m; sourceTree = ""; }; + 491FD42A9D3970BD3ACF252F98B968EB /* Masonry-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Masonry-dummy.m"; sourceTree = ""; }; + 49FC022BC0DDF2BFCA610030FC39F8BF /* UIView+WebCacheOperation.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+WebCacheOperation.m"; path = "SDWebImage/UIView+WebCacheOperation.m"; sourceTree = ""; }; + 4A26F8EC0D0C0834C08E37EF1C0D560D /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 4A2AF264E571B9997B0965D66283EAA6 /* SDWebImageManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageManager.h; path = SDWebImage/SDWebImageManager.h; sourceTree = ""; }; + 4A9D286E65BE10630D2D01808B376E3F /* JSONModel-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "JSONModel-umbrella.h"; sourceTree = ""; }; + 4AFDFD2D9A90BF4BB9DD861020532888 /* NJKWebViewProgress.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = NJKWebViewProgress.framework; path = NJKWebViewProgress.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 4B3F07A870FB3A3BFB758AD0E1BE2C36 /* NJKWebViewProgressView.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = NJKWebViewProgressView.m; path = NJKWebViewProgress/NJKWebViewProgressView.m; sourceTree = ""; }; + 4B4ACAA5FE6E4D692115FD521BCB1287 /* IQUITextFieldView+Additions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "IQUITextFieldView+Additions.h"; path = "IQKeyboardManager/Categories/IQUITextFieldView+Additions.h"; sourceTree = ""; }; + 4B63AC7AEEF5E567F175F4F93CD3E083 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 4BB8C4AE22CA2904E7813EFEAFE8A067 /* Pods-GIGA.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-GIGA.modulemap"; sourceTree = ""; }; + 4BFD3AE7B418D1AB696243F283ECC7F3 /* SDWebImageCoder.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageCoder.h; path = SDWebImage/SDWebImageCoder.h; sourceTree = ""; }; + 4CE36714FF24257CBB6D4A43CE11D871 /* TTTAttributedLabel.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = TTTAttributedLabel.m; path = TTTAttributedLabel/TTTAttributedLabel.m; sourceTree = ""; }; + 4D7894D466D10E51479750206920F843 /* MJRefreshFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshFooter.m; path = MJRefresh/Base/MJRefreshFooter.m; sourceTree = ""; }; + 4D870611B8793D878F9166BF6ACFCAFB /* LKDBHelper.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LKDBHelper.m; path = LKDBHelper/Helper/LKDBHelper.m; sourceTree = ""; }; + 4FA220EAF4B2366FE3383A5AF8AD3D27 /* UIImage+ForceDecode.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImage+ForceDecode.h"; path = "SDWebImage/UIImage+ForceDecode.h"; sourceTree = ""; }; + 4FD6E6CFFA09827B260BD7CEF9FB0968 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 50E0055FB2FCA5A95F12691436BC4D68 /* SDWebImage-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SDWebImage-prefix.pch"; sourceTree = ""; }; + 5464A11C33E8A793B5FAA8C62E68999D /* YTKKeyValueStore-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "YTKKeyValueStore-prefix.pch"; sourceTree = ""; }; + 54BA54731B31CD6D22D2D59BBE0D5608 /* SDWebImageCoderHelper.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageCoderHelper.m; path = SDWebImage/SDWebImageCoderHelper.m; sourceTree = ""; }; + 54F3536A4C88BAB5768A5110E968D42E /* AFHTTPSessionManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFHTTPSessionManager.m; path = AFNetworking/AFHTTPSessionManager.m; sourceTree = ""; }; + 555E43817D41A5303D4F6306F7FA062E /* View+MASAdditions.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "View+MASAdditions.m"; path = "Masonry/View+MASAdditions.m"; sourceTree = ""; }; + 5569AA726D3D85E6DF8895BAAE8DEBDF /* UIImageView+HighlightedWebCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImageView+HighlightedWebCache.h"; path = "SDWebImage/UIImageView+HighlightedWebCache.h"; sourceTree = ""; }; + 572894CF08231457B24C1071533852F6 /* TTTAttributedLabel.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = TTTAttributedLabel.xcconfig; sourceTree = ""; }; + 581983071B50ED00E03BBC3807ED5DEB /* IQKeyboardManager.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = IQKeyboardManager.framework; path = IQKeyboardManager.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 598BCA3C824B45B4D482801D765BB44E /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 598F5B2A218C7D65218EE2E74A1FAB90 /* MJRefreshBackFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshBackFooter.h; path = MJRefresh/Base/MJRefreshBackFooter.h; sourceTree = ""; }; + 5A802226FA114075D3D6409ACCFB1EEA /* UIImageView+WebCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImageView+WebCache.h"; path = "SDWebImage/UIImageView+WebCache.h"; sourceTree = ""; }; + 5AF74F6EDDDBDE1594378798EDC8F75B /* IQTitleBarButtonItem.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = IQTitleBarButtonItem.h; path = IQKeyboardManager/IQToolbar/IQTitleBarButtonItem.h; sourceTree = ""; }; + 5BC59BC77E65287BF00DC491E679E48C /* IQToolbar.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = IQToolbar.m; path = IQKeyboardManager/IQToolbar/IQToolbar.m; sourceTree = ""; }; + 5C9D2325DCA16A38D58B21BD7DB5CF28 /* TTTAttributedLabel.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = TTTAttributedLabel.modulemap; sourceTree = ""; }; + 5CF1B2D752E061B673D94FCB8D0E7610 /* MJRefreshAutoStateFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshAutoStateFooter.h; path = MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.h; sourceTree = ""; }; + 5E99B96339C8127EC7FC7C8FFD3C7553 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 5F39613535A087B430D652C5A35BE82A /* JSONModel.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = JSONModel.m; path = JSONModel/JSONModel/JSONModel.m; sourceTree = ""; }; + 5F98DCFCF300EBC97C2A16DCF1294D7F /* LKDBHelper.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = LKDBHelper.h; path = LKDBHelper/Helper/LKDBHelper.h; sourceTree = ""; }; + 5FA15CE76838746D55FF0B6B9296F3F7 /* LKDBHelper-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "LKDBHelper-prefix.pch"; sourceTree = ""; }; + 60DE6EFB52862BBD769E650DE1A53D87 /* FMResultSet.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FMResultSet.h; path = src/fmdb/FMResultSet.h; sourceTree = ""; }; + 6144F56D8D5366616DE12FF84D28B206 /* MBProgressHUD.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = MBProgressHUD.modulemap; sourceTree = ""; }; + 623CEFA44508E2233D6C8BDDC1A723AB /* UITableView+FDIndexPathHeightCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UITableView+FDIndexPathHeightCache.h"; path = "Classes/UITableView+FDIndexPathHeightCache.h"; sourceTree = ""; }; + 644412ADC146571600D9B79498A3AF6E /* MJRefreshNormalHeader.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshNormalHeader.m; path = MJRefresh/Custom/Header/MJRefreshNormalHeader.m; sourceTree = ""; }; + 64BCE5A336C9FAB2ED7600867B5FBA97 /* UIScrollView+MJExtension.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIScrollView+MJExtension.m"; path = "MJRefresh/UIScrollView+MJExtension.m"; sourceTree = ""; }; + 65DC0A6004D8CA989364A1123D836695 /* IQKeyboardManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = IQKeyboardManager.m; path = IQKeyboardManager/IQKeyboardManager.m; sourceTree = ""; }; + 6631EE01B7EC6B5EF820B3874307CCE0 /* SDAnimatedImageRep.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDAnimatedImageRep.h; path = SDWebImage/SDAnimatedImageRep.h; sourceTree = ""; }; + 671B1C68838C43D897AF46AADD606C4A /* SDWebImageDownloaderOperation.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageDownloaderOperation.m; path = SDWebImage/SDWebImageDownloaderOperation.m; sourceTree = ""; }; + 673F2354B6D1C0F8E9955046A21D6A4B /* MASCompositeConstraint.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MASCompositeConstraint.m; path = Masonry/MASCompositeConstraint.m; sourceTree = ""; }; + 67B406F183DB1F705B966496FF984505 /* UIView+WebCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+WebCache.h"; path = "SDWebImage/UIView+WebCache.h"; sourceTree = ""; }; + 687C5821B77D4D232E15C3BD22C69C47 /* IQKeyboardManager.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = IQKeyboardManager.xcconfig; sourceTree = ""; }; + 68C17CA9F7C67D59F90F34E65B93D62E /* NJKWebViewProgress-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "NJKWebViewProgress-umbrella.h"; sourceTree = ""; }; + 6930C47F6DA9FF53FCC809972D1C2267 /* TTTAttributedLabel-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "TTTAttributedLabel-umbrella.h"; sourceTree = ""; }; + 69C00A3ED643BFA7CBFB31DC4CB6E601 /* FMDatabase.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FMDatabase.m; path = src/fmdb/FMDatabase.m; sourceTree = ""; }; + 6AB8391ABC38E6024FB65A20D3351A17 /* View+MASShorthandAdditions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "View+MASShorthandAdditions.h"; path = "Masonry/View+MASShorthandAdditions.h"; sourceTree = ""; }; + 6AD72E84C0BAA5647385371F3B370E7D /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImageView+AFNetworking.h"; path = "UIKit+AFNetworking/UIImageView+AFNetworking.h"; sourceTree = ""; }; + 6C18F3E40A6F8667E93BF7E113A19F41 /* MBProgressHUD-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "MBProgressHUD-dummy.m"; sourceTree = ""; }; + 6CE816757FAB87E4B239A9085210DA0C /* libjpush-ios-3.1.0.a */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = archive.ar; path = "libjpush-ios-3.1.0.a"; sourceTree = ""; }; + 6E3BCEC765BAFBF7315B2835E33E8AC4 /* SDImageCacheConfig.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageCacheConfig.m; path = SDWebImage/SDImageCacheConfig.m; sourceTree = ""; }; + 6F0DCAD0FC2007DC95B13AE9D58DB89A /* MJRefreshAutoGifFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshAutoGifFooter.h; path = MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.h; sourceTree = ""; }; + 6FD513AB29E9316802D99A9C3C9BE9F1 /* IQKeyboardManagerConstantsInternal.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = IQKeyboardManagerConstantsInternal.h; path = IQKeyboardManager/Constants/IQKeyboardManagerConstantsInternal.h; sourceTree = ""; }; + 6FD79569D1481B1CCEBC524AE5E2B8C0 /* UIKit+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIKit+AFNetworking.h"; path = "UIKit+AFNetworking/UIKit+AFNetworking.h"; sourceTree = ""; }; + 70FB502773E45F7563AF74BD45F329B0 /* IQKeyboardReturnKeyHandler.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = IQKeyboardReturnKeyHandler.m; path = IQKeyboardManager/IQKeyboardReturnKeyHandler.m; sourceTree = ""; }; + 7105E6B5675EAB9B1DB66075A38FC383 /* MJRefresh-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "MJRefresh-dummy.m"; sourceTree = ""; }; + 71BF153300C08FBD61FC51383839A880 /* UITableView+FDTemplateLayoutCell-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "UITableView+FDTemplateLayoutCell-prefix.pch"; sourceTree = ""; }; + 723FBBA74F07E67C701AE828B5405E83 /* UIRefreshControl+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIRefreshControl+AFNetworking.h"; path = "UIKit+AFNetworking/UIRefreshControl+AFNetworking.h"; sourceTree = ""; }; + 7297AD18E47185F3F70FA09B01B9E511 /* LKDBHelper.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = LKDBHelper.xcconfig; sourceTree = ""; }; + 72E288068C58BB673219CEFB1686BC93 /* NSArray+MASAdditions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSArray+MASAdditions.h"; path = "Masonry/NSArray+MASAdditions.h"; sourceTree = ""; }; + 72E7FF6F0D74FA6229F49C74AD38E9D2 /* MJRefreshBackNormalFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshBackNormalFooter.h; path = MJRefresh/Custom/Footer/Back/MJRefreshBackNormalFooter.h; sourceTree = ""; }; + 732E1114AA44818AFA36C115D6C2E3B3 /* LKDBHelper-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "LKDBHelper-umbrella.h"; sourceTree = ""; }; + 73EB4D54E40F7146E8F50D99256E3AB6 /* YTKKeyValueStore.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = YTKKeyValueStore.h; path = YTKKeyValueStore/YTKKeyValueStore.h; sourceTree = ""; }; + 7475210B8C97452DB2D28FF46AD4B78D /* SDWebImageCoder.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageCoder.m; path = SDWebImage/SDWebImageCoder.m; sourceTree = ""; }; + 7567613ABCFDCEBA938593A0036C32A9 /* UIView+Toast.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+Toast.h"; path = "Toast/UIView+Toast.h"; sourceTree = ""; }; + 756EBE270AB520A42983575D8062C88C /* LKDB+Mapping.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "LKDB+Mapping.h"; path = "LKDBHelper/Helper/LKDB+Mapping.h"; sourceTree = ""; }; + 758B3F6E587B47427A1ADFF5C9973B84 /* NJKWebViewProgress.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = NJKWebViewProgress.xcconfig; sourceTree = ""; }; + 76E253E1BAB6E3A4164B42F93C3B0EE8 /* MASLayoutConstraint.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MASLayoutConstraint.m; path = Masonry/MASLayoutConstraint.m; sourceTree = ""; }; + 7714D1833FFBB408B18F2747E65E5790 /* SDWebImageCodersManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageCodersManager.m; path = SDWebImage/SDWebImageCodersManager.m; sourceTree = ""; }; + 771FAC488702BC45D9B3E1C95287F985 /* SDAnimatedImageRep.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDAnimatedImageRep.m; path = SDWebImage/SDAnimatedImageRep.m; sourceTree = ""; }; + 77F995714B12945BE98FB29DB7AABBA0 /* SDImageCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDImageCache.m; path = SDWebImage/SDImageCache.m; sourceTree = ""; }; + 78B556FE17B6F40F4C14A82F0936900C /* LKDB+Mapping.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "LKDB+Mapping.m"; path = "LKDBHelper/Helper/LKDB+Mapping.m"; sourceTree = ""; }; + 7A1FB3C2A543ACC9B55752A4F4B00514 /* SDWebImage.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = SDWebImage.modulemap; sourceTree = ""; }; + 7A2DE5C636CB7384C70AE55DEBC248F7 /* SDWebImageFrame.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageFrame.h; path = SDWebImage/SDWebImageFrame.h; sourceTree = ""; }; + 7B66A6C8F7C747D007AEDA080245D186 /* CoreText.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreText.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/CoreText.framework; sourceTree = DEVELOPER_DIR; }; + 7C92D2200160EED2E09E78F7DC6CAE4A /* MBProgressHUD-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "MBProgressHUD-umbrella.h"; sourceTree = ""; }; + 7EC0F45B5A1A9049F0BA580A2E665024 /* LKDBHelper-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "LKDBHelper-dummy.m"; sourceTree = ""; }; + 7FD3A5585C7A6F8C8EBD39C59F4BCF02 /* UIImage+MultiFormat.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImage+MultiFormat.h"; path = "SDWebImage/UIImage+MultiFormat.h"; sourceTree = ""; }; + 80EBC7AC78ACE04DDC3E429CC36690EB /* SRWebSocket.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SRWebSocket.h; path = SocketRocket/SRWebSocket.h; sourceTree = ""; }; + 8126B93DD8D474B90337F38D978130C5 /* AFNetworking.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = AFNetworking.framework; path = AFNetworking.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8226479816A8DD0C45BACA4F04014C2C /* FMDB.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = FMDB.modulemap; sourceTree = ""; }; + 82AD1D80CEB504366F098535F8C51A1C /* MJRefreshStateHeader.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshStateHeader.m; path = MJRefresh/Custom/Header/MJRefreshStateHeader.m; sourceTree = ""; }; + 8394F96FDD5517B382EFAC03271A2F76 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 84190D645A029D929576CE3874A30E53 /* JSONModelError.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = JSONModelError.h; path = JSONModel/JSONModel/JSONModelError.h; sourceTree = ""; }; + 854A1DB41CF7A374ADAE2118B47984FC /* SocketRocket.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = SocketRocket.modulemap; sourceTree = ""; }; + 865509F3D52113ED76312034BC65B7C6 /* MJRefreshGifHeader.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshGifHeader.m; path = MJRefresh/Custom/Header/MJRefreshGifHeader.m; sourceTree = ""; }; + 86B4DD8A5BE1003157681F47B9A06D90 /* UIImageView+HighlightedWebCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImageView+HighlightedWebCache.m"; path = "SDWebImage/UIImageView+HighlightedWebCache.m"; sourceTree = ""; }; + 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 87D34EBA9583ABA27F69D9C80E8042A8 /* IQUIView+IQKeyboardToolbar.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "IQUIView+IQKeyboardToolbar.m"; path = "IQKeyboardManager/IQToolbar/IQUIView+IQKeyboardToolbar.m"; sourceTree = ""; }; + 886A7A948A578AF0481B05CD6E2FAE30 /* MJRefreshAutoGifFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshAutoGifFooter.m; path = MJRefresh/Custom/Footer/Auto/MJRefreshAutoGifFooter.m; sourceTree = ""; }; + 8BBB7F3A03E7F2608FE52B0194635075 /* Pods-GIGA-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-GIGA-acknowledgements.markdown"; sourceTree = ""; }; + 8C9BAAF1EC72C985C348BCF60EC4D10A /* AFImageDownloader.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFImageDownloader.m; path = "UIKit+AFNetworking/AFImageDownloader.m"; sourceTree = ""; }; + 8CB53A6BCAB7A1F76E7F79652415A592 /* Masonry-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Masonry-umbrella.h"; sourceTree = ""; }; + 8CDF9E3C2D2416AC7550ED950AB0CC88 /* SDImageCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDImageCache.h; path = SDWebImage/SDImageCache.h; sourceTree = ""; }; + 8CF4ACF01E4CEA3CAE293EF3F4CFB20D /* IQNSArray+Sort.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "IQNSArray+Sort.h"; path = "IQKeyboardManager/Categories/IQNSArray+Sort.h"; sourceTree = ""; }; + 8D0CC50CC4E4ABC5F7473302F3F1B511 /* SDWebImageDownloaderOperation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageDownloaderOperation.h; path = SDWebImage/SDWebImageDownloaderOperation.h; sourceTree = ""; }; + 8D854FE9416C9CB1B7597F28FE1AF9F1 /* JSONModel-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "JSONModel-prefix.pch"; sourceTree = ""; }; + 8E5DA37AC55ADD979E448DB4CCE99D62 /* FMDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = FMDB.framework; path = FMDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8FFE95948B8B44700795DACEC0372ED5 /* UITableView+FDTemplateLayoutCell.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "UITableView+FDTemplateLayoutCell.xcconfig"; sourceTree = ""; }; + 90670E1F67061B599C126301C1A3C2D0 /* UIButton+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIButton+AFNetworking.h"; path = "UIKit+AFNetworking/UIButton+AFNetworking.h"; sourceTree = ""; }; + 918438D2584B201AE3B75ECE63C18CD5 /* FMResultSet.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FMResultSet.m; path = src/fmdb/FMResultSet.m; sourceTree = ""; }; + 9224D1F9357D1822DC11BB7D3C5CA29B /* AFURLRequestSerialization.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFURLRequestSerialization.h; path = AFNetworking/AFURLRequestSerialization.h; sourceTree = ""; }; + 9271B8514D90DCA03D6343D0CDCE050D /* MJRefreshHeader.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshHeader.m; path = MJRefresh/Base/MJRefreshHeader.m; sourceTree = ""; }; + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 9404C50D3CA53F5CBA8FB043A06BFAD6 /* MASConstraintMaker.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MASConstraintMaker.m; path = Masonry/MASConstraintMaker.m; sourceTree = ""; }; + 94752DBCE44CA942E27A896C7CB73B8D /* FMDatabaseAdditions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FMDatabaseAdditions.h; path = src/fmdb/FMDatabaseAdditions.h; sourceTree = ""; }; + 94FEA07F421E380A35B094F7568EAF10 /* NSObject+LKModel.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSObject+LKModel.m"; path = "LKDBHelper/Helper/NSObject+LKModel.m"; sourceTree = ""; }; + 9508DBBE609A983ECCD13E2627C7678E /* JSONModel.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = JSONModel.xcconfig; sourceTree = ""; }; + 951A926C2E402064AFF54E885DEE23D1 /* IQKeyboardManager-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "IQKeyboardManager-dummy.m"; sourceTree = ""; }; + 954FBC78E632E1BCD88EEB65027EAEDE /* NJKWebViewProgressView.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = NJKWebViewProgressView.h; path = NJKWebViewProgress/NJKWebViewProgressView.h; sourceTree = ""; }; + 9574A12E8279712E0544674068BEC2E1 /* Pods-GIGA.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-GIGA.release.xcconfig"; sourceTree = ""; }; + 957C4EAC3550D522CFC086D33020AF15 /* SDWebImageImageIOCoder.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageImageIOCoder.h; path = SDWebImage/SDWebImageImageIOCoder.h; sourceTree = ""; }; + 95A1ADBB90DEADD3CC0BB6D927F30DBA /* FMDatabaseQueue.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FMDatabaseQueue.h; path = src/fmdb/FMDatabaseQueue.h; sourceTree = ""; }; + 95E1101C679649DD67CF310BC7C41D40 /* UIButton+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIButton+AFNetworking.m"; path = "UIKit+AFNetworking/UIButton+AFNetworking.m"; sourceTree = ""; }; + 95F6A7B21DB909CA345A47903CB4D39A /* MJRefreshAutoStateFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshAutoStateFooter.m; path = MJRefresh/Custom/Footer/Auto/MJRefreshAutoStateFooter.m; sourceTree = ""; }; + 961B9982B287A938D23CE983804F2FC5 /* LKDBHelper.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = LKDBHelper.framework; path = LKDBHelper.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 967FC3D6EE75AAC4E5853A52FC40FBD1 /* JSONModel+networking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "JSONModel+networking.m"; path = "JSONModel/JSONModelNetworking/JSONModel+networking.m"; sourceTree = ""; }; + 9690628DA2E17BA5835C5D826268D509 /* MJRefreshAutoFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshAutoFooter.h; path = MJRefresh/Base/MJRefreshAutoFooter.h; sourceTree = ""; }; + 997A2F2BD5D2ACC81541F8F909D4E847 /* SDWebImageCodersManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageCodersManager.h; path = SDWebImage/SDWebImageCodersManager.h; sourceTree = ""; }; + 99E94B95014F639BCEFE5DE77CF86A13 /* JSONKeyMapper.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = JSONKeyMapper.m; path = JSONModel/JSONModelTransformations/JSONKeyMapper.m; sourceTree = ""; }; + 9A99A07094C4466F723559D841338C20 /* NJKWebViewProgress.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = NJKWebViewProgress.modulemap; sourceTree = ""; }; + 9B08C8E485946B27165B1EE380D12B99 /* Pods-GIGA-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-GIGA-frameworks.sh"; sourceTree = ""; }; + 9B608913B805E97D3B45F563A37ABCEB /* Toast-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Toast-umbrella.h"; sourceTree = ""; }; + 9B8D6BCD909A41774E16030943339AEB /* NSLayoutConstraint+MASDebugAdditions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSLayoutConstraint+MASDebugAdditions.h"; path = "Masonry/NSLayoutConstraint+MASDebugAdditions.h"; sourceTree = ""; }; + 9BDE845BAEED6040E590CA9903B14998 /* SDWebImageGIFCoder.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageGIFCoder.m; path = SDWebImage/SDWebImageGIFCoder.m; sourceTree = ""; }; + 9C52134DD48D89A347BF80B6D47974CD /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/CFNetwork.framework; sourceTree = DEVELOPER_DIR; }; + 9CB6460D14EA9B327CE96B0450FA717B /* FMDatabaseQueue.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = FMDatabaseQueue.m; path = src/fmdb/FMDatabaseQueue.m; sourceTree = ""; }; + 9D0303615C02A9FC06E4284A85443DC1 /* ViewController+MASAdditions.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "ViewController+MASAdditions.m"; path = "Masonry/ViewController+MASAdditions.m"; sourceTree = ""; }; + 9E43D4748ACBDE3E7E8E94CCE6225EFE /* SocketRocket.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SocketRocket.framework; path = SocketRocket.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 9E72EDED93B07A3890590F87235248C0 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 9F3FD02A35657C32B7608DD9E484CD49 /* SDWebImagePrefetcher.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImagePrefetcher.m; path = SDWebImage/SDWebImagePrefetcher.m; sourceTree = ""; }; + A03F70F63980CD170CD5750B6B5B2168 /* MJRefreshBackGifFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshBackGifFooter.m; path = MJRefresh/Custom/Footer/Back/MJRefreshBackGifFooter.m; sourceTree = ""; }; + A06DE5502BE4BF7357DB2DF5A8BA5207 /* UIButton+WebCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIButton+WebCache.m"; path = "SDWebImage/UIButton+WebCache.m"; sourceTree = ""; }; + A1984BDF5C4B9F316463CFAE01F131B6 /* NSImage+WebCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSImage+WebCache.h"; path = "SDWebImage/NSImage+WebCache.h"; sourceTree = ""; }; + A57F7F0A6AB5550D6C39E86241A2C3B4 /* TTTAttributedLabel.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = TTTAttributedLabel.framework; path = TTTAttributedLabel.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + A7319007CA14024A0376E223A1A702CB /* Toast.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Toast.framework; path = Toast.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + A77BAB4386BD7374C1D019FB835C1F77 /* AFNetworking-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "AFNetworking-prefix.pch"; sourceTree = ""; }; + A7D9C6AE37D287719040FA3D994C8059 /* SDWebImageImageIOCoder.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageImageIOCoder.m; path = SDWebImage/SDWebImageImageIOCoder.m; sourceTree = ""; }; + A81B52350911B789957965FA41897580 /* LKDBUtils.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = LKDBUtils.m; path = LKDBHelper/Helper/LKDBUtils.m; sourceTree = ""; }; + A9BD5EC9B66096A214F0369AC4DB24E4 /* AFAutoPurgingImageCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFAutoPurgingImageCache.m; path = "UIKit+AFNetworking/AFAutoPurgingImageCache.m"; sourceTree = ""; }; + AA70955B3AF65BF0DC77A605CF3D7DED /* AFHTTPSessionManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFHTTPSessionManager.h; path = AFNetworking/AFHTTPSessionManager.h; sourceTree = ""; }; + AB2DF74840B542C3AD232BD2BD39EDAC /* Pods-GIGA-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-GIGA-acknowledgements.plist"; sourceTree = ""; }; + ABDEED48273ED3899189469BF754EA64 /* Masonry.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Masonry.h; path = Masonry/Masonry.h; sourceTree = ""; }; + AD7E0507C28D6B5E81792E2F089A883B /* MJRefresh.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefresh.h; path = MJRefresh/MJRefresh.h; sourceTree = ""; }; + AE211004837DB758CC532F2DBA59761F /* SocketRocket-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SocketRocket-umbrella.h"; sourceTree = ""; }; + AE26C6DD2E39EE7DC6BF9724F70BD49F /* IQKeyboardManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = IQKeyboardManager.h; path = IQKeyboardManager/IQKeyboardManager.h; sourceTree = ""; }; + AE919D25345375BA78B8CD922B87C8FC /* AFURLRequestSerialization.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFURLRequestSerialization.m; path = AFNetworking/AFURLRequestSerialization.m; sourceTree = ""; }; + AF1448946B3216D28ED8EB8AD4031D91 /* WXApi.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = WXApi.h; path = WechatSDK1.8.2/WXApi.h; sourceTree = ""; }; + B02F00E2B5DA269DDA1D546D77FD45BA /* UITableView_FDTemplateLayoutCell.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = UITableView_FDTemplateLayoutCell.framework; path = "UITableView+FDTemplateLayoutCell.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + B0455BB0F27DA9FDF09E6D7A8D38B2D8 /* SDWebImage-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SDWebImage-dummy.m"; sourceTree = ""; }; + B1A17C97B5BA3258AF5BFA6C4CB10011 /* MJRefreshConst.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshConst.m; path = MJRefresh/MJRefreshConst.m; sourceTree = ""; }; + B27B051036F118C3C3CD87D2112F68DA /* MASViewAttribute.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MASViewAttribute.m; path = Masonry/MASViewAttribute.m; sourceTree = ""; }; + B2A3E53B989849FAD2CD8B551234827B /* JSONModel.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = JSONModel.h; path = JSONModel/JSONModel/JSONModel.h; sourceTree = ""; }; + B3128EC48EC5433341A281DE78719B72 /* SDWebImageOperation.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageOperation.h; path = SDWebImage/SDWebImageOperation.h; sourceTree = ""; }; + B3746F3DB8A767202DDD4F8D8A9E522E /* NSImage+WebCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSImage+WebCache.m"; path = "SDWebImage/NSImage+WebCache.m"; sourceTree = ""; }; + B492A50B9B2BA1D7B867E756DCB7166A /* JPUSHService.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = JPUSHService.h; sourceTree = ""; }; + B4DF3C7BB807E1348544AA2900CC9BCC /* NJKWebViewProgress.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = NJKWebViewProgress.m; path = NJKWebViewProgress/NJKWebViewProgress.m; sourceTree = ""; }; + B54528DCAAE17FD388F81210D69C2B65 /* TTTAttributedLabel-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "TTTAttributedLabel-prefix.pch"; sourceTree = ""; }; + B597ABA83FF34D41BD88B02629DFF141 /* TTTAttributedLabel.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = TTTAttributedLabel.h; path = TTTAttributedLabel/TTTAttributedLabel.h; sourceTree = ""; }; + B5FB7DF227C9ADBFB34C1E276FF37EAA /* AFURLSessionManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFURLSessionManager.m; path = AFNetworking/AFURLSessionManager.m; sourceTree = ""; }; + B6800D584E4D1A1A19C71F4FD327A635 /* Toast.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Toast.h; path = "Toast-Framework/Toast.h"; sourceTree = ""; }; + B72C980E30572DC8C26C148404219FE9 /* YTKKeyValueStore.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = YTKKeyValueStore.framework; path = YTKKeyValueStore.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + B77606B69936F395DA6F6B9FF330A961 /* MASLayoutConstraint.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MASLayoutConstraint.h; path = Masonry/MASLayoutConstraint.h; sourceTree = ""; }; + B9F50AA966B1D80C51332499B80A5CFA /* IQUIViewController+Additions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "IQUIViewController+Additions.h"; path = "IQKeyboardManager/Categories/IQUIViewController+Additions.h"; sourceTree = ""; }; + BC724DAEA419916CD03249BD222F8124 /* UIImage+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIImage+AFNetworking.h"; path = "UIKit+AFNetworking/UIImage+AFNetworking.h"; sourceTree = ""; }; + BDA80F5D7B6C75DE56A43090A20E478E /* MobileCoreServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MobileCoreServices.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/MobileCoreServices.framework; sourceTree = DEVELOPER_DIR; }; + BE6A57C1E6EE6E72829EF1A0239DD712 /* NSButton+WebCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSButton+WebCache.m"; path = "SDWebImage/NSButton+WebCache.m"; sourceTree = ""; }; + BF83FBC6FB90CE550B6AF3F1CB2F1277 /* AFURLSessionManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFURLSessionManager.h; path = AFNetworking/AFURLSessionManager.h; sourceTree = ""; }; + BFB6E4B64CC9DCE8FD1F6CB4FA1AD798 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + C0E318B9FCDDCC5AA2EF7612D8B92B1C /* UIImage+ForceDecode.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImage+ForceDecode.m"; path = "SDWebImage/UIImage+ForceDecode.m"; sourceTree = ""; }; + C1023377CD29F52DBD86B670EC330990 /* NSButton+WebCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSButton+WebCache.h"; path = "SDWebImage/NSButton+WebCache.h"; sourceTree = ""; }; + C2916A23C5B0F16555EFB6F4420162BF /* JSONModelLib.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = JSONModelLib.h; path = JSONModel/JSONModelLib.h; sourceTree = ""; }; + C3ABE0317E38D1EFCDEEDCB80F2C86D8 /* MJRefresh.bundle */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "wrapper.plug-in"; name = MJRefresh.bundle; path = MJRefresh/MJRefresh.bundle; sourceTree = ""; }; + C3E61325D32EBCE4A1055AE3C720464B /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + C47485FA05B8E0C83A44515FDF510F25 /* JSONModelError.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = JSONModelError.m; path = JSONModel/JSONModel/JSONModelError.m; sourceTree = ""; }; + C5201CCF6BAA96A03DE5923F727DC879 /* UIImageView+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImageView+AFNetworking.m"; path = "UIKit+AFNetworking/UIImageView+AFNetworking.m"; sourceTree = ""; }; + C5F6388857FDFC150CCD9AEF58FD9078 /* UITableView+FDTemplateLayoutCell-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "UITableView+FDTemplateLayoutCell-dummy.m"; sourceTree = ""; }; + C68E6D01DE9F66C2C15D29D4D81D7DD0 /* IQUIView+IQKeyboardToolbar.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "IQUIView+IQKeyboardToolbar.h"; path = "IQKeyboardManager/IQToolbar/IQUIView+IQKeyboardToolbar.h"; sourceTree = ""; }; + C7949A099C444A21B8BF2123F5474A11 /* FMDatabasePool.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FMDatabasePool.h; path = src/fmdb/FMDatabasePool.h; sourceTree = ""; }; + C79F418E3B67CEA0D2E4853E93EB61D6 /* FMDB-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "FMDB-dummy.m"; sourceTree = ""; }; + CB3C6DE0D6C1AC3A7591955C5B69B39A /* WXApiObject.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = WXApiObject.h; path = WechatSDK1.8.2/WXApiObject.h; sourceTree = ""; }; + CBAE109E687AA08F5504796C0C8AAA94 /* NSArray+MASShorthandAdditions.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSArray+MASShorthandAdditions.h"; path = "Masonry/NSArray+MASShorthandAdditions.h"; sourceTree = ""; }; + CBC3B8F0F4C790990E0EAD42A406FC8E /* MBProgressHUD.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = MBProgressHUD.h; sourceTree = ""; }; + CD4F3960CA6F8FEB29501115CCD8193B /* IQKeyboardManager-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "IQKeyboardManager-prefix.pch"; sourceTree = ""; }; + CDC9C0D785840A863C238FA9918232BF /* MJRefreshGifHeader.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshGifHeader.h; path = MJRefresh/Custom/Header/MJRefreshGifHeader.h; sourceTree = ""; }; + D0BBA864722B591909F62D13DC4EEB0D /* AFAutoPurgingImageCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFAutoPurgingImageCache.h; path = "UIKit+AFNetworking/AFAutoPurgingImageCache.h"; sourceTree = ""; }; + D1BEE5EFF3DDAAB7DF105B6EE039CC8A /* MJRefreshNormalHeader.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshNormalHeader.h; path = MJRefresh/Custom/Header/MJRefreshNormalHeader.h; sourceTree = ""; }; + D23E765E4467A1A7780E0DA185FD0871 /* MJRefreshBackStateFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshBackStateFooter.h; path = MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.h; sourceTree = ""; }; + D3042F160C52C7D88773233C16FADD9D /* MASConstraintMaker.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MASConstraintMaker.h; path = Masonry/MASConstraintMaker.h; sourceTree = ""; }; + D3DDD162B07601DE29947637C3F96BD1 /* JSONModel.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = JSONModel.modulemap; sourceTree = ""; }; + D4372399A31F995ED53980B44F7B90A0 /* MJRefreshAutoNormalFooter.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshAutoNormalFooter.h; path = MJRefresh/Custom/Footer/Auto/MJRefreshAutoNormalFooter.h; sourceTree = ""; }; + D4D98F9C1B4313133F8617D4703C0673 /* UIWebView+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIWebView+AFNetworking.h"; path = "UIKit+AFNetworking/UIWebView+AFNetworking.h"; sourceTree = ""; }; + D50758F82022F3137CBA65220EEAE68E /* IQUITextFieldView+Additions.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "IQUITextFieldView+Additions.m"; path = "IQKeyboardManager/Categories/IQUITextFieldView+Additions.m"; sourceTree = ""; }; + D59CC779E29EBC0013D1E71D0571D5F5 /* MJRefreshBackFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshBackFooter.m; path = MJRefresh/Base/MJRefreshBackFooter.m; sourceTree = ""; }; + D5DA3E8C666672F7C13E27E88DD39873 /* MJRefreshStateHeader.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshStateHeader.h; path = MJRefresh/Custom/Header/MJRefreshStateHeader.h; sourceTree = ""; }; + D62B3C1698127F67086E6858CE18DE57 /* NSLayoutConstraint+MASDebugAdditions.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "NSLayoutConstraint+MASDebugAdditions.m"; path = "Masonry/NSLayoutConstraint+MASDebugAdditions.m"; sourceTree = ""; }; + D664875BF8233C012F6082B1CF537B8E /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + D6A5BFBE51D80535DEA9FCDD8E232F54 /* UIButton+WebCache.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIButton+WebCache.h"; path = "SDWebImage/UIButton+WebCache.h"; sourceTree = ""; }; + D77DAA3898C22DBC2AF3A8D090AC5F67 /* UIScrollView+MJExtension.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIScrollView+MJExtension.h"; path = "MJRefresh/UIScrollView+MJExtension.h"; sourceTree = ""; }; + D7AAFFA73849C31AECBF14C1EF8A1803 /* NSObject+LKDBHelper.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSObject+LKDBHelper.h"; path = "LKDBHelper/Helper/NSObject+LKDBHelper.h"; sourceTree = ""; }; + D7AE865D229ADE1C34958B1CED9B69F9 /* UIWebView+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIWebView+AFNetworking.m"; path = "UIKit+AFNetworking/UIWebView+AFNetworking.m"; sourceTree = ""; }; + D8024B8DF0B73056894292AB56168798 /* IQTitleBarButtonItem.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = IQTitleBarButtonItem.m; path = IQKeyboardManager/IQToolbar/IQTitleBarButtonItem.m; sourceTree = ""; }; + D8C17DF1169974E2F089CBF839A7E422 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + D935D6502CF164CFEAC6164421D07051 /* IQUIView+Hierarchy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "IQUIView+Hierarchy.m"; path = "IQKeyboardManager/Categories/IQUIView+Hierarchy.m"; sourceTree = ""; }; + DAEB829C6F88208F28EE3BB434586358 /* AFCompatibilityMacros.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFCompatibilityMacros.h; path = AFNetworking/AFCompatibilityMacros.h; sourceTree = ""; }; + DBDB01D83E6928E50B7FF753E107C53A /* JSONHTTPClient.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = JSONHTTPClient.m; path = JSONModel/JSONModelNetworking/JSONHTTPClient.m; sourceTree = ""; }; + DC42B3EFD027159BE710AF977CD3F498 /* Toast-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Toast-prefix.pch"; sourceTree = ""; }; + DC42CB78293EF7E2CE36240956AA0249 /* Toast.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Toast.xcconfig; sourceTree = ""; }; + DCF7622A90866CFF5D62183257744DE6 /* UITableView+FDTemplateLayoutCellDebug.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UITableView+FDTemplateLayoutCellDebug.h"; path = "Classes/UITableView+FDTemplateLayoutCellDebug.h"; sourceTree = ""; }; + DD9F8097FDD26C1A767654BEFDB692CC /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; + DDAD4BFB56B1F3E882395A34A77631FC /* MJRefreshComponent.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshComponent.h; path = MJRefresh/Base/MJRefreshComponent.h; sourceTree = ""; }; + DE6B846782E8125465DD1F586A583755 /* NSData+ImageContentType.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSData+ImageContentType.h"; path = "SDWebImage/NSData+ImageContentType.h"; sourceTree = ""; }; + DF6EA442E132FC00898030CD91DAE0EE /* LKDBHelper.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = LKDBHelper.modulemap; sourceTree = ""; }; + DFC7905E56582FC83E9C96252A1FA555 /* SocketRocket-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SocketRocket-prefix.pch"; sourceTree = ""; }; + E10C0C2DBA4DAE58B1ED06F7FAE8C22E /* JSONModelClassProperty.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = JSONModelClassProperty.h; path = JSONModel/JSONModel/JSONModelClassProperty.h; sourceTree = ""; }; + E26447099EDFE24E2B1AF730E232EB27 /* FMDatabase.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = FMDatabase.h; path = src/fmdb/FMDatabase.h; sourceTree = ""; }; + E299BD8696B2E375B3B2FB48F530F119 /* SDWebImageCompat.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageCompat.h; path = SDWebImage/SDWebImageCompat.h; sourceTree = ""; }; + E3B23910D26EDEA317A033232CA8A99D /* Toast.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Toast.modulemap; sourceTree = ""; }; + E45AFFE407A50EB7A6C9911EA9DA835A /* MJRefreshBackStateFooter.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = MJRefreshBackStateFooter.m; path = MJRefresh/Custom/Footer/Back/MJRefreshBackStateFooter.m; sourceTree = ""; }; + E4811330CBE4D8F15CD07A0E6B28196A /* SDWebImage.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SDWebImage.framework; path = SDWebImage.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + E57E4AA31B3259BADDB06AFC1EC7C03E /* Toast-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Toast-dummy.m"; sourceTree = ""; }; + E6F21509CADAC096896FDF9E0A67980E /* UIActivityIndicatorView+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIActivityIndicatorView+AFNetworking.h"; path = "UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h"; sourceTree = ""; }; + E7914083BC99732D0EB9526F21C3F14D /* IQKeyboardManagerConstants.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = IQKeyboardManagerConstants.h; path = IQKeyboardManager/Constants/IQKeyboardManagerConstants.h; sourceTree = ""; }; + E7CD153E51D85BD9B97F92233C5BD64F /* UIActivityIndicatorView+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIActivityIndicatorView+AFNetworking.m"; path = "UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m"; sourceTree = ""; }; + E8317B8AC22FB1696D93176C5E5DD172 /* NSObject+LKModel.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSObject+LKModel.h"; path = "LKDBHelper/Helper/NSObject+LKModel.h"; sourceTree = ""; }; + E836B7746FAE9BCF200AD6092BEA26FA /* UIProgressView+AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIProgressView+AFNetworking.h"; path = "UIKit+AFNetworking/UIProgressView+AFNetworking.h"; sourceTree = ""; }; + E838CA14206F7C95DDF8E5A291D3845A /* IQUIViewController+Additions.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "IQUIViewController+Additions.m"; path = "IQKeyboardManager/Categories/IQUIViewController+Additions.m"; sourceTree = ""; }; + E85D699181AA7FA0C2BD301F59B6B2B3 /* IQPreviousNextView.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = IQPreviousNextView.h; path = IQKeyboardManager/IQToolbar/IQPreviousNextView.h; sourceTree = ""; }; + E9B9FF3E9F69E2D04EB243D2A2B0D44A /* UIImage+MultiFormat.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIImage+MultiFormat.m"; path = "SDWebImage/UIImage+MultiFormat.m"; sourceTree = ""; }; + E9CC4C0DA475DA5B31053CF995EC62C0 /* UIView+WebCache.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIView+WebCache.m"; path = "SDWebImage/UIView+WebCache.m"; sourceTree = ""; }; + EA582EA6A55F892186937BD64F6CA1C5 /* YTKKeyValueStore-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "YTKKeyValueStore-umbrella.h"; sourceTree = ""; }; + EAFD436D5E0537D470329DFCF3A97191 /* JSONKeyMapper.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = JSONKeyMapper.h; path = JSONModel/JSONModelTransformations/JSONKeyMapper.h; sourceTree = ""; }; + EB20094359DE221C41846E960C38BB8B /* IQTextView.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = IQTextView.h; path = IQKeyboardManager/IQTextView/IQTextView.h; sourceTree = ""; }; + EB57F96C679159F822541623D7479456 /* libWeChatSDK.a */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = archive.ar; name = libWeChatSDK.a; path = WechatSDK1.8.2/libWeChatSDK.a; sourceTree = ""; }; + EB5A22B7F55187B0C899BDE644913E34 /* NJKWebViewProgress.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = NJKWebViewProgress.h; path = NJKWebViewProgress/NJKWebViewProgress.h; sourceTree = ""; }; + ECEDCC8EF733B2FA85A2559FD547A300 /* IQBarButtonItem.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = IQBarButtonItem.h; path = IQKeyboardManager/IQToolbar/IQBarButtonItem.h; sourceTree = ""; }; + EF2886493D8197A42561F3F3282F8612 /* SDWebImageManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageManager.m; path = SDWebImage/SDWebImageManager.m; sourceTree = ""; }; + EF536E6DCD40B46C2DDB4A7B5CDF9949 /* IQPreviousNextView.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = IQPreviousNextView.m; path = IQKeyboardManager/IQToolbar/IQPreviousNextView.m; sourceTree = ""; }; + EF647DB47CA8072604B32A11D318121C /* SDWebImageTransition.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageTransition.m; path = SDWebImage/SDWebImageTransition.m; sourceTree = ""; }; + EF729ACD28BC9F84101647D920D4287D /* AFNetworking.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFNetworking.h; path = AFNetworking/AFNetworking.h; sourceTree = ""; }; + EF92BCA63C71FB6589B6D4DE535D28B2 /* IQKeyboardManager.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = IQKeyboardManager.modulemap; sourceTree = ""; }; + F11F0CB1B9CA018793DBBE97E44883F4 /* SDWebImageDownloader.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SDWebImageDownloader.m; path = SDWebImage/SDWebImageDownloader.m; sourceTree = ""; }; + F2D330C281F30235A5D8E2C8D8CC7445 /* SRWebSocket.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = SRWebSocket.m; path = SocketRocket/SRWebSocket.m; sourceTree = ""; }; + F371B6BB584B1CC6193A5B5E7327AD5A /* UIView+MJExtension.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UIView+MJExtension.h"; path = "MJRefresh/UIView+MJExtension.h"; sourceTree = ""; }; + F37E8A21FCF063D9A8212C6CA857A124 /* YTKKeyValueStore.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = YTKKeyValueStore.xcconfig; sourceTree = ""; }; + F39CD7FEBA3936962AFCB24609CFA605 /* SocketRocket.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SocketRocket.h; path = SocketRocket/SocketRocket.h; sourceTree = ""; }; + F42F1412F20D8BA676203B880AC08EE3 /* UITableView+FDTemplateLayoutCell-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "UITableView+FDTemplateLayoutCell-umbrella.h"; sourceTree = ""; }; + F5F9245FC6E3E879D3070CAC3CE9039E /* AFNetworkReachabilityManager.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = AFNetworkReachabilityManager.m; path = AFNetworking/AFNetworkReachabilityManager.m; sourceTree = ""; }; + F60AD73AF21127AF807A87155E176BB2 /* SDWebImageGIFCoder.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageGIFCoder.h; path = SDWebImage/SDWebImageGIFCoder.h; sourceTree = ""; }; + F63B516844D3BA3C6CC53B029BFB6C1D /* SDWebImageDownloader.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageDownloader.h; path = SDWebImage/SDWebImageDownloader.h; sourceTree = ""; }; + F64387C5F8EF527B7D20778BEE103274 /* FMDB-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "FMDB-umbrella.h"; sourceTree = ""; }; + F66E969B978843AD18F5745FC07B3C9B /* SDWebImageTransition.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImageTransition.h; path = SDWebImage/SDWebImageTransition.h; sourceTree = ""; }; + F72E8914E30DFA385018D03B6F117C98 /* UITableView+FDTemplateLayoutCell.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UITableView+FDTemplateLayoutCell.m"; path = "Classes/UITableView+FDTemplateLayoutCell.m"; sourceTree = ""; }; + F75D7F8DB268EAE736A191EE0B8F9761 /* IQUIScrollView+Additions.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "IQUIScrollView+Additions.m"; path = "IQKeyboardManager/Categories/IQUIScrollView+Additions.m"; sourceTree = ""; }; + F79298FCF0E5B2FCDD163272B33DB5DE /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/SystemConfiguration.framework; sourceTree = DEVELOPER_DIR; }; + F8242C88C595688B579B2B397424ADC8 /* Pods-GIGA-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-GIGA-resources.sh"; sourceTree = ""; }; + F84E6ED65E201E2FB224E9591458D599 /* IQUIView+Hierarchy.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "IQUIView+Hierarchy.h"; path = "IQKeyboardManager/Categories/IQUIView+Hierarchy.h"; sourceTree = ""; }; + F898CDF03B802432B5C1BDB6EE59D826 /* AFNetworking-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "AFNetworking-umbrella.h"; sourceTree = ""; }; + F8EDD5DCE505C958412B980AE9818187 /* SDWebImage.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SDWebImage.xcconfig; sourceTree = ""; }; + F92F1C168C292C57C28B8CB8572DA418 /* MJRefreshHeader.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = MJRefreshHeader.h; path = MJRefresh/Base/MJRefreshHeader.h; sourceTree = ""; }; + F9CB6479D82C197DA7B4EE0F7B6817CA /* WechatAuthSDK.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = WechatAuthSDK.h; path = WechatSDK1.8.2/WechatAuthSDK.h; sourceTree = ""; }; + F9D614BEB063937B5BF5775FECFC299E /* AFNetworkActivityIndicatorManager.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AFNetworkActivityIndicatorManager.h; path = "UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h"; sourceTree = ""; }; + FA61AF596C08910907F9123EEB554A9B /* NSBundle+MJRefresh.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "NSBundle+MJRefresh.h"; path = "MJRefresh/NSBundle+MJRefresh.h"; sourceTree = ""; }; + FA6A254D84CBEA155F2904CB5F55CFEE /* MBProgressHUD-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "MBProgressHUD-prefix.pch"; sourceTree = ""; }; + FB184C0EAA6CE1C593837FC6A4C4A7A0 /* UITableView+FDTemplateLayoutCell.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "UITableView+FDTemplateLayoutCell.h"; path = "Classes/UITableView+FDTemplateLayoutCell.h"; sourceTree = ""; }; + FD113136C3BE7E4822B80A29F3DC5E42 /* Pods-GIGA-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-GIGA-dummy.m"; sourceTree = ""; }; + FEC5B235D8066671988C356BB8479445 /* UIProgressView+AFNetworking.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "UIProgressView+AFNetworking.m"; path = "UIKit+AFNetworking/UIProgressView+AFNetworking.m"; sourceTree = ""; }; + FFFC1118336CE5A0F2379778BD1CBCFE /* SDWebImagePrefetcher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = SDWebImagePrefetcher.h; path = SDWebImage/SDWebImagePrefetcher.h; sourceTree = ""; }; + FFFC1D06E09FCB725E5075FB470389CA /* IQKeyboardManager.bundle */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = "wrapper.plug-in"; name = IQKeyboardManager.bundle; path = IQKeyboardManager/Resources/IQKeyboardManager.bundle; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 0F13FDE48FAA625D37D626F69DA46819 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + D4E9B3DE75C23D365E255B6212CB1CB7 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 1AAD91176E5F5F9AD062AD678F6746E4 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A2D9F9EFFDFE9C19DA842E826B06BCEB /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 2F6AD2793DCCAC8655F20980C31F5B6E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + F38B93D66E5151DC14AA52242858DDCB /* FMDB.framework in Frameworks */, + D2AFDC9DBB18F68AD5B7EE3A1A951D68 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 59DA24E1BFBF4DF2381ED2E0EE6964A0 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 347945A5FC349A6E31AC7E3403E2CDE5 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6DE9B3A8689C804A43D970F1265675A4 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78AC6714960C42CC866222B6D956EDF6 /* CoreGraphics.framework in Frameworks */, + 09EC74E4AFC1D5951D1F80094D06969A /* Foundation.framework in Frameworks */, + 89637BFFD180A1E05F04DAF0CF4A6540 /* MobileCoreServices.framework in Frameworks */, + 6478B0091202F9429D2A61E30BEDA571 /* Security.framework in Frameworks */, + 81ABD96C8FA6FF28CFB2A3A78A6EA560 /* SystemConfiguration.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 77A4F3ABB18A1CBD901A6D7F4564A99A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2B0AD5F72C574005D53D512A8F8E2800 /* FMDB.framework in Frameworks */, + 02A0ADD96B43A9970DD5C7C6BAEAB761 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8944C0B131AF550CF6CC8073435E22F2 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A1BB32FF4BE29C004A13F2E03127E8F1 /* CoreGraphics.framework in Frameworks */, + 6D13591A430260C31F6102B30645B5CD /* Foundation.framework in Frameworks */, + 148E57B8B5F299475BF5877A2EA6E7C1 /* QuartzCore.framework in Frameworks */, + 291C24EA8B69C1738694B0729ED3ADA4 /* UIKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 89CB805BF93CBFFF9178240B3DA62840 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + DBD3B4544D8320D0D83479AEB921D088 /* CFNetwork.framework in Frameworks */, + C6CCF6FAC5899D681F921B1917ECD40E /* Foundation.framework in Frameworks */, + B690948AF82E335069677012C9793C0A /* Security.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 99BF636A9F3AC96472168608CED7A74E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + BE342AF4C9583018FBDF18A52FAE927A /* Foundation.framework in Frameworks */, + 48B6FAC56A1A05850F229702C850CDB1 /* QuartzCore.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9FE6CEF1763E05FB90653801CE3E2B5B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + E4AC26FB387427964538FA5FCEA4A8A3 /* CoreGraphics.framework in Frameworks */, + ECBA1F4D70AF4600563FD39112D5997B /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B8E0CDE9D6B78B63BC6132265D5D95E0 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + F53E65E5CA956894846C5A6969536F83 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CCB6C94A3B7F7AF612CA6128178B688A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2E2BA6CBA0D6349BF6CF9E13753D5DBD /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EEFB61A65EB8DA6653B544822EB9CE44 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 72563ADE99DC9E753B27D48B16AA3654 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F43DF7F5860C5353DC417595794C69DB /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 41BA2631080F7FE9052001D51A5104E7 /* Foundation.framework in Frameworks */, + 2B66A577AE7687E6001469BF9F99CA5B /* ImageIO.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F6EC657AC5A7BEE9A3D288B582F4C5E9 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 432FA22864D148EBD4CB22F55AB68004 /* Foundation.framework in Frameworks */, + 38E0CD63021889EE46E1A6B9FA0415F5 /* UIKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F8B6CBF4BE519D592974034E0A5D06DA /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + DA75132AF02110EA8FED838245F245B3 /* CoreGraphics.framework in Frameworks */, + FA194D9EFAB084FD2FF27BF01F7B30DD /* CoreText.framework in Frameworks */, + 13DEE8E5A10BE2160E85D5B339446521 /* Foundation.framework in Frameworks */, + CBA3B98ED2708713025BFD6F244D419F /* QuartzCore.framework in Frameworks */, + 28D57235593277A82B18D9E2B3B4B5ED /* UIKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 01D6253C27FE24064BE3A182F31EAF7D /* TTTAttributedLabel */ = { + isa = PBXGroup; + children = ( + B597ABA83FF34D41BD88B02629DFF141 /* TTTAttributedLabel.h */, + 4CE36714FF24257CBB6D4A43CE11D871 /* TTTAttributedLabel.m */, + 1846DA0110F324051424B5CDA0786569 /* Support Files */, + ); + name = TTTAttributedLabel; + path = TTTAttributedLabel; + sourceTree = ""; + }; + 01E8C2568D6E2F08B419418E6D7ACBAE /* Support Files */ = { + isa = PBXGroup; + children = ( + 207C7B70CDF9CB324605A2DE508A6A07 /* Info.plist */, + D3DDD162B07601DE29947637C3F96BD1 /* JSONModel.modulemap */, + 9508DBBE609A983ECCD13E2627C7678E /* JSONModel.xcconfig */, + 26C29828B683FB67FD6E1E218F63F152 /* JSONModel-dummy.m */, + 8D854FE9416C9CB1B7597F28FE1AF9F1 /* JSONModel-prefix.pch */, + 4A9D286E65BE10630D2D01808B376E3F /* JSONModel-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/JSONModel"; + sourceTree = ""; + }; + 021FEB9DC865A149815BAC72AF6E091A /* Support Files */ = { + isa = PBXGroup; + children = ( + 4B63AC7AEEF5E567F175F4F93CD3E083 /* Info.plist */, + 9A99A07094C4466F723559D841338C20 /* NJKWebViewProgress.modulemap */, + 758B3F6E587B47427A1ADFF5C9973B84 /* NJKWebViewProgress.xcconfig */, + 147C7A5F29B419F15BD11AE9B4D6E40F /* NJKWebViewProgress-dummy.m */, + 4828CBF98C8FA0FD91EC3A44854FF58F /* NJKWebViewProgress-prefix.pch */, + 68C17CA9F7C67D59F90F34E65B93D62E /* NJKWebViewProgress-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/NJKWebViewProgress"; + sourceTree = ""; + }; + 05EBD8BDE003587FA6FCE72925D5CE5D /* Support Files */ = { + isa = PBXGroup; + children = ( + 1A438A62B6C02EC44F5039151E9F9A71 /* Info.plist */, + 854A1DB41CF7A374ADAE2118B47984FC /* SocketRocket.modulemap */, + 17979012F15292B8E646C3D69BB45763 /* SocketRocket.xcconfig */, + 3C0DB12ED7065982F99681E7208B396E /* SocketRocket-dummy.m */, + DFC7905E56582FC83E9C96252A1FA555 /* SocketRocket-prefix.pch */, + AE211004837DB758CC532F2DBA59761F /* SocketRocket-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/SocketRocket"; + sourceTree = ""; + }; + 060922B716FF31D85A27005CADCAC643 /* ProgressView */ = { + isa = PBXGroup; + children = ( + 954FBC78E632E1BCD88EEB65027EAEDE /* NJKWebViewProgressView.h */, + 4B3F07A870FB3A3BFB758AD0E1BE2C36 /* NJKWebViewProgressView.m */, + ); + name = ProgressView; + sourceTree = ""; + }; + 09CFE9D731B4AF8CC2880C9887CD494F /* JPush */ = { + isa = PBXGroup; + children = ( + B492A50B9B2BA1D7B867E756DCB7166A /* JPUSHService.h */, + 4C8EDE720C81C0372D7448EB09E55701 /* Frameworks */, + ); + name = JPush; + path = JPush; + sourceTree = ""; + }; + 0E915C4D94602C591F6A5CC632DC1007 /* YTKKeyValueStore */ = { + isa = PBXGroup; + children = ( + 73EB4D54E40F7146E8F50D99256E3AB6 /* YTKKeyValueStore.h */, + 2CE1C92FCE95492CB6C334FDB10A3525 /* YTKKeyValueStore.m */, + 279B30241AC95D812E1CB0968C7689D8 /* Support Files */, + ); + name = YTKKeyValueStore; + path = YTKKeyValueStore; + sourceTree = ""; + }; + 1846DA0110F324051424B5CDA0786569 /* Support Files */ = { + isa = PBXGroup; + children = ( + 5E99B96339C8127EC7FC7C8FFD3C7553 /* Info.plist */, + 5C9D2325DCA16A38D58B21BD7DB5CF28 /* TTTAttributedLabel.modulemap */, + 572894CF08231457B24C1071533852F6 /* TTTAttributedLabel.xcconfig */, + 0B7DB276EA29841EF61406CACDDBA7DF /* TTTAttributedLabel-dummy.m */, + B54528DCAAE17FD388F81210D69C2B65 /* TTTAttributedLabel-prefix.pch */, + 6930C47F6DA9FF53FCC809972D1C2267 /* TTTAttributedLabel-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/TTTAttributedLabel"; + sourceTree = ""; + }; + 1F7B07C459EA3268CF782A3D115FA759 /* LKDBHelper */ = { + isa = PBXGroup; + children = ( + 5732733F4F0B03379EF5B7AB163B963E /* standard */, + 5F2254EB65E8743B4F88570AFDD347F9 /* Support Files */, + ); + name = LKDBHelper; + path = LKDBHelper; + sourceTree = ""; + }; + 204D78156C2EC3DBC444EB544EC0A6C9 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + FBB949B909D1BC7355CE4C96A365A607 /* Pods-GIGA */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + 2462064A6081ED68A040469CF7B0A674 /* Support Files */ = { + isa = PBXGroup; + children = ( + 36D82CC8DDDDD9C3AA54A9368D31C3B7 /* Info.plist */, + 453E45CF34A191D43B74674E7A90FBD7 /* MJRefresh.modulemap */, + 39CB9D0EBDE904E619E327F0B49A9062 /* MJRefresh.xcconfig */, + 7105E6B5675EAB9B1DB66075A38FC383 /* MJRefresh-dummy.m */, + 0A9C84FF7695F4A1769FBD2619ECC029 /* MJRefresh-prefix.pch */, + 2AE6A655C2E452806506AB901CB710BC /* MJRefresh-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/MJRefresh"; + sourceTree = ""; + }; + 279B30241AC95D812E1CB0968C7689D8 /* Support Files */ = { + isa = PBXGroup; + children = ( + C3E61325D32EBCE4A1055AE3C720464B /* Info.plist */, + 30D477DB1A599E055F88B89589F278A7 /* YTKKeyValueStore.modulemap */, + F37E8A21FCF063D9A8212C6CA857A124 /* YTKKeyValueStore.xcconfig */, + 2BB9D5AF91DFC97D964A3278CD65C526 /* YTKKeyValueStore-dummy.m */, + 5464A11C33E8A793B5FAA8C62E68999D /* YTKKeyValueStore-prefix.pch */, + EA582EA6A55F892186937BD64F6CA1C5 /* YTKKeyValueStore-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/YTKKeyValueStore"; + sourceTree = ""; + }; + 3CD1199C5CEF88CE566F0DD9431C294F /* Security */ = { + isa = PBXGroup; + children = ( + 12F1549F9D1FEC79B40E50D906C6E8CC /* AFSecurityPolicy.h */, + 2764D65BCE489D3C4CED132E012A1434 /* AFSecurityPolicy.m */, + ); + name = Security; + sourceTree = ""; + }; + 405C02B08001E17E18B08C927D4CD6CF /* Support Files */ = { + isa = PBXGroup; + children = ( + 1268983E6F23E528A8D0D9A8615131B6 /* AFNetworking.modulemap */, + 0712B6EB2B50F748C0C18FF36D97B3DF /* AFNetworking.xcconfig */, + 422402DD22D498220638075EF90B07A3 /* AFNetworking-dummy.m */, + A77BAB4386BD7374C1D019FB835C1F77 /* AFNetworking-prefix.pch */, + F898CDF03B802432B5C1BDB6EE59D826 /* AFNetworking-umbrella.h */, + 10E8184A26C2F3665BEE0311F178C96E /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/AFNetworking"; + sourceTree = ""; + }; + 40720EB1BF2BBEC9F842CF644AEA2FF0 /* UITableView+FDTemplateLayoutCell */ = { + isa = PBXGroup; + children = ( + 623CEFA44508E2233D6C8BDDC1A723AB /* UITableView+FDIndexPathHeightCache.h */, + 08E127FD35CF12E2DFEAE98245B87676 /* UITableView+FDIndexPathHeightCache.m */, + 22C882FD98CA446EFA39A29BFF94A28B /* UITableView+FDKeyedHeightCache.h */, + 2127EDE3F7D3FA57134EACCE79E57C4B /* UITableView+FDKeyedHeightCache.m */, + FB184C0EAA6CE1C593837FC6A4C4A7A0 /* UITableView+FDTemplateLayoutCell.h */, + F72E8914E30DFA385018D03B6F117C98 /* UITableView+FDTemplateLayoutCell.m */, + DCF7622A90866CFF5D62183257744DE6 /* UITableView+FDTemplateLayoutCellDebug.h */, + 2F9966C0F9F759260F26024DC5F6FCB1 /* UITableView+FDTemplateLayoutCellDebug.m */, + BDC55BBF9D65278672BAE81AD9040ECD /* Support Files */, + ); + name = "UITableView+FDTemplateLayoutCell"; + path = "UITableView+FDTemplateLayoutCell"; + sourceTree = ""; + }; + 40CD1D51F43C1B457F999E6EAAD05746 /* Resources */ = { + isa = PBXGroup; + children = ( + C3ABE0317E38D1EFCDEEDCB80F2C86D8 /* MJRefresh.bundle */, + ); + name = Resources; + sourceTree = ""; + }; + 48DC167AA915D67ACB11445A672127DD /* MBProgressHUD */ = { + isa = PBXGroup; + children = ( + CBC3B8F0F4C790990E0EAD42A406FC8E /* MBProgressHUD.h */, + 272CBD0843CB816395E98BA936E24B87 /* MBProgressHUD.m */, + C5C82C4EF670EFD5913423A97472284F /* Support Files */, + ); + name = MBProgressHUD; + path = MBProgressHUD; + sourceTree = ""; + }; + 4C8EDE720C81C0372D7448EB09E55701 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 6CE816757FAB87E4B239A9085210DA0C /* libjpush-ios-3.1.0.a */, + ); + name = Frameworks; + sourceTree = ""; + }; + 4E2409466EDA7D01AAFAA30805FECFE6 /* Pods */ = { + isa = PBXGroup; + children = ( + 6933B7F163390872D50F8E117EB082C7 /* AFNetworking */, + E9BE045C83FF29AC7E11071DF389EEBA /* FMDB */, + C0BFCE03F930943A24DEE8FF325CFC73 /* IQKeyboardManager */, + DD333C0B31A9ADBD5F94278B63FF34BA /* JCore */, + 09CFE9D731B4AF8CC2880C9887CD494F /* JPush */, + DDBA2363A71ACA26A55AA9E9624F6937 /* JSONModel */, + 1F7B07C459EA3268CF782A3D115FA759 /* LKDBHelper */, + 96B1E2700A00C3B89D34F5887525CDFD /* Masonry */, + 48DC167AA915D67ACB11445A672127DD /* MBProgressHUD */, + C2F9AAA86531AE276C6CB86983E76035 /* MJRefresh */, + D43F32F7C148ED9532BFE3EC61BA319E /* NJKWebViewProgress */, + C6BBCD0A12903501F64C8279700A8E78 /* SDWebImage */, + F440F326A67EDD4710F38EFA8047C7B2 /* SocketRocket */, + C7CDEDA068E9C4538A614C77593EE6D0 /* Toast */, + 01D6253C27FE24064BE3A182F31EAF7D /* TTTAttributedLabel */, + 40720EB1BF2BBEC9F842CF644AEA2FF0 /* UITableView+FDTemplateLayoutCell */, + EEF7773B173A78B2CE1CF7937918485B /* WechatOpenSDK */, + 0E915C4D94602C591F6A5CC632DC1007 /* YTKKeyValueStore */, + ); + name = Pods; + sourceTree = ""; + }; + 544FB77D6D6BCB080AE979EA734CA3D9 /* Products */ = { + isa = PBXGroup; + children = ( + 8126B93DD8D474B90337F38D978130C5 /* AFNetworking.framework */, + 8E5DA37AC55ADD979E448DB4CCE99D62 /* FMDB.framework */, + 581983071B50ED00E03BBC3807ED5DEB /* IQKeyboardManager.framework */, + 342C32AD5BF61779D426BDA9F82DEDE5 /* JSONModel.framework */, + 961B9982B287A938D23CE983804F2FC5 /* LKDBHelper.framework */, + 0D6854C9307CDCC712B55D7EC927935E /* Masonry.framework */, + 4738089B8361F3D3AB1BCED704498464 /* MBProgressHUD.framework */, + 2312E64F77FC628042C95F6F42AC9204 /* MJRefresh.framework */, + 4AFDFD2D9A90BF4BB9DD861020532888 /* NJKWebViewProgress.framework */, + 1DB7026C750DB559A03CDBE2742DC1B3 /* Pods_GIGA.framework */, + E4811330CBE4D8F15CD07A0E6B28196A /* SDWebImage.framework */, + 9E43D4748ACBDE3E7E8E94CCE6225EFE /* SocketRocket.framework */, + A7319007CA14024A0376E223A1A702CB /* Toast.framework */, + A57F7F0A6AB5550D6C39E86241A2C3B4 /* TTTAttributedLabel.framework */, + B02F00E2B5DA269DDA1D546D77FD45BA /* UITableView_FDTemplateLayoutCell.framework */, + B72C980E30572DC8C26C148404219FE9 /* YTKKeyValueStore.framework */, + ); + name = Products; + sourceTree = ""; + }; + 5732733F4F0B03379EF5B7AB163B963E /* standard */ = { + isa = PBXGroup; + children = ( + 756EBE270AB520A42983575D8062C88C /* LKDB+Mapping.h */, + 78B556FE17B6F40F4C14A82F0936900C /* LKDB+Mapping.m */, + 5F98DCFCF300EBC97C2A16DCF1294D7F /* LKDBHelper.h */, + 4D870611B8793D878F9166BF6ACFCAFB /* LKDBHelper.m */, + 14A57F7FDCD24207067E3E300876540C /* LKDBUtils.h */, + A81B52350911B789957965FA41897580 /* LKDBUtils.m */, + D7AAFFA73849C31AECBF14C1EF8A1803 /* NSObject+LKDBHelper.h */, + 311DDA855B68C2C82DA3F585C044E5D0 /* NSObject+LKDBHelper.m */, + E8317B8AC22FB1696D93176C5E5DD172 /* NSObject+LKModel.h */, + 94FEA07F421E380A35B094F7568EAF10 /* NSObject+LKModel.m */, + ); + name = standard; + sourceTree = ""; + }; + 5F2254EB65E8743B4F88570AFDD347F9 /* Support Files */ = { + isa = PBXGroup; + children = ( + 4FD6E6CFFA09827B260BD7CEF9FB0968 /* Info.plist */, + DF6EA442E132FC00898030CD91DAE0EE /* LKDBHelper.modulemap */, + 7297AD18E47185F3F70FA09B01B9E511 /* LKDBHelper.xcconfig */, + 7EC0F45B5A1A9049F0BA580A2E665024 /* LKDBHelper-dummy.m */, + 5FA15CE76838746D55FF0B6B9296F3F7 /* LKDBHelper-prefix.pch */, + 732E1114AA44818AFA36C115D6C2E3B3 /* LKDBHelper-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/LKDBHelper"; + sourceTree = ""; + }; + 62C036EABCB21A4EEE1067F2E9297965 /* UIKit */ = { + isa = PBXGroup; + children = ( + D0BBA864722B591909F62D13DC4EEB0D /* AFAutoPurgingImageCache.h */, + A9BD5EC9B66096A214F0369AC4DB24E4 /* AFAutoPurgingImageCache.m */, + 0AB0C00E8C3E7BA94AF01A2DD16F0620 /* AFImageDownloader.h */, + 8C9BAAF1EC72C985C348BCF60EC4D10A /* AFImageDownloader.m */, + F9D614BEB063937B5BF5775FECFC299E /* AFNetworkActivityIndicatorManager.h */, + 0F034245E549B8FD80F5294F722A39F5 /* AFNetworkActivityIndicatorManager.m */, + E6F21509CADAC096896FDF9E0A67980E /* UIActivityIndicatorView+AFNetworking.h */, + E7CD153E51D85BD9B97F92233C5BD64F /* UIActivityIndicatorView+AFNetworking.m */, + 90670E1F67061B599C126301C1A3C2D0 /* UIButton+AFNetworking.h */, + 95E1101C679649DD67CF310BC7C41D40 /* UIButton+AFNetworking.m */, + BC724DAEA419916CD03249BD222F8124 /* UIImage+AFNetworking.h */, + 6AD72E84C0BAA5647385371F3B370E7D /* UIImageView+AFNetworking.h */, + C5201CCF6BAA96A03DE5923F727DC879 /* UIImageView+AFNetworking.m */, + 6FD79569D1481B1CCEBC524AE5E2B8C0 /* UIKit+AFNetworking.h */, + E836B7746FAE9BCF200AD6092BEA26FA /* UIProgressView+AFNetworking.h */, + FEC5B235D8066671988C356BB8479445 /* UIProgressView+AFNetworking.m */, + 723FBBA74F07E67C701AE828B5405E83 /* UIRefreshControl+AFNetworking.h */, + 2368EA7094707071EF9EB1847081B539 /* UIRefreshControl+AFNetworking.m */, + D4D98F9C1B4313133F8617D4703C0673 /* UIWebView+AFNetworking.h */, + D7AE865D229ADE1C34958B1CED9B69F9 /* UIWebView+AFNetworking.m */, + ); + name = UIKit; + sourceTree = ""; + }; + 6933B7F163390872D50F8E117EB082C7 /* AFNetworking */ = { + isa = PBXGroup; + children = ( + EF729ACD28BC9F84101647D920D4287D /* AFNetworking.h */, + 9E227C9A88916A75B5ECA7AB82A86D07 /* NSURLSession */, + F139BBCD98A0E7BAE3ACB11DD38CE8CF /* Reachability */, + 3CD1199C5CEF88CE566F0DD9431C294F /* Security */, + 8C7561F5ACBC2F088FFE8FD9E091C53B /* Serialization */, + 405C02B08001E17E18B08C927D4CD6CF /* Support Files */, + 62C036EABCB21A4EEE1067F2E9297965 /* UIKit */, + ); + name = AFNetworking; + path = AFNetworking; + sourceTree = ""; + }; + 6BC435B216BF0CD988087AF387048847 /* Support Files */ = { + isa = PBXGroup; + children = ( + D664875BF8233C012F6082B1CF537B8E /* Info.plist */, + EF92BCA63C71FB6589B6D4DE535D28B2 /* IQKeyboardManager.modulemap */, + 687C5821B77D4D232E15C3BD22C69C47 /* IQKeyboardManager.xcconfig */, + 951A926C2E402064AFF54E885DEE23D1 /* IQKeyboardManager-dummy.m */, + CD4F3960CA6F8FEB29501115CCD8193B /* IQKeyboardManager-prefix.pch */, + 362634D02C8734DCDBB1B3FA29AF2E5A /* IQKeyboardManager-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/IQKeyboardManager"; + sourceTree = ""; + }; + 70BBF347D3A89FFECCDCCCF0D97A1027 /* Support Files */ = { + isa = PBXGroup; + children = ( + 598BCA3C824B45B4D482801D765BB44E /* Info.plist */, + 29BE32503E41FD5479AAF41A8A089CFD /* Masonry.modulemap */, + 0DE0E0C75D4EFF8E1F1A6897C860EC33 /* Masonry.xcconfig */, + 491FD42A9D3970BD3ACF252F98B968EB /* Masonry-dummy.m */, + 1A7BD38C15C083C8004AF81AE4248CFF /* Masonry-prefix.pch */, + 8CB53A6BCAB7A1F76E7F79652415A592 /* Masonry-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/Masonry"; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, + B46F6D1AC0DA31D8B1B98490D3896990 /* Frameworks */, + 4E2409466EDA7D01AAFAA30805FECFE6 /* Pods */, + 544FB77D6D6BCB080AE979EA734CA3D9 /* Products */, + 204D78156C2EC3DBC444EB544EC0A6C9 /* Targets Support Files */, + ); + sourceTree = ""; + }; + 81AAE6DFE3752B1E3CE9FA5345D4D8E0 /* Support Files */ = { + isa = PBXGroup; + children = ( + 2B1A51FCBEFB476684647C57EDFB6E27 /* Info.plist */, + E3B23910D26EDEA317A033232CA8A99D /* Toast.modulemap */, + DC42CB78293EF7E2CE36240956AA0249 /* Toast.xcconfig */, + E57E4AA31B3259BADDB06AFC1EC7C03E /* Toast-dummy.m */, + DC42B3EFD027159BE710AF977CD3F498 /* Toast-prefix.pch */, + 9B608913B805E97D3B45F563A37ABCEB /* Toast-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/Toast"; + sourceTree = ""; + }; + 858F9FCAC1FEC22689328C603B89D06B /* Frameworks */ = { + isa = PBXGroup; + children = ( + 38D4A17D513EE0A59F71025AE92894BB /* libjcore-ios-1.2.2.a */, + ); + name = Frameworks; + sourceTree = ""; + }; + 8C7561F5ACBC2F088FFE8FD9E091C53B /* Serialization */ = { + isa = PBXGroup; + children = ( + 9224D1F9357D1822DC11BB7D3C5CA29B /* AFURLRequestSerialization.h */, + AE919D25345375BA78B8CD922B87C8FC /* AFURLRequestSerialization.m */, + 0437B58A81D211C5C568BBC32D5ED7EF /* AFURLResponseSerialization.h */, + 105F2F5DE7034DDDB46A5FF6C1257C53 /* AFURLResponseSerialization.m */, + ); + name = Serialization; + sourceTree = ""; + }; + 96B1E2700A00C3B89D34F5887525CDFD /* Masonry */ = { + isa = PBXGroup; + children = ( + 2F239ADCBC9530CFB69A3DBA4606CB39 /* MASCompositeConstraint.h */, + 673F2354B6D1C0F8E9955046A21D6A4B /* MASCompositeConstraint.m */, + 35877F4071E71D27BA630FEDB0FE43BA /* MASConstraint.h */, + 30C9D2B8F917B8405C9B54173E51741E /* MASConstraint.m */, + 417E2E632AF904B3B32155C62F0B19DC /* MASConstraint+Private.h */, + D3042F160C52C7D88773233C16FADD9D /* MASConstraintMaker.h */, + 9404C50D3CA53F5CBA8FB043A06BFAD6 /* MASConstraintMaker.m */, + B77606B69936F395DA6F6B9FF330A961 /* MASLayoutConstraint.h */, + 76E253E1BAB6E3A4164B42F93C3B0EE8 /* MASLayoutConstraint.m */, + ABDEED48273ED3899189469BF754EA64 /* Masonry.h */, + 26C0262CE054672814BFFD41BA3DE3AC /* MASUtilities.h */, + 0B8497F4D647973F7EF7F63CA4433C95 /* MASViewAttribute.h */, + B27B051036F118C3C3CD87D2112F68DA /* MASViewAttribute.m */, + 0023881B652D74804B040D7DA24C1D05 /* MASViewConstraint.h */, + 402AA4AB24F2AD705593DD3FB991387B /* MASViewConstraint.m */, + 72E288068C58BB673219CEFB1686BC93 /* NSArray+MASAdditions.h */, + 05E0636001879B23805B939764BB941A /* NSArray+MASAdditions.m */, + CBAE109E687AA08F5504796C0C8AAA94 /* NSArray+MASShorthandAdditions.h */, + 9B8D6BCD909A41774E16030943339AEB /* NSLayoutConstraint+MASDebugAdditions.h */, + D62B3C1698127F67086E6858CE18DE57 /* NSLayoutConstraint+MASDebugAdditions.m */, + 0DE0B076A96500EE0326A01598C25CD9 /* View+MASAdditions.h */, + 555E43817D41A5303D4F6306F7FA062E /* View+MASAdditions.m */, + 6AB8391ABC38E6024FB65A20D3351A17 /* View+MASShorthandAdditions.h */, + 218DE19B389EE5088E7040712F0704B3 /* ViewController+MASAdditions.h */, + 9D0303615C02A9FC06E4284A85443DC1 /* ViewController+MASAdditions.m */, + 70BBF347D3A89FFECCDCCCF0D97A1027 /* Support Files */, + ); + name = Masonry; + path = Masonry; + sourceTree = ""; + }; + 9E227C9A88916A75B5ECA7AB82A86D07 /* NSURLSession */ = { + isa = PBXGroup; + children = ( + DAEB829C6F88208F28EE3BB434586358 /* AFCompatibilityMacros.h */, + AA70955B3AF65BF0DC77A605CF3D7DED /* AFHTTPSessionManager.h */, + 54F3536A4C88BAB5768A5110E968D42E /* AFHTTPSessionManager.m */, + BF83FBC6FB90CE550B6AF3F1CB2F1277 /* AFURLSessionManager.h */, + B5FB7DF227C9ADBFB34C1E276FF37EAA /* AFURLSessionManager.m */, + ); + name = NSURLSession; + sourceTree = ""; + }; + A83804453FC7D973AEFD5E2423FC76D1 /* iOS */ = { + isa = PBXGroup; + children = ( + 9C52134DD48D89A347BF80B6D47974CD /* CFNetwork.framework */, + 223CC88B609D08C4EA1EC854A8D73AD1 /* CoreGraphics.framework */, + 7B66A6C8F7C747D007AEDA080245D186 /* CoreText.framework */, + 87C13B7502C32A61BD1DA18FC68E4DF3 /* Foundation.framework */, + 0ABED0039D2F20276FEA3153C100C8EA /* ImageIO.framework */, + BDA80F5D7B6C75DE56A43090A20E478E /* MobileCoreServices.framework */, + 2C5FBC24791EAE0728C65D6F9B9912B2 /* QuartzCore.framework */, + 47FC8BC593D3C4A9BCFAAB1AD76AC13D /* Security.framework */, + F79298FCF0E5B2FCDD163272B33DB5DE /* SystemConfiguration.framework */, + DD9F8097FDD26C1A767654BEFDB692CC /* UIKit.framework */, + ); + name = iOS; + sourceTree = ""; + }; + B46F6D1AC0DA31D8B1B98490D3896990 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 167E9F1BB5C566ED575F9AFA45711349 /* FMDB.framework */, + A83804453FC7D973AEFD5E2423FC76D1 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + B779D874E20ADC126160DE3D30A892F6 /* Support Files */ = { + isa = PBXGroup; + children = ( + 8394F96FDD5517B382EFAC03271A2F76 /* Info.plist */, + 7A1FB3C2A543ACC9B55752A4F4B00514 /* SDWebImage.modulemap */, + F8EDD5DCE505C958412B980AE9818187 /* SDWebImage.xcconfig */, + B0455BB0F27DA9FDF09E6D7A8D38B2D8 /* SDWebImage-dummy.m */, + 50E0055FB2FCA5A95F12691436BC4D68 /* SDWebImage-prefix.pch */, + 29C6CB0E4CB91AB0517A62CA7D3D4C95 /* SDWebImage-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/SDWebImage"; + sourceTree = ""; + }; + BDC55BBF9D65278672BAE81AD9040ECD /* Support Files */ = { + isa = PBXGroup; + children = ( + 9E72EDED93B07A3890590F87235248C0 /* Info.plist */, + 0934BA64BE003DD5F14A699685132128 /* UITableView+FDTemplateLayoutCell.modulemap */, + 8FFE95948B8B44700795DACEC0372ED5 /* UITableView+FDTemplateLayoutCell.xcconfig */, + C5F6388857FDFC150CCD9AEF58FD9078 /* UITableView+FDTemplateLayoutCell-dummy.m */, + 71BF153300C08FBD61FC51383839A880 /* UITableView+FDTemplateLayoutCell-prefix.pch */, + F42F1412F20D8BA676203B880AC08EE3 /* UITableView+FDTemplateLayoutCell-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/UITableView+FDTemplateLayoutCell"; + sourceTree = ""; + }; + C0BFCE03F930943A24DEE8FF325CFC73 /* IQKeyboardManager */ = { + isa = PBXGroup; + children = ( + ECEDCC8EF733B2FA85A2559FD547A300 /* IQBarButtonItem.h */, + 336B4CC378FCC45D7E43E8E330E67E1B /* IQBarButtonItem.m */, + AE26C6DD2E39EE7DC6BF9724F70BD49F /* IQKeyboardManager.h */, + 65DC0A6004D8CA989364A1123D836695 /* IQKeyboardManager.m */, + E7914083BC99732D0EB9526F21C3F14D /* IQKeyboardManagerConstants.h */, + 6FD513AB29E9316802D99A9C3C9BE9F1 /* IQKeyboardManagerConstantsInternal.h */, + 22262DD61DBB977FA2942AD0D070C595 /* IQKeyboardReturnKeyHandler.h */, + 70FB502773E45F7563AF74BD45F329B0 /* IQKeyboardReturnKeyHandler.m */, + 8CF4ACF01E4CEA3CAE293EF3F4CFB20D /* IQNSArray+Sort.h */, + 2D47457D3CE1E0737C687DB3E4E896A0 /* IQNSArray+Sort.m */, + E85D699181AA7FA0C2BD301F59B6B2B3 /* IQPreviousNextView.h */, + EF536E6DCD40B46C2DDB4A7B5CDF9949 /* IQPreviousNextView.m */, + EB20094359DE221C41846E960C38BB8B /* IQTextView.h */, + 0FF2FC65CD5737B5207D47B6520D5FC7 /* IQTextView.m */, + 5AF74F6EDDDBDE1594378798EDC8F75B /* IQTitleBarButtonItem.h */, + D8024B8DF0B73056894292AB56168798 /* IQTitleBarButtonItem.m */, + 00F8BF23D01B2525D48EF9EA2FF41BB9 /* IQToolbar.h */, + 5BC59BC77E65287BF00DC491E679E48C /* IQToolbar.m */, + 2DCB8E007F3B05111DC4769E7EA077D9 /* IQUIScrollView+Additions.h */, + F75D7F8DB268EAE736A191EE0B8F9761 /* IQUIScrollView+Additions.m */, + 4B4ACAA5FE6E4D692115FD521BCB1287 /* IQUITextFieldView+Additions.h */, + D50758F82022F3137CBA65220EEAE68E /* IQUITextFieldView+Additions.m */, + F84E6ED65E201E2FB224E9591458D599 /* IQUIView+Hierarchy.h */, + D935D6502CF164CFEAC6164421D07051 /* IQUIView+Hierarchy.m */, + C68E6D01DE9F66C2C15D29D4D81D7DD0 /* IQUIView+IQKeyboardToolbar.h */, + 87D34EBA9583ABA27F69D9C80E8042A8 /* IQUIView+IQKeyboardToolbar.m */, + B9F50AA966B1D80C51332499B80A5CFA /* IQUIViewController+Additions.h */, + E838CA14206F7C95DDF8E5A291D3845A /* IQUIViewController+Additions.m */, + E8954D6C56BC3381788DF4D08F5CC979 /* Resources */, + 6BC435B216BF0CD988087AF387048847 /* Support Files */, + ); + name = IQKeyboardManager; + path = IQKeyboardManager; + sourceTree = ""; + }; + C2F9AAA86531AE276C6CB86983E76035 /* MJRefresh */ = { + isa = PBXGroup; + children = ( + AD7E0507C28D6B5E81792E2F089A883B /* MJRefresh.h */, + 9690628DA2E17BA5835C5D826268D509 /* MJRefreshAutoFooter.h */, + 1137254611EEC2056578AEB819AA94C3 /* MJRefreshAutoFooter.m */, + 6F0DCAD0FC2007DC95B13AE9D58DB89A /* MJRefreshAutoGifFooter.h */, + 886A7A948A578AF0481B05CD6E2FAE30 /* MJRefreshAutoGifFooter.m */, + D4372399A31F995ED53980B44F7B90A0 /* MJRefreshAutoNormalFooter.h */, + 339D6D016535F8109AC998611978456D /* MJRefreshAutoNormalFooter.m */, + 5CF1B2D752E061B673D94FCB8D0E7610 /* MJRefreshAutoStateFooter.h */, + 95F6A7B21DB909CA345A47903CB4D39A /* MJRefreshAutoStateFooter.m */, + 598F5B2A218C7D65218EE2E74A1FAB90 /* MJRefreshBackFooter.h */, + D59CC779E29EBC0013D1E71D0571D5F5 /* MJRefreshBackFooter.m */, + 3C2E772FF38560DBD9204DA3173B1368 /* MJRefreshBackGifFooter.h */, + A03F70F63980CD170CD5750B6B5B2168 /* MJRefreshBackGifFooter.m */, + 72E7FF6F0D74FA6229F49C74AD38E9D2 /* MJRefreshBackNormalFooter.h */, + 43E2B344D60B305F452C5EFEB124C107 /* MJRefreshBackNormalFooter.m */, + D23E765E4467A1A7780E0DA185FD0871 /* MJRefreshBackStateFooter.h */, + E45AFFE407A50EB7A6C9911EA9DA835A /* MJRefreshBackStateFooter.m */, + DDAD4BFB56B1F3E882395A34A77631FC /* MJRefreshComponent.h */, + 359C930B2349FAEDE0BC33F8CBD77171 /* MJRefreshComponent.m */, + 37C4D86D5BC795F8CC7265B8FC971950 /* MJRefreshConst.h */, + B1A17C97B5BA3258AF5BFA6C4CB10011 /* MJRefreshConst.m */, + 0995F8AABB71D527DE51897FA8F83BA9 /* MJRefreshFooter.h */, + 4D7894D466D10E51479750206920F843 /* MJRefreshFooter.m */, + CDC9C0D785840A863C238FA9918232BF /* MJRefreshGifHeader.h */, + 865509F3D52113ED76312034BC65B7C6 /* MJRefreshGifHeader.m */, + F92F1C168C292C57C28B8CB8572DA418 /* MJRefreshHeader.h */, + 9271B8514D90DCA03D6343D0CDCE050D /* MJRefreshHeader.m */, + D1BEE5EFF3DDAAB7DF105B6EE039CC8A /* MJRefreshNormalHeader.h */, + 644412ADC146571600D9B79498A3AF6E /* MJRefreshNormalHeader.m */, + D5DA3E8C666672F7C13E27E88DD39873 /* MJRefreshStateHeader.h */, + 82AD1D80CEB504366F098535F8C51A1C /* MJRefreshStateHeader.m */, + FA61AF596C08910907F9123EEB554A9B /* NSBundle+MJRefresh.h */, + 1A77B18130425F1D9F7A7DDDB6553192 /* NSBundle+MJRefresh.m */, + D77DAA3898C22DBC2AF3A8D090AC5F67 /* UIScrollView+MJExtension.h */, + 64BCE5A336C9FAB2ED7600867B5FBA97 /* UIScrollView+MJExtension.m */, + 3C3A79FA17ABD84F81F1074C87C73E34 /* UIScrollView+MJRefresh.h */, + 2027232FAF2C4FD8C62B41D1443F10A8 /* UIScrollView+MJRefresh.m */, + F371B6BB584B1CC6193A5B5E7327AD5A /* UIView+MJExtension.h */, + 3A0319B9CF8094FC585EF6B82C4B2DA8 /* UIView+MJExtension.m */, + 40CD1D51F43C1B457F999E6EAAD05746 /* Resources */, + 2462064A6081ED68A040469CF7B0A674 /* Support Files */, + ); + name = MJRefresh; + path = MJRefresh; + sourceTree = ""; + }; + C5C82C4EF670EFD5913423A97472284F /* Support Files */ = { + isa = PBXGroup; + children = ( + BFB6E4B64CC9DCE8FD1F6CB4FA1AD798 /* Info.plist */, + 6144F56D8D5366616DE12FF84D28B206 /* MBProgressHUD.modulemap */, + 46D5F33AFF37B1C04CBDE88EF04B11A3 /* MBProgressHUD.xcconfig */, + 6C18F3E40A6F8667E93BF7E113A19F41 /* MBProgressHUD-dummy.m */, + FA6A254D84CBEA155F2904CB5F55CFEE /* MBProgressHUD-prefix.pch */, + 7C92D2200160EED2E09E78F7DC6CAE4A /* MBProgressHUD-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/MBProgressHUD"; + sourceTree = ""; + }; + C6BBCD0A12903501F64C8279700A8E78 /* SDWebImage */ = { + isa = PBXGroup; + children = ( + F4FC2287BD9B0EF9BC59CA92A5369B0F /* Core */, + B779D874E20ADC126160DE3D30A892F6 /* Support Files */, + ); + name = SDWebImage; + path = SDWebImage; + sourceTree = ""; + }; + C7CDEDA068E9C4538A614C77593EE6D0 /* Toast */ = { + isa = PBXGroup; + children = ( + B6800D584E4D1A1A19C71F4FD327A635 /* Toast.h */, + 7567613ABCFDCEBA938593A0036C32A9 /* UIView+Toast.h */, + 295F052A6A46300AE255CCA9D34FD7AF /* UIView+Toast.m */, + 81AAE6DFE3752B1E3CE9FA5345D4D8E0 /* Support Files */, + ); + name = Toast; + path = Toast; + sourceTree = ""; + }; + D43F32F7C148ED9532BFE3EC61BA319E /* NJKWebViewProgress */ = { + isa = PBXGroup; + children = ( + E87FC305A89908BBDA0EC1BA291D9691 /* Core */, + 060922B716FF31D85A27005CADCAC643 /* ProgressView */, + 021FEB9DC865A149815BAC72AF6E091A /* Support Files */, + ); + name = NJKWebViewProgress; + path = NJKWebViewProgress; + sourceTree = ""; + }; + DD333C0B31A9ADBD5F94278B63FF34BA /* JCore */ = { + isa = PBXGroup; + children = ( + 858F9FCAC1FEC22689328C603B89D06B /* Frameworks */, + ); + name = JCore; + path = JCore; + sourceTree = ""; + }; + DDBA2363A71ACA26A55AA9E9624F6937 /* JSONModel */ = { + isa = PBXGroup; + children = ( + 43189891007DC8B214462EE40E661B70 /* JSONAPI.h */, + 03E771AC05A23295139B2FB92DE413D1 /* JSONAPI.m */, + 1E49FA87D6265A153A6A377608BF76CF /* JSONHTTPClient.h */, + DBDB01D83E6928E50B7FF753E107C53A /* JSONHTTPClient.m */, + EAFD436D5E0537D470329DFCF3A97191 /* JSONKeyMapper.h */, + 99E94B95014F639BCEFE5DE77CF86A13 /* JSONKeyMapper.m */, + B2A3E53B989849FAD2CD8B551234827B /* JSONModel.h */, + 5F39613535A087B430D652C5A35BE82A /* JSONModel.m */, + 229EF78EA685C4B19FF8D820077AB1F8 /* JSONModel+networking.h */, + 967FC3D6EE75AAC4E5853A52FC40FBD1 /* JSONModel+networking.m */, + E10C0C2DBA4DAE58B1ED06F7FAE8C22E /* JSONModelClassProperty.h */, + 270737E79A641CBC04762BA9F997CE18 /* JSONModelClassProperty.m */, + 84190D645A029D929576CE3874A30E53 /* JSONModelError.h */, + C47485FA05B8E0C83A44515FDF510F25 /* JSONModelError.m */, + C2916A23C5B0F16555EFB6F4420162BF /* JSONModelLib.h */, + 098D4097B035C28D4D42FD43FBEF8C63 /* JSONValueTransformer.h */, + 1B2D027604F0FD4DDC858BCB8413D135 /* JSONValueTransformer.m */, + 01E8C2568D6E2F08B419418E6D7ACBAE /* Support Files */, + ); + name = JSONModel; + path = JSONModel; + sourceTree = ""; + }; + DECCF16B74AFC5008D41EAED7FCDA439 /* standard */ = { + isa = PBXGroup; + children = ( + E26447099EDFE24E2B1AF730E232EB27 /* FMDatabase.h */, + 69C00A3ED643BFA7CBFB31DC4CB6E601 /* FMDatabase.m */, + 94752DBCE44CA942E27A896C7CB73B8D /* FMDatabaseAdditions.h */, + 1E7820BA9423CD0C1D2DAC362014ED4B /* FMDatabaseAdditions.m */, + C7949A099C444A21B8BF2123F5474A11 /* FMDatabasePool.h */, + 491A04582FFB79FD874AFB04764A6F5C /* FMDatabasePool.m */, + 95A1ADBB90DEADD3CC0BB6D927F30DBA /* FMDatabaseQueue.h */, + 9CB6460D14EA9B327CE96B0450FA717B /* FMDatabaseQueue.m */, + 46C1C2B2A4BA6017298CF244B5B46838 /* FMDB.h */, + 60DE6EFB52862BBD769E650DE1A53D87 /* FMResultSet.h */, + 918438D2584B201AE3B75ECE63C18CD5 /* FMResultSet.m */, + ); + name = standard; + sourceTree = ""; + }; + E87FC305A89908BBDA0EC1BA291D9691 /* Core */ = { + isa = PBXGroup; + children = ( + EB5A22B7F55187B0C899BDE644913E34 /* NJKWebViewProgress.h */, + B4DF3C7BB807E1348544AA2900CC9BCC /* NJKWebViewProgress.m */, + ); + name = Core; + sourceTree = ""; + }; + E8954D6C56BC3381788DF4D08F5CC979 /* Resources */ = { + isa = PBXGroup; + children = ( + FFFC1D06E09FCB725E5075FB470389CA /* IQKeyboardManager.bundle */, + ); + name = Resources; + sourceTree = ""; + }; + E9BE045C83FF29AC7E11071DF389EEBA /* FMDB */ = { + isa = PBXGroup; + children = ( + DECCF16B74AFC5008D41EAED7FCDA439 /* standard */, + F4AEBA80A6922AC8398C70B537E6009C /* Support Files */, + ); + name = FMDB; + path = FMDB; + sourceTree = ""; + }; + EEF7773B173A78B2CE1CF7937918485B /* WechatOpenSDK */ = { + isa = PBXGroup; + children = ( + F9CB6479D82C197DA7B4EE0F7B6817CA /* WechatAuthSDK.h */, + AF1448946B3216D28ED8EB8AD4031D91 /* WXApi.h */, + CB3C6DE0D6C1AC3A7591955C5B69B39A /* WXApiObject.h */, + FB8EB1859B5795978895C32D0E3A4951 /* Frameworks */, + ); + name = WechatOpenSDK; + path = WechatOpenSDK; + sourceTree = ""; + }; + F139BBCD98A0E7BAE3ACB11DD38CE8CF /* Reachability */ = { + isa = PBXGroup; + children = ( + 125D8E7B25DE48B829EF26B5A344B3D0 /* AFNetworkReachabilityManager.h */, + F5F9245FC6E3E879D3070CAC3CE9039E /* AFNetworkReachabilityManager.m */, + ); + name = Reachability; + sourceTree = ""; + }; + F440F326A67EDD4710F38EFA8047C7B2 /* SocketRocket */ = { + isa = PBXGroup; + children = ( + F39CD7FEBA3936962AFCB24609CFA605 /* SocketRocket.h */, + 80EBC7AC78ACE04DDC3E429CC36690EB /* SRWebSocket.h */, + F2D330C281F30235A5D8E2C8D8CC7445 /* SRWebSocket.m */, + 05EBD8BDE003587FA6FCE72925D5CE5D /* Support Files */, + ); + name = SocketRocket; + path = SocketRocket; + sourceTree = ""; + }; + F4AEBA80A6922AC8398C70B537E6009C /* Support Files */ = { + isa = PBXGroup; + children = ( + 8226479816A8DD0C45BACA4F04014C2C /* FMDB.modulemap */, + 053BB0597C8AADB4758AD482E0A510B0 /* FMDB.xcconfig */, + C79F418E3B67CEA0D2E4853E93EB61D6 /* FMDB-dummy.m */, + 43BCA2F852A7750CEC56CEC17939F15A /* FMDB-prefix.pch */, + F64387C5F8EF527B7D20778BEE103274 /* FMDB-umbrella.h */, + D8C17DF1169974E2F089CBF839A7E422 /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/FMDB"; + sourceTree = ""; + }; + F4FC2287BD9B0EF9BC59CA92A5369B0F /* Core */ = { + isa = PBXGroup; + children = ( + C1023377CD29F52DBD86B670EC330990 /* NSButton+WebCache.h */, + BE6A57C1E6EE6E72829EF1A0239DD712 /* NSButton+WebCache.m */, + DE6B846782E8125465DD1F586A583755 /* NSData+ImageContentType.h */, + 4015BC1E8D9C87DAAE2DA773CDA1439F /* NSData+ImageContentType.m */, + A1984BDF5C4B9F316463CFAE01F131B6 /* NSImage+WebCache.h */, + B3746F3DB8A767202DDD4F8D8A9E522E /* NSImage+WebCache.m */, + 6631EE01B7EC6B5EF820B3874307CCE0 /* SDAnimatedImageRep.h */, + 771FAC488702BC45D9B3E1C95287F985 /* SDAnimatedImageRep.m */, + 8CDF9E3C2D2416AC7550ED950AB0CC88 /* SDImageCache.h */, + 77F995714B12945BE98FB29DB7AABBA0 /* SDImageCache.m */, + 3B60C061E6AF24D5ABF4219ABB4D7F9C /* SDImageCacheConfig.h */, + 6E3BCEC765BAFBF7315B2835E33E8AC4 /* SDImageCacheConfig.m */, + 4BFD3AE7B418D1AB696243F283ECC7F3 /* SDWebImageCoder.h */, + 7475210B8C97452DB2D28FF46AD4B78D /* SDWebImageCoder.m */, + 1F3542CD47C057D6C551C30C3B46D2DB /* SDWebImageCoderHelper.h */, + 54BA54731B31CD6D22D2D59BBE0D5608 /* SDWebImageCoderHelper.m */, + 997A2F2BD5D2ACC81541F8F909D4E847 /* SDWebImageCodersManager.h */, + 7714D1833FFBB408B18F2747E65E5790 /* SDWebImageCodersManager.m */, + E299BD8696B2E375B3B2FB48F530F119 /* SDWebImageCompat.h */, + 33F7C39FC1E079D25B57C66BE636FC39 /* SDWebImageCompat.m */, + F63B516844D3BA3C6CC53B029BFB6C1D /* SDWebImageDownloader.h */, + F11F0CB1B9CA018793DBBE97E44883F4 /* SDWebImageDownloader.m */, + 8D0CC50CC4E4ABC5F7473302F3F1B511 /* SDWebImageDownloaderOperation.h */, + 671B1C68838C43D897AF46AADD606C4A /* SDWebImageDownloaderOperation.m */, + 7A2DE5C636CB7384C70AE55DEBC248F7 /* SDWebImageFrame.h */, + 350E7464A1D787085E3C8AB20B8D3699 /* SDWebImageFrame.m */, + F60AD73AF21127AF807A87155E176BB2 /* SDWebImageGIFCoder.h */, + 9BDE845BAEED6040E590CA9903B14998 /* SDWebImageGIFCoder.m */, + 957C4EAC3550D522CFC086D33020AF15 /* SDWebImageImageIOCoder.h */, + A7D9C6AE37D287719040FA3D994C8059 /* SDWebImageImageIOCoder.m */, + 4A2AF264E571B9997B0965D66283EAA6 /* SDWebImageManager.h */, + EF2886493D8197A42561F3F3282F8612 /* SDWebImageManager.m */, + B3128EC48EC5433341A281DE78719B72 /* SDWebImageOperation.h */, + FFFC1118336CE5A0F2379778BD1CBCFE /* SDWebImagePrefetcher.h */, + 9F3FD02A35657C32B7608DD9E484CD49 /* SDWebImagePrefetcher.m */, + F66E969B978843AD18F5745FC07B3C9B /* SDWebImageTransition.h */, + EF647DB47CA8072604B32A11D318121C /* SDWebImageTransition.m */, + D6A5BFBE51D80535DEA9FCDD8E232F54 /* UIButton+WebCache.h */, + A06DE5502BE4BF7357DB2DF5A8BA5207 /* UIButton+WebCache.m */, + 4FA220EAF4B2366FE3383A5AF8AD3D27 /* UIImage+ForceDecode.h */, + C0E318B9FCDDCC5AA2EF7612D8B92B1C /* UIImage+ForceDecode.m */, + 0A3B12D0C0FC24CB5EEC1457E32FC6BF /* UIImage+GIF.h */, + 04AF8FBCCAA5C10FBF5C8D678095B349 /* UIImage+GIF.m */, + 7FD3A5585C7A6F8C8EBD39C59F4BCF02 /* UIImage+MultiFormat.h */, + E9B9FF3E9F69E2D04EB243D2A2B0D44A /* UIImage+MultiFormat.m */, + 5569AA726D3D85E6DF8895BAAE8DEBDF /* UIImageView+HighlightedWebCache.h */, + 86B4DD8A5BE1003157681F47B9A06D90 /* UIImageView+HighlightedWebCache.m */, + 5A802226FA114075D3D6409ACCFB1EEA /* UIImageView+WebCache.h */, + 454A5B629D064F61E8CD89588ACADB13 /* UIImageView+WebCache.m */, + 67B406F183DB1F705B966496FF984505 /* UIView+WebCache.h */, + E9CC4C0DA475DA5B31053CF995EC62C0 /* UIView+WebCache.m */, + 053476A95CBB33D3F007559250E2E712 /* UIView+WebCacheOperation.h */, + 49FC022BC0DDF2BFCA610030FC39F8BF /* UIView+WebCacheOperation.m */, + ); + name = Core; + sourceTree = ""; + }; + FB8EB1859B5795978895C32D0E3A4951 /* Frameworks */ = { + isa = PBXGroup; + children = ( + EB57F96C679159F822541623D7479456 /* libWeChatSDK.a */, + ); + name = Frameworks; + sourceTree = ""; + }; + FBB949B909D1BC7355CE4C96A365A607 /* Pods-GIGA */ = { + isa = PBXGroup; + children = ( + 4A26F8EC0D0C0834C08E37EF1C0D560D /* Info.plist */, + 4BB8C4AE22CA2904E7813EFEAFE8A067 /* Pods-GIGA.modulemap */, + 8BBB7F3A03E7F2608FE52B0194635075 /* Pods-GIGA-acknowledgements.markdown */, + AB2DF74840B542C3AD232BD2BD39EDAC /* Pods-GIGA-acknowledgements.plist */, + FD113136C3BE7E4822B80A29F3DC5E42 /* Pods-GIGA-dummy.m */, + 9B08C8E485946B27165B1EE380D12B99 /* Pods-GIGA-frameworks.sh */, + F8242C88C595688B579B2B397424ADC8 /* Pods-GIGA-resources.sh */, + 4333DE13F7B28D62D7251611E26C7D1F /* Pods-GIGA-umbrella.h */, + 218B6E61733A5B9138CB4D0815133580 /* Pods-GIGA.debug.xcconfig */, + 9574A12E8279712E0544674068BEC2E1 /* Pods-GIGA.release.xcconfig */, + ); + name = "Pods-GIGA"; + path = "Target Support Files/Pods-GIGA"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 03AB14DB0235B494910320324F3BF2C2 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 0648973667FB537BDC3ABFA9F3AD2ED8 /* IQBarButtonItem.h in Headers */, + 85F02B2E2F922F439A12C7CBB077E8DE /* IQKeyboardManager-umbrella.h in Headers */, + 14479278EA90F38247811468ADD8EBB7 /* IQKeyboardManager.h in Headers */, + C49ED0BA3BE26C50F202C5ED5FB85573 /* IQKeyboardManagerConstants.h in Headers */, + B21C3C93DAA23B1C331B9326991CDCFC /* IQKeyboardManagerConstantsInternal.h in Headers */, + 3619E77A8EC11571EE9F32921DAC0C89 /* IQKeyboardReturnKeyHandler.h in Headers */, + 688E0882DFC8CABA02390F43178CB33F /* IQNSArray+Sort.h in Headers */, + CF4EB3350726A86BCCDF5F363C5FCE72 /* IQPreviousNextView.h in Headers */, + AAC6DB8270C474C50F5D71DE9BC73382 /* IQTextView.h in Headers */, + 99249B44D65716B5CCA0BFFD5F83062C /* IQTitleBarButtonItem.h in Headers */, + 7CF3668C8E30DA3CAB92C9C6A8B88B8F /* IQToolbar.h in Headers */, + 06FF2586AE76FBBCBF8171F98255D8CB /* IQUIScrollView+Additions.h in Headers */, + B05BDA89A18DA866355AD804B694F851 /* IQUITextFieldView+Additions.h in Headers */, + 63F5BA839B931DB6605554B6D4369A0C /* IQUIView+Hierarchy.h in Headers */, + 639A86F8EDAF569092C61103FFAEA21D /* IQUIView+IQKeyboardToolbar.h in Headers */, + 13D87E1D99CFD98771E8066E6FF832CD /* IQUIViewController+Additions.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 1D0B0A5525CB3F57F2D64B587D880D88 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + D820DE54D6E9E5C85E0F9BF8A399E5EF /* MJRefresh-umbrella.h in Headers */, + 35D685CF7C6F73A65AD3DD99674CA78F /* MJRefresh.h in Headers */, + D9F2BA4D713DAC2A85CB4A453240EA3E /* MJRefreshAutoFooter.h in Headers */, + D0E7D5B865722A25EC7D91B0FAD8A6CD /* MJRefreshAutoGifFooter.h in Headers */, + A5382D3EA98D2EB1AD9EDA5F2138F00D /* MJRefreshAutoNormalFooter.h in Headers */, + BA0711638621C2A47AABFF9E03546893 /* MJRefreshAutoStateFooter.h in Headers */, + B02D91E02099D3C6A2F988C766032176 /* MJRefreshBackFooter.h in Headers */, + 2CEA12D52F3F7AC0669C99A157E19F62 /* MJRefreshBackGifFooter.h in Headers */, + 17F033046E658F3BFD0011DCB768CF54 /* MJRefreshBackNormalFooter.h in Headers */, + 1ED505CC385A149F4DF8F4B94BA4FC0B /* MJRefreshBackStateFooter.h in Headers */, + A72D242BEF61E27D6C29092DF4666A4A /* MJRefreshComponent.h in Headers */, + EBEB72F80DCD10DEB82BF5F856D467FD /* MJRefreshConst.h in Headers */, + AA4959949A290D4B8BE1E31A890D0C80 /* MJRefreshFooter.h in Headers */, + 6A0B1A0FA7A75C861B9D401D0E8CC95E /* MJRefreshGifHeader.h in Headers */, + 71F6D96E3AEAA07389F37E2C4B63C4F6 /* MJRefreshHeader.h in Headers */, + 7942D242D079A5710A72B659A54D7E26 /* MJRefreshNormalHeader.h in Headers */, + BDB33C3708110C6D755175D1F0A2A70B /* MJRefreshStateHeader.h in Headers */, + 58E6E68D10EF3D64522BD267CC1761A6 /* NSBundle+MJRefresh.h in Headers */, + D02DEBC241C24DEEFDA13C355197A2FB /* UIScrollView+MJExtension.h in Headers */, + 0EFB524EFDF2F8712A2F5067817A672E /* UIScrollView+MJRefresh.h in Headers */, + DE17E4C2C6EADE5D2D531268B1695405 /* UIView+MJExtension.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3D2A080C5CD4ED4520C6AEFA1D6BA26F /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + F11FAB91014130EE233A3429439D38D7 /* FMDatabase.h in Headers */, + A548833BE5FAD40830428F36E77D0F52 /* FMDatabaseAdditions.h in Headers */, + 9B8D84996694C541CD3434386E0A081A /* FMDatabasePool.h in Headers */, + 22554065FA07F1BFE5308A685394CB12 /* FMDatabaseQueue.h in Headers */, + 96E70B43FC04BC99AED1BBD4FB1D7581 /* FMDB-umbrella.h in Headers */, + CCB74062CE0F4B8E5B7483599BC398DA /* FMDB.h in Headers */, + 3E43906B70EB01C06F3AE17008B853B9 /* FMResultSet.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 437257DE3C6D9F839BDC24CB20C0A24B /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 91D993FDEE2D0C2D3B4047D9E8BEE9BA /* UITableView+FDIndexPathHeightCache.h in Headers */, + 4BA2F37913AFB59DC45A84CA29AAB2F8 /* UITableView+FDKeyedHeightCache.h in Headers */, + D88C9F75BDFC1CE7034687208D830D81 /* UITableView+FDTemplateLayoutCell-umbrella.h in Headers */, + C5BCB61A9B530249DD0CEC33C6E07EB3 /* UITableView+FDTemplateLayoutCell.h in Headers */, + CB8230F8171A44F80B11C0BE0E8420AC /* UITableView+FDTemplateLayoutCellDebug.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 437E0B8BDA100834FD20877E5FCDC59D /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 4AA21F40697CB42D7D219ACEDE4FBFCF /* AFAutoPurgingImageCache.h in Headers */, + 9898B13B5771AC304E096319E72F8098 /* AFCompatibilityMacros.h in Headers */, + B086C8017A694E281B3F30DCCE8FA588 /* AFHTTPSessionManager.h in Headers */, + F54879EEAE223E90AC9674197E6B1ADE /* AFImageDownloader.h in Headers */, + 9AC1064802A4D107353A87F2B4A963B0 /* AFNetworkActivityIndicatorManager.h in Headers */, + 5BFE1CC79F693B6218B419AE50B2070E /* AFNetworking-umbrella.h in Headers */, + 3DDB894364CEC991E61B04E9036D6D54 /* AFNetworking.h in Headers */, + 8D9636C74777C684BDF312EE66F8A585 /* AFNetworkReachabilityManager.h in Headers */, + 04F3BBE71B24770E40CC66A993AD85D1 /* AFSecurityPolicy.h in Headers */, + F26CD9A1DF452688BF3C98BBA9090F92 /* AFURLRequestSerialization.h in Headers */, + CA0D37AE5433954573D3E37771CDDBFA /* AFURLResponseSerialization.h in Headers */, + C12BAA822391D670C53FF0C2299654AD /* AFURLSessionManager.h in Headers */, + AD868043328B2125E27A5DC14D11958F /* UIActivityIndicatorView+AFNetworking.h in Headers */, + 0ACBBA158F4635FAE16AB5456ABADCA4 /* UIButton+AFNetworking.h in Headers */, + F1199E40BF416FC1ACA2DDCD7B2E23A1 /* UIImage+AFNetworking.h in Headers */, + A5B069CA1170E03891AC5648DE5CF87D /* UIImageView+AFNetworking.h in Headers */, + ADD011E9ABBD96D70AAA32A4B9ACBD02 /* UIKit+AFNetworking.h in Headers */, + 63BA6FBA10304F4828DE97C0FA63ED9D /* UIProgressView+AFNetworking.h in Headers */, + 86EA527BA1862E06A8E19E0960C66E7E /* UIRefreshControl+AFNetworking.h in Headers */, + 15F6265FCE0955CDB4967F7306407D67 /* UIWebView+AFNetworking.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4BA32C028BF2AB9BF5D03EAACD01702B /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 95A76E599F3448FD0E5C736D98354DA8 /* YTKKeyValueStore-umbrella.h in Headers */, + 65EC43DAB5ACAAEE8F1CE61529A09102 /* YTKKeyValueStore.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5C04B9F89558E45F265E0006FBC995EE /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + ECD71FC38CCAFD1ACC2E546FAAEC0D60 /* SocketRocket-umbrella.h in Headers */, + 106D6F89336E06DBE4E973818BD887AA /* SocketRocket.h in Headers */, + 16831E5AE64E97E9BD8FA96E93C8DF19 /* SRWebSocket.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BBF7227F5BD0440E9DF598DF26EC3891 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 4EB17293737C717D12298CFFE6A67514 /* JSONAPI.h in Headers */, + 7F66E5779B29E0BC17D565DAD7CDEC1B /* JSONHTTPClient.h in Headers */, + 58388F773008AF671CE67FE1C902E6CB /* JSONKeyMapper.h in Headers */, + E3C47E114E924D2F331F9A3F122AEE5C /* JSONModel+networking.h in Headers */, + 36E344E5B627E04368ECC96338E17F26 /* JSONModel-umbrella.h in Headers */, + 37FD169854FF4B397051998D611F152A /* JSONModel.h in Headers */, + 009C79BE88C2F4C986644CD3E0B088C2 /* JSONModelClassProperty.h in Headers */, + 2AFB0AFA2138181E162CD00669D87FE3 /* JSONModelError.h in Headers */, + 6F5906B58272E07A0850248867562581 /* JSONModelLib.h in Headers */, + DFA0B0C7EC02135911CACDAFD38BE715 /* JSONValueTransformer.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CDCC81C5A7B82E18A00A9F9EC5474BDC /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 0DCFD83A6149FC0514890A5ED67047B5 /* NJKWebViewProgress-umbrella.h in Headers */, + F2EFDC17C03449A9A15E26464453103F /* NJKWebViewProgress.h in Headers */, + 7AE9484F09D29428653109D73D4FC488 /* NJKWebViewProgressView.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D015B3F3E2F85391AA3B395B5B1ADCE5 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + B646C96E2D7DF54445B3719F800D79E9 /* MBProgressHUD-umbrella.h in Headers */, + D206EDC84CE44D5DC711ADD087BC4B17 /* MBProgressHUD.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + DD5EB35A6633261597F3AA694BC6C2A4 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 3ACB80ACD4B743F9EAD47339F10594A0 /* Toast-umbrella.h in Headers */, + AF5A5DF8096192FC74E02A3408AADC21 /* Toast.h in Headers */, + 4CC5EC830A89C3CB7F53C52CDF13CF81 /* UIView+Toast.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + DEBE5273066D0E9ECC684BD423857AA5 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + AB2CEAF630532A05339889D5663E1C08 /* TTTAttributedLabel-umbrella.h in Headers */, + 4B8BFD0889A2513D7BAB9D582C077810 /* TTTAttributedLabel.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E5AB7E4C7C9142C52B005A940AFAC12E /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + EBA34A3FBF57D5834C2EC4722210066A /* Pods-GIGA-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + ED8FF911FDD33A3EF0E4C647B44A922E /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + D1641F0A353E02D971A2E6C004D4D996 /* LKDB+Mapping.h in Headers */, + AC5F946DEC898FE1FE7BA74426FE6A8D /* LKDBHelper-umbrella.h in Headers */, + 0FDFFDFAF40F6A37B8911FA7C57428CB /* LKDBHelper.h in Headers */, + 6FF8739ADFFE8465389AF3F0603E6F83 /* LKDBUtils.h in Headers */, + 0AF48B0ADAD7D4F5A2CB22075A3F5FEC /* NSObject+LKDBHelper.h in Headers */, + 4985E014269593640635A8DBD75DA450 /* NSObject+LKModel.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F3E9930C736C01D12F5733EFD1F0A948 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 8CD45B754192DE834B642975E85257AB /* MASCompositeConstraint.h in Headers */, + 4D4F2050654580FE1F1D5F4F82CEDDB8 /* MASConstraint+Private.h in Headers */, + C8DF22EAFFC2F81B0426E2165AC93E44 /* MASConstraint.h in Headers */, + 88DE7BAB1F4999A5F4B617F44E5FD1D3 /* MASConstraintMaker.h in Headers */, + 7C17BEA6034027310D1D205DB2008CA5 /* MASLayoutConstraint.h in Headers */, + 457ACF9150DCF9AF445B129CC9678FB6 /* Masonry-umbrella.h in Headers */, + CC8F9B4A1AC4E276EA8AA4C6F2BF3CD4 /* Masonry.h in Headers */, + 04A7D6AADAB213CE7D26F8EAD2F87536 /* MASUtilities.h in Headers */, + 636BBA734C1A17A734761D674FAE8800 /* MASViewAttribute.h in Headers */, + 091D17D5D8F832D28546A72B788CF0AE /* MASViewConstraint.h in Headers */, + C0A16E00B4BC2D88A7833D5DAED62942 /* NSArray+MASAdditions.h in Headers */, + D8B1525CB3DFCBD8E5032680530413D9 /* NSArray+MASShorthandAdditions.h in Headers */, + 0FDB2B4F75591851F0F119EAE70B3F63 /* NSLayoutConstraint+MASDebugAdditions.h in Headers */, + 068EF598E554EC57038ACFB89CC2C47A /* View+MASAdditions.h in Headers */, + B44383A3FA435C1E986942C817339302 /* View+MASShorthandAdditions.h in Headers */, + 2854C9B1086758BD2B6681206B6759B4 /* ViewController+MASAdditions.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FEDF3C3884236EB4E61F6B9D4D2048BA /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 93BF58C19C5E6A78EDAA38855DDDE348 /* NSButton+WebCache.h in Headers */, + 68168E99337712B83A79810B55602D01 /* NSData+ImageContentType.h in Headers */, + 2D170EDC2BE147629AF7D661BCDBD2AF /* NSImage+WebCache.h in Headers */, + 538E922BA03E8B2C147BF047ED195DF4 /* SDAnimatedImageRep.h in Headers */, + 5423F7BB578AF69EEFD339909261F01E /* SDImageCache.h in Headers */, + E82991D928C3CFEDC23555B3F2CB017D /* SDImageCacheConfig.h in Headers */, + 48EEC19D6C3DCAD43836914B8D0F1EB9 /* SDWebImage-umbrella.h in Headers */, + 5E0CA8102FFB7E6CB9B04DF6DEC83AEE /* SDWebImageCoder.h in Headers */, + 43E74DBE8C8D7F79A45B9344D2D2D1BD /* SDWebImageCoderHelper.h in Headers */, + 0B53B4188A47FECDD7E1798EAB8B6B9D /* SDWebImageCodersManager.h in Headers */, + 39530A48FC40F64E8B08B45AD5555D0A /* SDWebImageCompat.h in Headers */, + A9A91BA2015E3033BF4DAD29264D03F0 /* SDWebImageDownloader.h in Headers */, + E23258A837180BD5EBE5217D1D69909B /* SDWebImageDownloaderOperation.h in Headers */, + 182956A69F1B4571D23008AD8C160B3E /* SDWebImageFrame.h in Headers */, + 76C5CEA598337CC1FC825899FF1CDAD9 /* SDWebImageGIFCoder.h in Headers */, + B215AD383364D4C829F4EC9803568809 /* SDWebImageImageIOCoder.h in Headers */, + B1C1164914E351C022A5C6637E8599BF /* SDWebImageManager.h in Headers */, + E008B05370128F8FD8B4B627C8C4D4F4 /* SDWebImageOperation.h in Headers */, + D16764F0C1C13D1FE859B4EA2B33E474 /* SDWebImagePrefetcher.h in Headers */, + 53514C9A8CBD604E5DE2ABFFB322C3AE /* SDWebImageTransition.h in Headers */, + F3FBCDC1B575D58AD9F78DA4AF687438 /* UIButton+WebCache.h in Headers */, + 7E653E1D9DF593D82DEA20D2340F2C1E /* UIImage+ForceDecode.h in Headers */, + 0ABD694709F6B146E908A254CDF1A968 /* UIImage+GIF.h in Headers */, + 38A1AC3A26C93B53FCD959E136990990 /* UIImage+MultiFormat.h in Headers */, + 1624AFE5A1732E1D58AB884329EB4C94 /* UIImageView+HighlightedWebCache.h in Headers */, + 6115C3ED460710318D33BBB7375B07A9 /* UIImageView+WebCache.h in Headers */, + 0F3CEE11E6552204415ED069B86372BC /* UIView+WebCache.h in Headers */, + 7F37E7BCFFC785854FD19F23B89C39AE /* UIView+WebCacheOperation.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 251BAD17812F7EBF6532EACF66F941C3 /* FMDB */ = { + isa = PBXNativeTarget; + buildConfigurationList = 5B0566FF0CE681AC326D316CEC45A8CF /* Build configuration list for PBXNativeTarget "FMDB" */; + buildPhases = ( + 8FE0D4B503A94502F3431DC0DCB58040 /* Sources */, + EEFB61A65EB8DA6653B544822EB9CE44 /* Frameworks */, + 3D2A080C5CD4ED4520C6AEFA1D6BA26F /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = FMDB; + productName = FMDB; + productReference = 8E5DA37AC55ADD979E448DB4CCE99D62 /* FMDB.framework */; + productType = "com.apple.product-type.framework"; + }; + 37E3F76B9AB64BE59F26C42C0DB02B51 /* SocketRocket */ = { + isa = PBXNativeTarget; + buildConfigurationList = CEE1C7C5EB2923B3BFB904DF6E10ABAE /* Build configuration list for PBXNativeTarget "SocketRocket" */; + buildPhases = ( + 9FF620AC95D419DCDC9860DC4E44F14E /* Sources */, + 89CB805BF93CBFFF9178240B3DA62840 /* Frameworks */, + 5C04B9F89558E45F265E0006FBC995EE /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SocketRocket; + productName = SocketRocket; + productReference = 9E43D4748ACBDE3E7E8E94CCE6225EFE /* SocketRocket.framework */; + productType = "com.apple.product-type.framework"; + }; + 5CC70589280C1B49544760FFD838E2A4 /* TTTAttributedLabel */ = { + isa = PBXNativeTarget; + buildConfigurationList = 4DC283BD16CE8D51C0C47A03AE2B9931 /* Build configuration list for PBXNativeTarget "TTTAttributedLabel" */; + buildPhases = ( + 9CAE333B428F0263F4FD761FC1E2B4D0 /* Sources */, + F8B6CBF4BE519D592974034E0A5D06DA /* Frameworks */, + DEBE5273066D0E9ECC684BD423857AA5 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = TTTAttributedLabel; + productName = TTTAttributedLabel; + productReference = A57F7F0A6AB5550D6C39E86241A2C3B4 /* TTTAttributedLabel.framework */; + productType = "com.apple.product-type.framework"; + }; + 6B1714E816AE794962516E2ECBB40A5A /* MBProgressHUD */ = { + isa = PBXNativeTarget; + buildConfigurationList = 28A1BDB3CE3F2F1CB0931DFEEDBA7936 /* Build configuration list for PBXNativeTarget "MBProgressHUD" */; + buildPhases = ( + 5D9F4A386169F298C8544D099324BB28 /* Sources */, + 9FE6CEF1763E05FB90653801CE3E2B5B /* Frameworks */, + D015B3F3E2F85391AA3B395B5B1ADCE5 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = MBProgressHUD; + productName = MBProgressHUD; + productReference = 4738089B8361F3D3AB1BCED704498464 /* MBProgressHUD.framework */; + productType = "com.apple.product-type.framework"; + }; + 826EFF975442065A54A0B2D3103EE6A4 /* NJKWebViewProgress */ = { + isa = PBXNativeTarget; + buildConfigurationList = 5C5BD8C49D5108DF93608FA1EDC5B5EF /* Build configuration list for PBXNativeTarget "NJKWebViewProgress" */; + buildPhases = ( + 333271689444C03071D8092853B02EDD /* Sources */, + 59DA24E1BFBF4DF2381ED2E0EE6964A0 /* Frameworks */, + CDCC81C5A7B82E18A00A9F9EC5474BDC /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = NJKWebViewProgress; + productName = NJKWebViewProgress; + productReference = 4AFDFD2D9A90BF4BB9DD861020532888 /* NJKWebViewProgress.framework */; + productType = "com.apple.product-type.framework"; + }; + 95BEAA384CB15B77BDF7ACD211017BBF /* UITableView+FDTemplateLayoutCell */ = { + isa = PBXNativeTarget; + buildConfigurationList = 529362CDA42ABA356BEDB1C8DE1878E5 /* Build configuration list for PBXNativeTarget "UITableView+FDTemplateLayoutCell" */; + buildPhases = ( + DC6EE35E0B75550D805CBE30078E9EC7 /* Sources */, + CCB6C94A3B7F7AF612CA6128178B688A /* Frameworks */, + 437257DE3C6D9F839BDC24CB20C0A24B /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "UITableView+FDTemplateLayoutCell"; + productName = "UITableView+FDTemplateLayoutCell"; + productReference = B02F00E2B5DA269DDA1D546D77FD45BA /* UITableView_FDTemplateLayoutCell.framework */; + productType = "com.apple.product-type.framework"; + }; + 9F61A37FCA87A09637399EBB3DE84342 /* Pods-GIGA */ = { + isa = PBXNativeTarget; + buildConfigurationList = 0012A7CF52D71D63FC55A4D5A6AC4075 /* Build configuration list for PBXNativeTarget "Pods-GIGA" */; + buildPhases = ( + 27F6CE0C00F35EB887C1A6E900A26E62 /* Sources */, + B8E0CDE9D6B78B63BC6132265D5D95E0 /* Frameworks */, + E5AB7E4C7C9142C52B005A940AFAC12E /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 52C881058B7DC72C4AF030FA8F99288E /* PBXTargetDependency */, + C06C0264289BBBE19528702557CC8FC1 /* PBXTargetDependency */, + 471DD9226DF1018D260537872E4FBDAE /* PBXTargetDependency */, + 57816986BEF7436716C5170BA0F6A708 /* PBXTargetDependency */, + 23C83C77DA981D934463D2CBA4E59819 /* PBXTargetDependency */, + 44A9CFDCB06EA5269E4C950DAD8ED972 /* PBXTargetDependency */, + 71A30A7A2718C8461D0FF1BE77A2D699 /* PBXTargetDependency */, + BCD3529C382009CD52BA7FE04C413E02 /* PBXTargetDependency */, + AB64071AA32D5C7F56262E76491764BE /* PBXTargetDependency */, + 47FBEED3E9AA3E4E9EC7667FF3B4777E /* PBXTargetDependency */, + 15B63977E3E79F3D3D3A1CC2E997A2AD /* PBXTargetDependency */, + 99A84B27A5415B21021711DF73056760 /* PBXTargetDependency */, + 43C4C6615D3225CE5887349E1E308532 /* PBXTargetDependency */, + 758008F7D1531C273A6CDA6ABA85E20B /* PBXTargetDependency */, + 52EFABC352FCC5BC3BEE5E4B4735B33D /* PBXTargetDependency */, + ); + name = "Pods-GIGA"; + productName = "Pods-GIGA"; + productReference = 1DB7026C750DB559A03CDBE2742DC1B3 /* Pods_GIGA.framework */; + productType = "com.apple.product-type.framework"; + }; + BC65E926DB84B0281E512834BE47D80A /* SDWebImage */ = { + isa = PBXNativeTarget; + buildConfigurationList = B54043E8C4A49656CF64035A2F5B237A /* Build configuration list for PBXNativeTarget "SDWebImage" */; + buildPhases = ( + AD6EFB2F02B9791F95156117142A99BE /* Sources */, + F43DF7F5860C5353DC417595794C69DB /* Frameworks */, + FEDF3C3884236EB4E61F6B9D4D2048BA /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SDWebImage; + productName = SDWebImage; + productReference = E4811330CBE4D8F15CD07A0E6B28196A /* SDWebImage.framework */; + productType = "com.apple.product-type.framework"; + }; + CCA9C33B127D6C859A3F8AFBEFCBABF0 /* LKDBHelper */ = { + isa = PBXNativeTarget; + buildConfigurationList = 730557350F2D643032C64C252A33646B /* Build configuration list for PBXNativeTarget "LKDBHelper" */; + buildPhases = ( + 28931639A1BF9251AAB8A696279FC52C /* Sources */, + 77A4F3ABB18A1CBD901A6D7F4564A99A /* Frameworks */, + ED8FF911FDD33A3EF0E4C647B44A922E /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + C5949C3702F8D473B24B99AF83A168EA /* PBXTargetDependency */, + ); + name = LKDBHelper; + productName = LKDBHelper; + productReference = 961B9982B287A938D23CE983804F2FC5 /* LKDBHelper.framework */; + productType = "com.apple.product-type.framework"; + }; + CF1D6BC4AC3FC60A30FB00811CF01999 /* YTKKeyValueStore */ = { + isa = PBXNativeTarget; + buildConfigurationList = 9CCFEAF1989FAB852D4659E698888A02 /* Build configuration list for PBXNativeTarget "YTKKeyValueStore" */; + buildPhases = ( + CCF8135D6E7EC6FF96D1888CC3999B4D /* Sources */, + 2F6AD2793DCCAC8655F20980C31F5B6E /* Frameworks */, + 4BA32C028BF2AB9BF5D03EAACD01702B /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + F615009BA540330ABAB8C97015D7E9D7 /* PBXTargetDependency */, + ); + name = YTKKeyValueStore; + productName = YTKKeyValueStore; + productReference = B72C980E30572DC8C26C148404219FE9 /* YTKKeyValueStore.framework */; + productType = "com.apple.product-type.framework"; + }; + D52144DE9D7255DE912490FF5A806573 /* Masonry */ = { + isa = PBXNativeTarget; + buildConfigurationList = 02D024184BD368B565F3B6257DF3C605 /* Build configuration list for PBXNativeTarget "Masonry" */; + buildPhases = ( + 00A62ED60FF8A98AB74C8F2CECD850BA /* Sources */, + F6EC657AC5A7BEE9A3D288B582F4C5E9 /* Frameworks */, + F3E9930C736C01D12F5733EFD1F0A948 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Masonry; + productName = Masonry; + productReference = 0D6854C9307CDCC712B55D7EC927935E /* Masonry.framework */; + productType = "com.apple.product-type.framework"; + }; + D55833EC3DE9EBD9B329CAEB983D5A9D /* IQKeyboardManager */ = { + isa = PBXNativeTarget; + buildConfigurationList = 22A2379BF2B87BFC7BA495F9BD85DD28 /* Build configuration list for PBXNativeTarget "IQKeyboardManager" */; + buildPhases = ( + EF7C3A296212CFB87AC9B8A7939E3733 /* Sources */, + 8944C0B131AF550CF6CC8073435E22F2 /* Frameworks */, + 03AB14DB0235B494910320324F3BF2C2 /* Headers */, + 2E730D5A406D8720DD8830A43109145D /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = IQKeyboardManager; + productName = IQKeyboardManager; + productReference = 581983071B50ED00E03BBC3807ED5DEB /* IQKeyboardManager.framework */; + productType = "com.apple.product-type.framework"; + }; + DC3688684BF42A20A8998F31DDA51A49 /* JSONModel */ = { + isa = PBXNativeTarget; + buildConfigurationList = F4D16BF2938703D3A0079C402F5E75D8 /* Build configuration list for PBXNativeTarget "JSONModel" */; + buildPhases = ( + CF525CD81327D7C4B38AF818D91B35A1 /* Sources */, + 0F13FDE48FAA625D37D626F69DA46819 /* Frameworks */, + BBF7227F5BD0440E9DF598DF26EC3891 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = JSONModel; + productName = JSONModel; + productReference = 342C32AD5BF61779D426BDA9F82DEDE5 /* JSONModel.framework */; + productType = "com.apple.product-type.framework"; + }; + E14A62900910444707A5504D25EC98DC /* MJRefresh */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1EFADDC2BB6831ED43B76E0241CCDB75 /* Build configuration list for PBXNativeTarget "MJRefresh" */; + buildPhases = ( + 6D4ECE0A60E69F261AA10FE2CB90A0AC /* Sources */, + 1AAD91176E5F5F9AD062AD678F6746E4 /* Frameworks */, + 1D0B0A5525CB3F57F2D64B587D880D88 /* Headers */, + 8E06EE42A2928B5842D11E8A0A68E87D /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = MJRefresh; + productName = MJRefresh; + productReference = 2312E64F77FC628042C95F6F42AC9204 /* MJRefresh.framework */; + productType = "com.apple.product-type.framework"; + }; + E16D87E1F5CFFF8F722CF5A492B046B9 /* Toast */ = { + isa = PBXNativeTarget; + buildConfigurationList = 22083EC4897837089BD9F11DA45914F5 /* Build configuration list for PBXNativeTarget "Toast" */; + buildPhases = ( + 80EEAAD750B7EB5C6DB3F55299EBE91F /* Sources */, + 99BF636A9F3AC96472168608CED7A74E /* Frameworks */, + DD5EB35A6633261597F3AA694BC6C2A4 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Toast; + productName = Toast; + productReference = A7319007CA14024A0376E223A1A702CB /* Toast.framework */; + productType = "com.apple.product-type.framework"; + }; + F4160500DCEA3DA3E93FBA579E88CA0A /* AFNetworking */ = { + isa = PBXNativeTarget; + buildConfigurationList = 25909703FE8BF472066161C98342A956 /* Build configuration list for PBXNativeTarget "AFNetworking" */; + buildPhases = ( + 4CC771DB3008E2E9E454A6212D41A5E9 /* Sources */, + 6DE9B3A8689C804A43D970F1265675A4 /* Frameworks */, + 437E0B8BDA100834FD20877E5FCDC59D /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = AFNetworking; + productName = AFNetworking; + productReference = 8126B93DD8D474B90337F38D978130C5 /* AFNetworking.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0930; + LastUpgradeCheck = 0930; + }; + buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 7DB346D0F39D3F0E887471402A8071AB; + productRefGroup = 544FB77D6D6BCB080AE979EA734CA3D9 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + F4160500DCEA3DA3E93FBA579E88CA0A /* AFNetworking */, + 251BAD17812F7EBF6532EACF66F941C3 /* FMDB */, + D55833EC3DE9EBD9B329CAEB983D5A9D /* IQKeyboardManager */, + DC3688684BF42A20A8998F31DDA51A49 /* JSONModel */, + CCA9C33B127D6C859A3F8AFBEFCBABF0 /* LKDBHelper */, + D52144DE9D7255DE912490FF5A806573 /* Masonry */, + 6B1714E816AE794962516E2ECBB40A5A /* MBProgressHUD */, + E14A62900910444707A5504D25EC98DC /* MJRefresh */, + 826EFF975442065A54A0B2D3103EE6A4 /* NJKWebViewProgress */, + 9F61A37FCA87A09637399EBB3DE84342 /* Pods-GIGA */, + BC65E926DB84B0281E512834BE47D80A /* SDWebImage */, + 37E3F76B9AB64BE59F26C42C0DB02B51 /* SocketRocket */, + E16D87E1F5CFFF8F722CF5A492B046B9 /* Toast */, + 5CC70589280C1B49544760FFD838E2A4 /* TTTAttributedLabel */, + 95BEAA384CB15B77BDF7ACD211017BBF /* UITableView+FDTemplateLayoutCell */, + CF1D6BC4AC3FC60A30FB00811CF01999 /* YTKKeyValueStore */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 2E730D5A406D8720DD8830A43109145D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 788BA72F67004504FFDFC670048786B5 /* IQKeyboardManager.bundle in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8E06EE42A2928B5842D11E8A0A68E87D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6298B1C2234864DA5ED3B5E6398B95AC /* MJRefresh.bundle in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 00A62ED60FF8A98AB74C8F2CECD850BA /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 53BDF81D0A52EA526D597A5C5B139D7F /* MASCompositeConstraint.m in Sources */, + 59F81DE0305CC2AC448D2A3C6B3280A2 /* MASConstraint.m in Sources */, + 73BBDACC22CCA36A6DAAA167AD780BAF /* MASConstraintMaker.m in Sources */, + 6C23BBF56ED4DCC10CA1765A6736D1F8 /* MASLayoutConstraint.m in Sources */, + A08A8AB356264E248D01F1BC0EF08166 /* Masonry-dummy.m in Sources */, + A7370CE9231F9A4927142D79021879EC /* MASViewAttribute.m in Sources */, + 756DF24546C7D91459DCADC8F1C98660 /* MASViewConstraint.m in Sources */, + E72EDE323AC9F92EC8A00A93AC186093 /* NSArray+MASAdditions.m in Sources */, + 0F3DF5C3BEFCC9838B53C37735B414BE /* NSLayoutConstraint+MASDebugAdditions.m in Sources */, + F4B3E44D5D2F6508BC1BB35A9FBDEC70 /* View+MASAdditions.m in Sources */, + 8A6EEF68E7625AB66A3A8DED1594F88F /* ViewController+MASAdditions.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 27F6CE0C00F35EB887C1A6E900A26E62 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6A30D4D71707D4B4B6033AA5399D35C6 /* Pods-GIGA-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 28931639A1BF9251AAB8A696279FC52C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + D29CF1B9A1D71268C1F85EA53B32BA24 /* LKDB+Mapping.m in Sources */, + 6E6E8ADF2879B9F6832CE82F2B538366 /* LKDBHelper-dummy.m in Sources */, + 19119F01A87FAA55D45B4F11F33B7B3E /* LKDBHelper.m in Sources */, + A77943B15F7CF5151B637808B40DD722 /* LKDBUtils.m in Sources */, + DB55C38E306ED2B647AA6E49486483B7 /* NSObject+LKDBHelper.m in Sources */, + 2C5EA66B987D887948303DB77AF68D61 /* NSObject+LKModel.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 333271689444C03071D8092853B02EDD /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 1563D7F05577852DD479C1BA3CFC24CC /* NJKWebViewProgress-dummy.m in Sources */, + 40E6B7A671DFD76170156328D995546B /* NJKWebViewProgress.m in Sources */, + 8C9165B82240F78C43F7E7ACFD17612B /* NJKWebViewProgressView.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4CC771DB3008E2E9E454A6212D41A5E9 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 7099E4035C06D3116DA2586EFE563C0B /* AFAutoPurgingImageCache.m in Sources */, + 939EF882233B22D0321A70F6DADED11F /* AFHTTPSessionManager.m in Sources */, + B46FE8C00C2CDDE0B4790FFD3DC961A4 /* AFImageDownloader.m in Sources */, + EA23726556D213DB485BD1791C7164CF /* AFNetworkActivityIndicatorManager.m in Sources */, + 4C321BA8844AA4C44D4416CC6948DF2B /* AFNetworking-dummy.m in Sources */, + A12A3BC640B690479F345A49C6C48209 /* AFNetworkReachabilityManager.m in Sources */, + F30950E63F3D8D6C07FFB50C5971116E /* AFSecurityPolicy.m in Sources */, + E5CD5C797956697DDCC98A3EAC7E99E3 /* AFURLRequestSerialization.m in Sources */, + 3C9E113B7712442B4BCB59AB7EEC2085 /* AFURLResponseSerialization.m in Sources */, + 4C5DA96F7CAC26975EEEBD7450FF214D /* AFURLSessionManager.m in Sources */, + C257BE809D4C4357A8EB7118960E3143 /* UIActivityIndicatorView+AFNetworking.m in Sources */, + 8A1EB96C607F92E8AA20676F9A4BC7D9 /* UIButton+AFNetworking.m in Sources */, + 6AB8F78680B3470391219F11D51A1DE7 /* UIImageView+AFNetworking.m in Sources */, + 6595C6295B9EBBF40751A376239681FD /* UIProgressView+AFNetworking.m in Sources */, + 4AA3A9FC9AAD94C226CA975946C9395B /* UIRefreshControl+AFNetworking.m in Sources */, + 3345805C0D8E8D0726F7E5981DA61A5F /* UIWebView+AFNetworking.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5D9F4A386169F298C8544D099324BB28 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 57E9B041CC1D8988C38DDC97CAEFCD76 /* MBProgressHUD-dummy.m in Sources */, + AA00DCC0C8174B2D7E48EEC3C768B047 /* MBProgressHUD.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 6D4ECE0A60E69F261AA10FE2CB90A0AC /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 621B413DAEFE75991251ED378822527C /* MJRefresh-dummy.m in Sources */, + D46545D206874E3A223372C84F1EA73E /* MJRefreshAutoFooter.m in Sources */, + 7EFDAA1642FA83DE777CFD086182D5A4 /* MJRefreshAutoGifFooter.m in Sources */, + 344DB99F8332029C0391F08B6D0E425C /* MJRefreshAutoNormalFooter.m in Sources */, + 1843E6DF520A5EFE9C83C38E18578E42 /* MJRefreshAutoStateFooter.m in Sources */, + E80DB5D9B2D35085282DF057BB540AFE /* MJRefreshBackFooter.m in Sources */, + D66E78D63935A98894E702D922AA8B91 /* MJRefreshBackGifFooter.m in Sources */, + 101F836F887C01B45F4DCF351EBC28D1 /* MJRefreshBackNormalFooter.m in Sources */, + 2524EC4EF024A6C067A0FA082084CFB5 /* MJRefreshBackStateFooter.m in Sources */, + F68EA720B0ED1BF96CEBF07977A1C0A2 /* MJRefreshComponent.m in Sources */, + 8069223DDD6D0F2E1A87D8E66966709B /* MJRefreshConst.m in Sources */, + 3829CBCC3598DB13C2AD3B7383D1F24A /* MJRefreshFooter.m in Sources */, + FD31283E2A43955C5BA6FA9008EE8D7C /* MJRefreshGifHeader.m in Sources */, + 8DC3FC2342EC2E944B3A3E83E2683130 /* MJRefreshHeader.m in Sources */, + E57312010AFB591EE37870F65E651EA6 /* MJRefreshNormalHeader.m in Sources */, + 07159A933B3C47A02FE2B2744ABAAC89 /* MJRefreshStateHeader.m in Sources */, + F4A57F7C1F8184A6DDEABB07FA6D7083 /* NSBundle+MJRefresh.m in Sources */, + FB9C6242B11049E2F1062D04565E568D /* UIScrollView+MJExtension.m in Sources */, + 8B855A73B75155FB2C0CB05B54FDDE0D /* UIScrollView+MJRefresh.m in Sources */, + 0A1E34B4A27DCD62A914F3B028A07E6C /* UIView+MJExtension.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 80EEAAD750B7EB5C6DB3F55299EBE91F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 601FD63D1FC6DBB1277966362EE290CD /* Toast-dummy.m in Sources */, + D51D64915E3DDF60300CB400C1F49027 /* UIView+Toast.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 8FE0D4B503A94502F3431DC0DCB58040 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 37F097E2269EF1BD238AD7449D796445 /* FMDatabase.m in Sources */, + 9C11A290C9C5866A185A54F1EC04E2BB /* FMDatabaseAdditions.m in Sources */, + C605A44DF96E7FCACF7D6E37B62F795D /* FMDatabasePool.m in Sources */, + A1B5D80A8998311B8C9043E6942925E6 /* FMDatabaseQueue.m in Sources */, + D5991941DC41DDDDDACAE0B5D47A4639 /* FMDB-dummy.m in Sources */, + 87ECA447DB887426665260651B7F147E /* FMResultSet.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9CAE333B428F0263F4FD761FC1E2B4D0 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 7DE362297135870194FA02C34D3135E7 /* TTTAttributedLabel-dummy.m in Sources */, + C0F07BA73BBC072EFCABCED3B6D24604 /* TTTAttributedLabel.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9FF620AC95D419DCDC9860DC4E44F14E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + DB596BB8F97C2B0A0CA72695B4010141 /* SocketRocket-dummy.m in Sources */, + 8138BA0A46637819E90CE18C773CA9FD /* SRWebSocket.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + AD6EFB2F02B9791F95156117142A99BE /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C0BD02712FC62F45C60CA65FDCF21D80 /* NSButton+WebCache.m in Sources */, + 09FD31B5AA4FD8F5D8691D0A3ACF1A6B /* NSData+ImageContentType.m in Sources */, + E8DAB555F27A1AF5B02B19282B609B8E /* NSImage+WebCache.m in Sources */, + 59F5736C531C7F4C5F79C9EDDACC0B64 /* SDAnimatedImageRep.m in Sources */, + 0CAD81FA7346928A75DFA501EDF7A678 /* SDImageCache.m in Sources */, + E2E95C8112B691A912057A2DCD2B9297 /* SDImageCacheConfig.m in Sources */, + C0337E1DD3AA7BD36B20A9C92EA3208F /* SDWebImage-dummy.m in Sources */, + DE83F763EE2F69844D4359D9E80840F2 /* SDWebImageCoder.m in Sources */, + B72A7B6970A8E91258D4AC521B86A8B0 /* SDWebImageCoderHelper.m in Sources */, + A91C005A46878C2DB5B6B4A67CC1DDC4 /* SDWebImageCodersManager.m in Sources */, + E504492C8894D7522724712EFA67C7D1 /* SDWebImageCompat.m in Sources */, + B26E3D1F70F70E23C4EDA96CC327BC1E /* SDWebImageDownloader.m in Sources */, + 39A98121DA410F19CE5F46E280F22179 /* SDWebImageDownloaderOperation.m in Sources */, + 8EF496E24AC25617194114DDB71D5385 /* SDWebImageFrame.m in Sources */, + 92126299C232FC474021BADE26F056A4 /* SDWebImageGIFCoder.m in Sources */, + 7E40D4939F89C4852C4224D6A65E6BD5 /* SDWebImageImageIOCoder.m in Sources */, + 39120D78F1F32B35C353A9EBA0149B45 /* SDWebImageManager.m in Sources */, + D7814F3ED165AA11096F7B172D35FD5F /* SDWebImagePrefetcher.m in Sources */, + 3376AE1663C14F1926F04D4FE0225E97 /* SDWebImageTransition.m in Sources */, + FA0124E4B3FEA15F037A936E569EBAEF /* UIButton+WebCache.m in Sources */, + 5BC4E3F5EFAE7516C06D8A357407DCAF /* UIImage+ForceDecode.m in Sources */, + 81D12B648C1E782DEC1B2566EE17FB6A /* UIImage+GIF.m in Sources */, + ACA82B48BEE47C89F7AEE07F4F8B462E /* UIImage+MultiFormat.m in Sources */, + 327E1782C89B350FDE631F3CACD4C8A2 /* UIImageView+HighlightedWebCache.m in Sources */, + DA6FBCC4512298773ABFFA8A1F8BD972 /* UIImageView+WebCache.m in Sources */, + B0E60D4A86434F567D7F9E590161AA7C /* UIView+WebCache.m in Sources */, + 5B9AB2E420B063C994B8295F4EF48E37 /* UIView+WebCacheOperation.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CCF8135D6E7EC6FF96D1888CC3999B4D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 5E1468EA73C7741EEC370E4A15167D0E /* YTKKeyValueStore-dummy.m in Sources */, + 02307CD9BE8AB7050090F7CE6AA1C4E8 /* YTKKeyValueStore.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CF525CD81327D7C4B38AF818D91B35A1 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 06697BBB6E6D73B5F021E6DACAC5DE45 /* JSONAPI.m in Sources */, + 57FE38F17C0EDD5CF73B2A084A17586E /* JSONHTTPClient.m in Sources */, + 772785574BC1059C2913576CBFF3AD17 /* JSONKeyMapper.m in Sources */, + 98F19C682AC68E9D2E2052F709F42AF9 /* JSONModel+networking.m in Sources */, + 8060025235D93F30A5F10B412DD0822E /* JSONModel-dummy.m in Sources */, + E39D9A942BCE728467A42C478816966F /* JSONModel.m in Sources */, + 40A6216FC50B4540584DA1C45F98F9FD /* JSONModelClassProperty.m in Sources */, + 0B1C5725C7BE03D622114275D6FD6EFA /* JSONModelError.m in Sources */, + 37F6913EE3CD6EB8715086F0C9F6A823 /* JSONValueTransformer.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + DC6EE35E0B75550D805CBE30078E9EC7 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8C2908931C952C7B1801BC7D5D321BED /* UITableView+FDIndexPathHeightCache.m in Sources */, + 6FAE8BF1BF564D1F2D5F368F8704A6D1 /* UITableView+FDKeyedHeightCache.m in Sources */, + E624C54E55BFAE88D8EC8492E2B62619 /* UITableView+FDTemplateLayoutCell-dummy.m in Sources */, + 971255F19D9DC5EEC2566D186FB5A433 /* UITableView+FDTemplateLayoutCell.m in Sources */, + D54920CE34AFF30F529E61D9459C5006 /* UITableView+FDTemplateLayoutCellDebug.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EF7C3A296212CFB87AC9B8A7939E3733 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 0DB2E34289D18AA9810609ADCCBFA181 /* IQBarButtonItem.m in Sources */, + A3CE2D718CEB5AC059823178404AF0EF /* IQKeyboardManager-dummy.m in Sources */, + 2D407C6492BC569F5361B9210C89A19C /* IQKeyboardManager.m in Sources */, + E802560B425A04296159872675948D29 /* IQKeyboardReturnKeyHandler.m in Sources */, + 7C49A18841060D12A58F92CE62C21F9D /* IQNSArray+Sort.m in Sources */, + C2B7F4EB405C401EA53023341C05E15E /* IQPreviousNextView.m in Sources */, + 72EE4A5DC3076CD8C13717D4DAA37DFD /* IQTextView.m in Sources */, + 958FEEE31215AB970371D4CBAEB8A4DC /* IQTitleBarButtonItem.m in Sources */, + CA1E205A4D3A8515ED42F76C2671F1BA /* IQToolbar.m in Sources */, + 431C76067CB09B1FC0E4DD5AEA6B540A /* IQUIScrollView+Additions.m in Sources */, + 665B3B037B98D3E3ADB449A43FF14F42 /* IQUITextFieldView+Additions.m in Sources */, + DEB92E2DB086E554AEA1DBFA8A9F00D0 /* IQUIView+Hierarchy.m in Sources */, + C4AA57B938513DE614A7B90AEF5CD858 /* IQUIView+IQKeyboardToolbar.m in Sources */, + C480AC5D32406D4901116FCAC5FB0EB5 /* IQUIViewController+Additions.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 15B63977E3E79F3D3D3A1CC2E997A2AD /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = SocketRocket; + target = 37E3F76B9AB64BE59F26C42C0DB02B51 /* SocketRocket */; + targetProxy = 79CCAC30E08937B11F101E7A789BF6A9 /* PBXContainerItemProxy */; + }; + 23C83C77DA981D934463D2CBA4E59819 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = LKDBHelper; + target = CCA9C33B127D6C859A3F8AFBEFCBABF0 /* LKDBHelper */; + targetProxy = D16DEB882FB3ACDF2B1D59F84EB72924 /* PBXContainerItemProxy */; + }; + 43C4C6615D3225CE5887349E1E308532 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Toast; + target = E16D87E1F5CFFF8F722CF5A492B046B9 /* Toast */; + targetProxy = 12C08506A8A26019CD1B7D866E2D9AE0 /* PBXContainerItemProxy */; + }; + 44A9CFDCB06EA5269E4C950DAD8ED972 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = MBProgressHUD; + target = 6B1714E816AE794962516E2ECBB40A5A /* MBProgressHUD */; + targetProxy = 10C19AB1817BEF22435DC5055DE4F0F4 /* PBXContainerItemProxy */; + }; + 471DD9226DF1018D260537872E4FBDAE /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = IQKeyboardManager; + target = D55833EC3DE9EBD9B329CAEB983D5A9D /* IQKeyboardManager */; + targetProxy = D55D2D92CB19AF61F08790B384A513E0 /* PBXContainerItemProxy */; + }; + 47FBEED3E9AA3E4E9EC7667FF3B4777E /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = SDWebImage; + target = BC65E926DB84B0281E512834BE47D80A /* SDWebImage */; + targetProxy = 448C316EBC342AEAB86CA07E51B7CCEB /* PBXContainerItemProxy */; + }; + 52C881058B7DC72C4AF030FA8F99288E /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = AFNetworking; + target = F4160500DCEA3DA3E93FBA579E88CA0A /* AFNetworking */; + targetProxy = 23CDBC7F0F0884CFA75FBBEF10D3B03D /* PBXContainerItemProxy */; + }; + 52EFABC352FCC5BC3BEE5E4B4735B33D /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = YTKKeyValueStore; + target = CF1D6BC4AC3FC60A30FB00811CF01999 /* YTKKeyValueStore */; + targetProxy = F9DD1D0D243D5BA994B993C063F16F85 /* PBXContainerItemProxy */; + }; + 57816986BEF7436716C5170BA0F6A708 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = JSONModel; + target = DC3688684BF42A20A8998F31DDA51A49 /* JSONModel */; + targetProxy = 14399779F1E76914D37F4F6C523906BB /* PBXContainerItemProxy */; + }; + 71A30A7A2718C8461D0FF1BE77A2D699 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = MJRefresh; + target = E14A62900910444707A5504D25EC98DC /* MJRefresh */; + targetProxy = 07FD3E22A9DD4A1B99981D75716BD3AE /* PBXContainerItemProxy */; + }; + 758008F7D1531C273A6CDA6ABA85E20B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "UITableView+FDTemplateLayoutCell"; + target = 95BEAA384CB15B77BDF7ACD211017BBF /* UITableView+FDTemplateLayoutCell */; + targetProxy = 43E5D6A14DFB2BB82D0E18797207D59C /* PBXContainerItemProxy */; + }; + 99A84B27A5415B21021711DF73056760 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = TTTAttributedLabel; + target = 5CC70589280C1B49544760FFD838E2A4 /* TTTAttributedLabel */; + targetProxy = 0624AA154FDA56AB497466DC03BB55B6 /* PBXContainerItemProxy */; + }; + AB64071AA32D5C7F56262E76491764BE /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = NJKWebViewProgress; + target = 826EFF975442065A54A0B2D3103EE6A4 /* NJKWebViewProgress */; + targetProxy = 90FC23568A2780CCB2D594FAE3F3B4B3 /* PBXContainerItemProxy */; + }; + BCD3529C382009CD52BA7FE04C413E02 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Masonry; + target = D52144DE9D7255DE912490FF5A806573 /* Masonry */; + targetProxy = C250CB5A26266169FD4E1B35C6267674 /* PBXContainerItemProxy */; + }; + C06C0264289BBBE19528702557CC8FC1 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = FMDB; + target = 251BAD17812F7EBF6532EACF66F941C3 /* FMDB */; + targetProxy = C3C1D0DAF595497F4E217F601FF28DE8 /* PBXContainerItemProxy */; + }; + C5949C3702F8D473B24B99AF83A168EA /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = FMDB; + target = 251BAD17812F7EBF6532EACF66F941C3 /* FMDB */; + targetProxy = 8A906A446E3695C9C80C35AF0D8D128A /* PBXContainerItemProxy */; + }; + F615009BA540330ABAB8C97015D7E9D7 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = FMDB; + target = 251BAD17812F7EBF6532EACF66F941C3 /* FMDB */; + targetProxy = FDFB12CC87933DAABA8E177FE069CD99 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 030147F75322C49391CC6A180694DA1A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9508DBBE609A983ECCD13E2627C7678E /* JSONModel.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/JSONModel/JSONModel-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/JSONModel/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/JSONModel/JSONModel.modulemap"; + PRODUCT_MODULE_NAME = JSONModel; + PRODUCT_NAME = JSONModel; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 1EE19F5DD95931924296F637BF18BD8F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_ALLOWED = NO; + CODE_SIGNING_REQUIRED = NO; + 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 = 8.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 2B8A6007035DBC0EFFEAF10089E67972 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 572894CF08231457B24C1071533852F6 /* TTTAttributedLabel.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/TTTAttributedLabel/TTTAttributedLabel-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/TTTAttributedLabel/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/TTTAttributedLabel/TTTAttributedLabel.modulemap"; + PRODUCT_MODULE_NAME = TTTAttributedLabel; + PRODUCT_NAME = TTTAttributedLabel; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 3229F5219B17A9A0A495A822D0D76552 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9574A12E8279712E0544674068BEC2E1 /* Pods-GIGA.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = 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-GIGA/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-GIGA/Pods-GIGA.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; + }; + 3845069A573E47CF21533487C497A730 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 0DE0E0C75D4EFF8E1F1A6897C860EC33 /* Masonry.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/Masonry/Masonry-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Masonry/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/Masonry/Masonry.modulemap"; + PRODUCT_MODULE_NAME = Masonry; + PRODUCT_NAME = Masonry; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 3FDE1A3479CDFFEC9781B7D059673D86 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9508DBBE609A983ECCD13E2627C7678E /* JSONModel.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/JSONModel/JSONModel-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/JSONModel/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/JSONModel/JSONModel.modulemap"; + PRODUCT_MODULE_NAME = JSONModel; + PRODUCT_NAME = JSONModel; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 437D32CF66962E25C97C70E374F699A6 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F37E8A21FCF063D9A8212C6CA857A124 /* YTKKeyValueStore.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/YTKKeyValueStore/YTKKeyValueStore-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/YTKKeyValueStore/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/YTKKeyValueStore/YTKKeyValueStore.modulemap"; + PRODUCT_MODULE_NAME = YTKKeyValueStore; + PRODUCT_NAME = YTKKeyValueStore; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 43EAA89AC085B77AAC7B6708389028D8 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F37E8A21FCF063D9A8212C6CA857A124 /* YTKKeyValueStore.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/YTKKeyValueStore/YTKKeyValueStore-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/YTKKeyValueStore/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/YTKKeyValueStore/YTKKeyValueStore.modulemap"; + PRODUCT_MODULE_NAME = YTKKeyValueStore; + PRODUCT_NAME = YTKKeyValueStore; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 4F8845C8AA7628D814E62D3DA5BBE94C /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7297AD18E47185F3F70FA09B01B9E511 /* LKDBHelper.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/LKDBHelper/LKDBHelper-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/LKDBHelper/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/LKDBHelper/LKDBHelper.modulemap"; + PRODUCT_MODULE_NAME = LKDBHelper; + PRODUCT_NAME = LKDBHelper; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 5158EC3BBBE24D0DC0B7FD8485499D50 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 758B3F6E587B47427A1ADFF5C9973B84 /* NJKWebViewProgress.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/NJKWebViewProgress/NJKWebViewProgress-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/NJKWebViewProgress/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/NJKWebViewProgress/NJKWebViewProgress.modulemap"; + PRODUCT_MODULE_NAME = NJKWebViewProgress; + PRODUCT_NAME = NJKWebViewProgress; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 5EA25C1E9FDF8DEF6A53F68A6237E686 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 053BB0597C8AADB4758AD482E0A510B0 /* FMDB.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/FMDB/FMDB-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/FMDB/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/FMDB/FMDB.modulemap"; + PRODUCT_MODULE_NAME = FMDB; + PRODUCT_NAME = FMDB; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 6B20280CE6A95E2D8D451B55CDA5C940 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 39CB9D0EBDE904E619E327F0B49A9062 /* MJRefresh.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/MJRefresh/MJRefresh-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/MJRefresh/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/MJRefresh/MJRefresh.modulemap"; + PRODUCT_MODULE_NAME = MJRefresh; + PRODUCT_NAME = MJRefresh; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 6FDB77145A49DA9893642D8226EBEFB5 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 758B3F6E587B47427A1ADFF5C9973B84 /* NJKWebViewProgress.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/NJKWebViewProgress/NJKWebViewProgress-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/NJKWebViewProgress/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/NJKWebViewProgress/NJKWebViewProgress.modulemap"; + PRODUCT_MODULE_NAME = NJKWebViewProgress; + PRODUCT_NAME = NJKWebViewProgress; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 7D95619E7EDE9F3FC6AD74F265102D66 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 053BB0597C8AADB4758AD482E0A510B0 /* FMDB.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/FMDB/FMDB-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/FMDB/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/FMDB/FMDB.modulemap"; + PRODUCT_MODULE_NAME = FMDB; + PRODUCT_NAME = FMDB; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 91A17F62BDD3A47B620B8F785CC8B605 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 17979012F15292B8E646C3D69BB45763 /* SocketRocket.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/SocketRocket/SocketRocket-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SocketRocket/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/SocketRocket/SocketRocket.modulemap"; + PRODUCT_MODULE_NAME = SocketRocket; + PRODUCT_NAME = SocketRocket; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 98220769C0FAD22BA9763C663E86BBDA /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 8FFE95948B8B44700795DACEC0372ED5 /* UITableView+FDTemplateLayoutCell.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/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/UITableView+FDTemplateLayoutCell/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/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell.modulemap"; + PRODUCT_MODULE_NAME = UITableView_FDTemplateLayoutCell; + PRODUCT_NAME = UITableView_FDTemplateLayoutCell; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 9DB789882BAFB3FAAAC0CE3010D697E4 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 0712B6EB2B50F748C0C18FF36D97B3DF /* AFNetworking.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/AFNetworking/AFNetworking-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/AFNetworking/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/AFNetworking/AFNetworking.modulemap"; + PRODUCT_MODULE_NAME = AFNetworking; + PRODUCT_NAME = AFNetworking; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + A1F2087375C7B0E0FC17B7C69C343A24 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7297AD18E47185F3F70FA09B01B9E511 /* LKDBHelper.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/LKDBHelper/LKDBHelper-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/LKDBHelper/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/LKDBHelper/LKDBHelper.modulemap"; + PRODUCT_MODULE_NAME = LKDBHelper; + PRODUCT_NAME = LKDBHelper; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + A500AE804E9C41A4C32A283EE0F9FE17 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 17979012F15292B8E646C3D69BB45763 /* SocketRocket.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/SocketRocket/SocketRocket-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SocketRocket/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/SocketRocket/SocketRocket.modulemap"; + PRODUCT_MODULE_NAME = SocketRocket; + PRODUCT_NAME = SocketRocket; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + B47DB8873BD38F138D40B5834981E81C /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 8FFE95948B8B44700795DACEC0372ED5 /* UITableView+FDTemplateLayoutCell.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/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/UITableView+FDTemplateLayoutCell/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/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell.modulemap"; + PRODUCT_MODULE_NAME = UITableView_FDTemplateLayoutCell; + PRODUCT_NAME = UITableView_FDTemplateLayoutCell; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + C2562A2CCB1E969A1C97ED084AF1D0A2 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F8EDD5DCE505C958412B980AE9818187 /* SDWebImage.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/SDWebImage/SDWebImage-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SDWebImage/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/SDWebImage/SDWebImage.modulemap"; + PRODUCT_MODULE_NAME = SDWebImage; + PRODUCT_NAME = SDWebImage; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + C31D4A60B85340BE5612ED03122BB05A /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 687C5821B77D4D232E15C3BD22C69C47 /* IQKeyboardManager.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/IQKeyboardManager/IQKeyboardManager-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/IQKeyboardManager/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/IQKeyboardManager/IQKeyboardManager.modulemap"; + PRODUCT_MODULE_NAME = IQKeyboardManager; + PRODUCT_NAME = IQKeyboardManager; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + C7C4781DE4E0F4EACA91CAF393AB7B31 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DC42CB78293EF7E2CE36240956AA0249 /* Toast.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/Toast/Toast-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Toast/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/Toast/Toast.modulemap"; + PRODUCT_MODULE_NAME = Toast; + PRODUCT_NAME = Toast; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + CAE49E0E245A9D9D88D399CCA82567F0 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 218B6E61733A5B9138CB4D0815133580 /* Pods-GIGA.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = 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-GIGA/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-GIGA/Pods-GIGA.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; + }; + CF7020C6E9C00CE59577DC6F9E4255AF /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 46D5F33AFF37B1C04CBDE88EF04B11A3 /* MBProgressHUD.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/MBProgressHUD/MBProgressHUD-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/MBProgressHUD/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/MBProgressHUD/MBProgressHUD.modulemap"; + PRODUCT_MODULE_NAME = MBProgressHUD; + PRODUCT_NAME = MBProgressHUD; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + D0283D74AA9E4B0F055622C3C9C03217 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 39CB9D0EBDE904E619E327F0B49A9062 /* MJRefresh.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/MJRefresh/MJRefresh-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/MJRefresh/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/MJRefresh/MJRefresh.modulemap"; + PRODUCT_MODULE_NAME = MJRefresh; + PRODUCT_NAME = MJRefresh; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + D58874A0278544B4451530E213B17915 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = DC42CB78293EF7E2CE36240956AA0249 /* Toast.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/Toast/Toast-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Toast/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/Toast/Toast.modulemap"; + PRODUCT_MODULE_NAME = Toast; + PRODUCT_NAME = Toast; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + D8013C7029DB0DC9BF66FCEA8D372A24 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F8EDD5DCE505C958412B980AE9818187 /* SDWebImage.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/SDWebImage/SDWebImage-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SDWebImage/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/SDWebImage/SDWebImage.modulemap"; + PRODUCT_MODULE_NAME = SDWebImage; + PRODUCT_NAME = SDWebImage; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + D958D0B06505E793082732152F56DAB8 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 687C5821B77D4D232E15C3BD22C69C47 /* IQKeyboardManager.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/IQKeyboardManager/IQKeyboardManager-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/IQKeyboardManager/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/IQKeyboardManager/IQKeyboardManager.modulemap"; + PRODUCT_MODULE_NAME = IQKeyboardManager; + PRODUCT_NAME = IQKeyboardManager; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + DF7FA40181E08DC392346D86E3A8405C /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 0712B6EB2B50F748C0C18FF36D97B3DF /* AFNetworking.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/AFNetworking/AFNetworking-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/AFNetworking/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/AFNetworking/AFNetworking.modulemap"; + PRODUCT_MODULE_NAME = AFNetworking; + PRODUCT_NAME = AFNetworking; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + F147DE2EB0DE030E54C6E63C35F621A1 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 46D5F33AFF37B1C04CBDE88EF04B11A3 /* MBProgressHUD.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/MBProgressHUD/MBProgressHUD-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/MBProgressHUD/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/MBProgressHUD/MBProgressHUD.modulemap"; + PRODUCT_MODULE_NAME = MBProgressHUD; + PRODUCT_NAME = MBProgressHUD; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + F4568DEE257655D290C2B9CEAB37C934 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_ALLOWED = NO; + CODE_SIGNING_REQUIRED = NO; + 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 = 8.0; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Release; + }; + FC7B99973F9E44159F9D60984F5CB4EC /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 572894CF08231457B24C1071533852F6 /* TTTAttributedLabel.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/TTTAttributedLabel/TTTAttributedLabel-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/TTTAttributedLabel/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/TTTAttributedLabel/TTTAttributedLabel.modulemap"; + PRODUCT_MODULE_NAME = TTTAttributedLabel; + PRODUCT_NAME = TTTAttributedLabel; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + FE3EC76958EB417BB5A9577967FD1019 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 0DE0E0C75D4EFF8E1F1A6897C860EC33 /* Masonry.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/Masonry/Masonry-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Masonry/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/Masonry/Masonry.modulemap"; + PRODUCT_MODULE_NAME = Masonry; + PRODUCT_NAME = Masonry; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 0012A7CF52D71D63FC55A4D5A6AC4075 /* Build configuration list for PBXNativeTarget "Pods-GIGA" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + CAE49E0E245A9D9D88D399CCA82567F0 /* Debug */, + 3229F5219B17A9A0A495A822D0D76552 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 02D024184BD368B565F3B6257DF3C605 /* Build configuration list for PBXNativeTarget "Masonry" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 3845069A573E47CF21533487C497A730 /* Debug */, + FE3EC76958EB417BB5A9577967FD1019 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 1EFADDC2BB6831ED43B76E0241CCDB75 /* Build configuration list for PBXNativeTarget "MJRefresh" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + D0283D74AA9E4B0F055622C3C9C03217 /* Debug */, + 6B20280CE6A95E2D8D451B55CDA5C940 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 22083EC4897837089BD9F11DA45914F5 /* Build configuration list for PBXNativeTarget "Toast" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + D58874A0278544B4451530E213B17915 /* Debug */, + C7C4781DE4E0F4EACA91CAF393AB7B31 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 22A2379BF2B87BFC7BA495F9BD85DD28 /* Build configuration list for PBXNativeTarget "IQKeyboardManager" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C31D4A60B85340BE5612ED03122BB05A /* Debug */, + D958D0B06505E793082732152F56DAB8 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 25909703FE8BF472066161C98342A956 /* Build configuration list for PBXNativeTarget "AFNetworking" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 9DB789882BAFB3FAAAC0CE3010D697E4 /* Debug */, + DF7FA40181E08DC392346D86E3A8405C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 28A1BDB3CE3F2F1CB0931DFEEDBA7936 /* Build configuration list for PBXNativeTarget "MBProgressHUD" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + CF7020C6E9C00CE59577DC6F9E4255AF /* Debug */, + F147DE2EB0DE030E54C6E63C35F621A1 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1EE19F5DD95931924296F637BF18BD8F /* Debug */, + F4568DEE257655D290C2B9CEAB37C934 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4DC283BD16CE8D51C0C47A03AE2B9931 /* Build configuration list for PBXNativeTarget "TTTAttributedLabel" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FC7B99973F9E44159F9D60984F5CB4EC /* Debug */, + 2B8A6007035DBC0EFFEAF10089E67972 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 529362CDA42ABA356BEDB1C8DE1878E5 /* Build configuration list for PBXNativeTarget "UITableView+FDTemplateLayoutCell" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 98220769C0FAD22BA9763C663E86BBDA /* Debug */, + B47DB8873BD38F138D40B5834981E81C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 5B0566FF0CE681AC326D316CEC45A8CF /* Build configuration list for PBXNativeTarget "FMDB" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 5EA25C1E9FDF8DEF6A53F68A6237E686 /* Debug */, + 7D95619E7EDE9F3FC6AD74F265102D66 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 5C5BD8C49D5108DF93608FA1EDC5B5EF /* Build configuration list for PBXNativeTarget "NJKWebViewProgress" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 5158EC3BBBE24D0DC0B7FD8485499D50 /* Debug */, + 6FDB77145A49DA9893642D8226EBEFB5 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 730557350F2D643032C64C252A33646B /* Build configuration list for PBXNativeTarget "LKDBHelper" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 4F8845C8AA7628D814E62D3DA5BBE94C /* Debug */, + A1F2087375C7B0E0FC17B7C69C343A24 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 9CCFEAF1989FAB852D4659E698888A02 /* Build configuration list for PBXNativeTarget "YTKKeyValueStore" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 43EAA89AC085B77AAC7B6708389028D8 /* Debug */, + 437D32CF66962E25C97C70E374F699A6 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + B54043E8C4A49656CF64035A2F5B237A /* Build configuration list for PBXNativeTarget "SDWebImage" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + D8013C7029DB0DC9BF66FCEA8D372A24 /* Debug */, + C2562A2CCB1E969A1C97ED084AF1D0A2 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + CEE1C7C5EB2923B3BFB904DF6E10ABAE /* Build configuration list for PBXNativeTarget "SocketRocket" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 91A17F62BDD3A47B620B8F785CC8B605 /* Debug */, + A500AE804E9C41A4C32A283EE0F9FE17 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + F4D16BF2938703D3A0079C402F5E75D8 /* Build configuration list for PBXNativeTarget "JSONModel" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 3FDE1A3479CDFFEC9781B7D059673D86 /* Debug */, + 030147F75322C49391CC6A180694DA1A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; +} diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/AFNetworking.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/AFNetworking.xcscheme new file mode 100644 index 0000000..d49ba02 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/AFNetworking.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/FMDB.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/FMDB.xcscheme new file mode 100644 index 0000000..9e99512 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/FMDB.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/IQKeyboardManager.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/IQKeyboardManager.xcscheme new file mode 100644 index 0000000..6b24ae8 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/IQKeyboardManager.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/JSONModel.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/JSONModel.xcscheme new file mode 100644 index 0000000..7071267 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/JSONModel.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/LKDBHelper.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/LKDBHelper.xcscheme new file mode 100644 index 0000000..04ec8e4 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/LKDBHelper.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/MBProgressHUD.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/MBProgressHUD.xcscheme new file mode 100644 index 0000000..ae00253 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/MBProgressHUD.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/MJRefresh.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/MJRefresh.xcscheme new file mode 100644 index 0000000..3923004 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/MJRefresh.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/Masonry.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/Masonry.xcscheme new file mode 100644 index 0000000..eea9141 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/Masonry.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/NJKWebViewProgress.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/NJKWebViewProgress.xcscheme new file mode 100644 index 0000000..c207413 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/NJKWebViewProgress.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/Pods-GIGA.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/Pods-GIGA.xcscheme new file mode 100644 index 0000000..4777095 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/Pods-GIGA.xcscheme @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/SDWebImage.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/SDWebImage.xcscheme new file mode 100644 index 0000000..1a0b46d --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/SDWebImage.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/SocketRocket.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/SocketRocket.xcscheme new file mode 100644 index 0000000..cfd853c --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/SocketRocket.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/TTTAttributedLabel.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/TTTAttributedLabel.xcscheme new file mode 100644 index 0000000..19a9f4e --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/TTTAttributedLabel.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/Toast.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/Toast.xcscheme new file mode 100644 index 0000000..49d0d78 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/Toast.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/UITableView+FDTemplateLayoutCell.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/UITableView+FDTemplateLayoutCell.xcscheme new file mode 100644 index 0000000..9e7cc16 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/UITableView+FDTemplateLayoutCell.xcscheme @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/YTKKeyValueStore.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/YTKKeyValueStore.xcscheme new file mode 100644 index 0000000..40b4587 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/YTKKeyValueStore.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/xcschememanagement.plist b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..ae6ee25 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/lianxiang.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,123 @@ + + + + + SchemeUserState + + AFNetworking.xcscheme + + isShown + + orderHint + 0 + + FMDB.xcscheme + + isShown + + orderHint + 1 + + IQKeyboardManager.xcscheme + + isShown + + orderHint + 2 + + JSONModel.xcscheme + + isShown + + orderHint + 3 + + LKDBHelper.xcscheme + + isShown + + orderHint + 4 + + MBProgressHUD.xcscheme + + isShown + + orderHint + 6 + + MJRefresh.xcscheme + + isShown + + orderHint + 7 + + Masonry.xcscheme + + isShown + + orderHint + 5 + + NJKWebViewProgress.xcscheme + + isShown + + orderHint + 8 + + Pods-GIGA.xcscheme + + isShown + + orderHint + 9 + + SDWebImage.xcscheme + + isShown + + orderHint + 10 + + SocketRocket.xcscheme + + isShown + + orderHint + 11 + + TTTAttributedLabel.xcscheme + + isShown + + orderHint + 13 + + Toast.xcscheme + + isShown + + orderHint + 12 + + UITableView+FDTemplateLayoutCell.xcscheme + + isShown + + orderHint + 14 + + YTKKeyValueStore.xcscheme + + isShown + + orderHint + 15 + + + SuppressBuildableAutocreation + + + diff --git a/Pods/SDWebImage/LICENSE b/Pods/SDWebImage/LICENSE new file mode 100644 index 0000000..92a252a --- /dev/null +++ b/Pods/SDWebImage/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2009-2017 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. + diff --git a/Pods/SDWebImage/README.md b/Pods/SDWebImage/README.md new file mode 100644 index 0000000..c8bd848 --- /dev/null +++ b/Pods/SDWebImage/README.md @@ -0,0 +1,179 @@ +

+ +

+ + +[![Build Status](http://img.shields.io/travis/rs/SDWebImage/master.svg?style=flat)](https://travis-ci.org/rs/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) +[![Dependency Status](https://www.versioneye.com/objective-c/sdwebimage/badge.svg?style=flat)](https://www.versioneye.com/objective-c/sdwebimage) +[![Reference Status](https://www.versioneye.com/objective-c/sdwebimage/reference_badge.svg?style=flat)](https://www.versioneye.com/objective-c/sdwebimage/references) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/rs/SDWebImage) +[![codecov](https://codecov.io/gh/rs/SDWebImage/branch/master/graph/badge.svg)](https://codecov.io/gh/rs/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 +- [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] Performances! +- [x] Use GCD and ARC + +## Supported Image Formats + +- Image formats supported by UIImage (JPEG, PNG, ...), including GIF +- WebP format, including animated WebP (use the `WebP` subspec) + +## Requirements + +- iOS 7.0 or later +- tvOS 9.0 or later +- watchOS 2.0 or later +- macOS 10.9 or later +- Xcode 7.3 or later + +#### Backwards compatibility + +- For iOS 5 and 6, use [any 3.x version up to 3.7.6](https://github.com/rs/SDWebImage/tree/3.7.6) +- For iOS < 5.0, please use the last [2.0 version](https://github.com/rs/SDWebImage/tree/2.0-compat). + +## Getting Started + +- Read this Readme doc +- Read the [How to use section](https://github.com/rs/SDWebImage#how-to-use) +- Read the [Documentation @ CocoaDocs](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/rs/SDWebImage/wiki/Installation-Guide) +- Read the [SDWebImage 4.0 Migration Guide](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/rs/SDWebImage/wiki/Common-Problems) to find the solution for common problems +- Go to the [Wiki Page](https://github.com/rs/SDWebImage/wiki) for more information such as [Advanced Usage](https://github.com/rs/SDWebImage/wiki/Advanced-Usage) + +## Who Uses It +- Find out [who uses SDWebImage](https://github.com/rs/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. +- If you **want to contribute**, submit a pull request. + +## 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](Docs/HowToUse.md) + +## Animated Images (GIF) support + +- Starting with the 4.0 version, we rely on [FLAnimatedImage](https://github.com/Flipboard/FLAnimatedImage) to take care of our animated images. +- If you use cocoapods, add `pod 'SDWebImage/GIF'` to your podfile. +- To use it, simply make sure you use `FLAnimatedImageView` instead of `UIImageView`. +- **Note**: there is a backwards compatible feature, so if you are still trying to load a GIF into a `UIImageView`, it will only show the 1st frame as a static image by default. However, you can enable the full GIF support by using the built-in GIF coder. See [GIF coder](https://github.com/rs/SDWebImage/wiki/Advanced-Usage#gif-coder) +- **Important**: FLAnimatedImage only works on the iOS platform. For macOS, use `NSImageView` with `animates` set to `YES` to show the entire animated images and `NO` to only show the 1st frame. For all the other platforms (tvOS, watchOS) we will fallback to the backwards compatibility feature described above + +## Installation + +There are three ways to use SDWebImage in your project: +- using CocoaPods +- using Carthage +- by cloning the project into your repository + +### 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, '7.0' +pod 'SDWebImage', '~> 4.0' +``` + +If you are using Swift, be sure to add `use_frameworks!` and set your target to iOS 8+: +``` +platform :ios, '8.0' +use_frameworks! +``` + +#### Subspecs + +There are 4 subspecs available now: `Core`, `MapKit`, `GIF` and `WebP` (this means you can install only some of the SDWebImage modules. By default, you get just `Core`, so if you need `WebP`, you need to specify it). + +Podfile example: +``` +pod 'SDWebImage/WebP' +``` + +### 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) + +#### Cartfile +``` +github "rs/SDWebImage" +``` + +### Installation by cloning the repository +- see [Manual install](Docs/ManualInstallation.md) + +### Import headers in your source files + +In the source files where you need to use the library, import the 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) + +## Licenses + +All source code is licensed under the [MIT License](https://raw.github.com/rs/SDWebImage/master/LICENSE). + +## Architecture + +

+ +

+ +

+ +

diff --git a/Pods/SDWebImage/SDWebImage/NSButton+WebCache.h b/Pods/SDWebImage/SDWebImage/NSButton+WebCache.h new file mode 100644 index 0000000..57f7115 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/NSButton+WebCache.h @@ -0,0 +1,259 @@ +/* + * 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" + +@interface NSButton (WebCache) + +#pragma mark - Image + +/** + * Get the current image URL. + */ +- (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`. + * + * 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 SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +#pragma mark - Alternate Image + +/** + * Get the current alternateImage URL. + */ +- (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`. + * + * 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 SDWebImageDownloaderProgressBlock)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/Pods/SDWebImage/SDWebImage/NSButton+WebCache.m b/Pods/SDWebImage/SDWebImage/NSButton+WebCache.m new file mode 100644 index 0000000..3ca080f --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/NSButton+WebCache.m @@ -0,0 +1,147 @@ +/* + * 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" + +static inline NSString * imageOperationKey() { + return @"NSButtonImageOperation"; +} + +static inline NSString * alternateImageOperationKey() { + return @"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 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 SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + self.sd_currentImageURL = url; + + __weak typeof(self)weakSelf = self; + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + operationKey:imageOperationKey() + setImageBlock:^(NSImage * _Nullable image, NSData * _Nullable imageData) { + weakSelf.image = image; + } + progress:progressBlock + completed:completedBlock]; +} + +#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 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 SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + self.sd_currentAlternateImageURL = url; + + __weak typeof(self)weakSelf = self; + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + operationKey:alternateImageOperationKey() + setImageBlock:^(NSImage * _Nullable image, NSData * _Nullable imageData) { + weakSelf.alternateImage = image; + } + progress:progressBlock + completed:completedBlock]; +} + +#pragma mark - Cancel + +- (void)sd_cancelCurrentImageLoad { + [self sd_cancelImageLoadOperationWithKey:imageOperationKey()]; +} + +- (void)sd_cancelCurrentAlternateImageLoad { + [self sd_cancelImageLoadOperationWithKey:alternateImageOperationKey()]; +} + +#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/Pods/SDWebImage/SDWebImage/NSData+ImageContentType.h b/Pods/SDWebImage/SDWebImage/NSData+ImageContentType.h new file mode 100644 index 0000000..d7e2142 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/NSData+ImageContentType.h @@ -0,0 +1,50 @@ +/* + * 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" + +typedef NS_ENUM(NSInteger, SDImageFormat) { + SDImageFormatUndefined = -1, + SDImageFormatJPEG = 0, + SDImageFormatPNG, + SDImageFormatGIF, + SDImageFormatTIFF, + SDImageFormatWebP, + SDImageFormatHEIC +}; + +@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_UTTypeFromSDImageFormat:(SDImageFormat)format; + +/** + * 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/Pods/SDWebImage/SDWebImage/NSData+ImageContentType.m b/Pods/SDWebImage/SDWebImage/NSData+ImageContentType.m new file mode 100644 index 0000000..64ea0a3 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/NSData+ImageContentType.m @@ -0,0 +1,121 @@ +/* + * 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 + +// Currently Image/IO does not support WebP +#define kSDUTTypeWebP ((__bridge CFStringRef)@"public.webp") +// AVFileTypeHEIC is defined in AVFoundation via iOS 11, we use this without import AVFoundation +#define kSDUTTypeHEIC ((__bridge CFStringRef)@"public.heic") + +@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; + } + } + break; + } + } + return SDImageFormatUndefined; +} + ++ (nonnull CFStringRef)sd_UTTypeFromSDImageFormat:(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; + 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 { + imageFormat = SDImageFormatUndefined; + } + return imageFormat; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/NSImage+WebCache.h b/Pods/SDWebImage/SDWebImage/NSImage+WebCache.h new file mode 100644 index 0000000..7515d40 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/NSImage+WebCache.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 + +#import + +@interface NSImage (WebCache) + +- (CGImageRef)CGImage; +- (NSArray *)images; +- (BOOL)isGIF; + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/NSImage+WebCache.m b/Pods/SDWebImage/SDWebImage/NSImage+WebCache.m new file mode 100644 index 0000000..140ed6c --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/NSImage+WebCache.m @@ -0,0 +1,41 @@ +/* + * 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+WebCache.h" + +#if SD_MAC + +@implementation NSImage (WebCache) + +- (CGImageRef)CGImage { + NSRect imageRect = NSMakeRect(0, 0, self.size.width, self.size.height); + CGImageRef cgImage = [self CGImageForProposedRect:&imageRect context:NULL hints:nil]; + return cgImage; +} + +- (NSArray *)images { + return nil; +} + +- (BOOL)isGIF { + BOOL isGIF = NO; + for (NSImageRep *rep in self.representations) { + if ([rep isKindOfClass:[NSBitmapImageRep class]]) { + NSBitmapImageRep *bitmapRep = (NSBitmapImageRep *)rep; + NSUInteger frameCount = [[bitmapRep valueForProperty:NSImageFrameCount] unsignedIntegerValue]; + isGIF = frameCount > 1 ? YES : NO; + break; + } + } + return isGIF; +} + +@end + +#endif + diff --git a/Pods/SDWebImage/SDWebImage/SDAnimatedImageRep.h b/Pods/SDWebImage/SDWebImage/SDAnimatedImageRep.h new file mode 100644 index 0000000..c794c4b --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDAnimatedImageRep.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" + +#if SD_MAC + +// A subclass of `NSBitmapImageRep` to fix that GIF loop count issue because `NSBitmapImageRep` will reset `NSImageCurrentFrameDuration` by using `kCGImagePropertyGIFDelayTime` but not `kCGImagePropertyGIFUnclampedDelayTime`. +// Built in GIF coder use this instead of `NSBitmapImageRep` for better GIF rendering. If you do not want this, only enable `SDWebImageImageIOCoder`, which just call `NSImage` API and actually use `NSBitmapImageRep` for GIF image. + +@interface SDAnimatedImageRep : NSBitmapImageRep + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/SDAnimatedImageRep.m b/Pods/SDWebImage/SDWebImage/SDAnimatedImageRep.m new file mode 100644 index 0000000..f0907d5 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDAnimatedImageRep.m @@ -0,0 +1,66 @@ +/* + * 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 "SDWebImageGIFCoder.h" + +@interface SDWebImageGIFCoder () + +- (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source; + +@end + +@interface SDAnimatedImageRep () + +@property (nonatomic, assign, readonly, nullable) CGImageSourceRef imageSource; + +@end + +@implementation SDAnimatedImageRep + +// `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 = self.imageSource; + if (!imageSource) { + return; + } + // Check format type + CFStringRef type = CGImageSourceGetType(imageSource); + if (!type) { + return; + } + NSUInteger index = [value unsignedIntegerValue]; + float frameDuration = 0; + // Through we currently process GIF only, in the 5.x we support APNG so we keep the extensibility + if (CFStringCompare(type, kUTTypeGIF, 0) == kCFCompareEqualTo) { + frameDuration = [[SDWebImageGIFCoder sharedCoder] sd_frameDurationAtIndex:index source:imageSource]; + } + if (!frameDuration) { + return; + } + // Reset super frame duration with the actual frame duration + [super setProperty:NSImageCurrentFrameDuration withValue:@(frameDuration)]; + } +} + +- (CGImageSourceRef)imageSource { + if (_tiffData) { + return (__bridge CGImageSourceRef)(_tiffData); + } + return NULL; +} + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/SDImageCache.h b/Pods/SDWebImage/SDWebImage/SDImageCache.h new file mode 100644 index 0000000..ce25989 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDImageCache.h @@ -0,0 +1,310 @@ +/* + * 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 "SDImageCacheConfig.h" + +typedef NS_ENUM(NSInteger, SDImageCacheType) { + /** + * The image wasn't available the SDWebImage caches, but was downloaded from the web. + */ + SDImageCacheTypeNone, + /** + * The image was obtained from the disk cache. + */ + SDImageCacheTypeDisk, + /** + * The image was obtained from the memory cache. + */ + SDImageCacheTypeMemory +}; + +typedef NS_OPTIONS(NSUInteger, SDImageCacheOptions) { + /** + * By default, we do not query disk data when the image is cached in memory. This mask can force to query disk data at the same time. + */ + SDImageCacheQueryDataWhenInMemory = 1 << 0, + /** + * By default, we query the memory cache synchronously, disk cache asynchronously. This mask can force to query disk cache synchronously. + */ + SDImageCacheQueryDiskSync = 1 << 1, + /** + * 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 << 2 +}; + +typedef void(^SDCacheQueryCompletedBlock)(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType); + +typedef void(^SDWebImageCheckCacheCompletionBlock)(BOOL isInCache); + +typedef void(^SDWebImageCalculateSizeBlock)(NSUInteger fileCount, NSUInteger totalSize); + + +/** + * SDImageCache maintains a memory cache and an optional 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 + */ +@property (nonatomic, nonnull, readonly) SDImageCacheConfig *config; + +/** + * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory. + */ +@property (assign, nonatomic) NSUInteger maxMemoryCost; + +/** + * The maximum number of objects the cache should hold. + */ +@property (assign, nonatomic) NSUInteger maxMemoryCountLimit; + +#pragma mark - Singleton and initialization + +/** + * Returns global shared cache instance + * + * @return SDImageCache global instance + */ ++ (nonnull instancetype)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 + * + * @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:(nonnull NSString *)directory NS_DESIGNATED_INITIALIZER; + +#pragma mark - Cache paths + +- (nullable NSString *)makeDiskCachePath:(nonnull NSString*)fullNamespace; + +/** + * Add a read-only cache path to search for images pre-cached by SDImageCache + * Useful if you want to bundle pre-loaded images with your app + * + * @param path The path to use for this read-only cache path + */ +- (void)addReadOnlyCachePath:(nonnull NSString *)path; + +#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 + * @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 + * @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 NSData 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 - Query and Retrieve Ops + +/** + * Async 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 SDWebImageCheckCacheCompletionBlock)completionBlock; + +/** + * Sync 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; + +/** + * 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 SDCacheQueryCompletedBlock)doneBlock; + +/** + * Operation that queries the cache asynchronously 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 SDCacheQueryCompletedBlock)doneBlock; + +/** + * Query the memory cache synchronously. + * + * @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; + +/** + * Query the disk cache synchronously. + * + * @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; + +/** + * Query the cache (memory and or disk) synchronously 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 + +/** + * Remove the image from memory and disk cache asynchronously + * + * @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; + +/** + * Remove the image from memory and optionally disk cache asynchronously + * + * @param key The unique image cache key + * @param fromDisk Also remove cache entry from disk if YES + * @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; + +#pragma mark - Cache clean Ops + +/** + * Clear all memory cached images + */ +- (void)clearMemory; + +/** + * Async 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; + +/** + * Async 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 size used by the disk cache + */ +- (NSUInteger)getSize; + +/** + * Get the number of images in the disk cache + */ +- (NSUInteger)getDiskCount; + +/** + * Asynchronously calculate the disk cache's size. + */ +- (void)calculateSizeWithCompletionBlock:(nullable SDWebImageCalculateSizeBlock)completionBlock; + +#pragma mark - Cache Paths + +/** + * Get the cache path for a certain key (needs the cache path root folder) + * + * @param key the key (can be obtained from url using cacheKeyForURL) + * @param path the cache path root folder + * + * @return the cache path + */ +- (nullable NSString *)cachePathForKey:(nullable NSString *)key inPath:(nonnull NSString *)path; + +/** + * Get the default cache path for a certain key + * + * @param key the key (can be obtained from url using cacheKeyForURL) + * + * @return the default cache path + */ +- (nullable NSString *)defaultCachePathForKey:(nullable NSString *)key; + +@end diff --git a/Pods/SDWebImage/SDWebImage/SDImageCache.m b/Pods/SDWebImage/SDWebImage/SDImageCache.m new file mode 100644 index 0000000..8e116d1 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDImageCache.m @@ -0,0 +1,811 @@ +/* + * 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 +#import "NSImage+WebCache.h" +#import "SDWebImageCodersManager.h" + +#define LOCK(lock) dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER); +#define UNLOCK(lock) dispatch_semaphore_signal(lock); + +FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) { +#if SD_MAC + return image.size.height * image.size.width; +#elif SD_UIKIT || SD_WATCH + return image.size.height * image.size.width * image.scale * image.scale; +#endif +} + +// A memory cache which auto purge the cache on memory warning and support weak cache. +@interface SDMemoryCache : NSCache + +@end + +// Private +@interface SDMemoryCache () + +@property (nonatomic, strong, nonnull) SDImageCacheConfig *config; +@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 + +- (instancetype)init NS_UNAVAILABLE; +- (instancetype)initWithConfig:(nonnull SDImageCacheConfig *)config; + +@end + +@implementation SDMemoryCache + +// 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. +// But in the future there may be more options and features for this subclass. +#if SD_UIKIT + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil]; +} + +- (instancetype)initWithConfig:(SDImageCacheConfig *)config { + self = [super init]; + if (self) { + // Use a strong-weak maptable storing the secondary cache. Follow the doc that NSCache does not copy keys + // This is useful when the memory warning, the cache was purged. However, the image instance can be retained by other instance such as imageViews and alive. + // At this case, we can sync weak cache back and do not need to load from disk cache + self.weakCache = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0]; + self.weakCacheLock = dispatch_semaphore_create(1); + self.config = config; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(didReceiveMemoryWarning:) + name:UIApplicationDidReceiveMemoryWarningNotification + object:nil]; + } + return self; +} + +- (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 + LOCK(self.weakCacheLock); + [self.weakCache setObject:obj forKey:key]; + UNLOCK(self.weakCacheLock); + } +} + +- (id)objectForKey:(id)key { + id obj = [super objectForKey:key]; + if (!self.config.shouldUseWeakMemoryCache) { + return obj; + } + if (key && !obj) { + // Check weak cache + LOCK(self.weakCacheLock); + obj = [self.weakCache objectForKey:key]; + UNLOCK(self.weakCacheLock); + if (obj) { + // Sync cache + NSUInteger cost = 0; + if ([obj isKindOfClass:[UIImage class]]) { + cost = SDCacheCostForImage(obj); + } + [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 + LOCK(self.weakCacheLock); + [self.weakCache removeObjectForKey:key]; + UNLOCK(self.weakCacheLock); + } +} + +- (void)removeAllObjects { + [super removeAllObjects]; + if (!self.config.shouldUseWeakMemoryCache) { + return; + } + // Manually remove should also remove weak cache + LOCK(self.weakCacheLock); + [self.weakCache removeAllObjects]; + UNLOCK(self.weakCacheLock); +} + +#else + +- (instancetype)initWithConfig:(SDImageCacheConfig *)config { + self = [super init]; + return self; +} + +#endif + +@end + +@interface SDImageCache () + +#pragma mark - Properties +@property (strong, nonatomic, nonnull) SDMemoryCache *memCache; +@property (strong, nonatomic, nonnull) NSString *diskCachePath; +@property (strong, nonatomic, nullable) NSMutableArray *customPaths; +@property (strong, nonatomic, nullable) dispatch_queue_t ioQueue; +@property (strong, nonatomic, nonnull) NSFileManager *fileManager; + +@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 { + NSString *path = [self makeDiskCachePath:ns]; + return [self initWithNamespace:ns diskCacheDirectory:path]; +} + +- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns + diskCacheDirectory:(nonnull NSString *)directory { + if ((self = [super init])) { + NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns]; + + // Create IO serial queue + _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL); + + _config = [[SDImageCacheConfig alloc] init]; + + // Init the memory cache + _memCache = [[SDMemoryCache alloc] initWithConfig:_config]; + _memCache.name = fullNamespace; + + // Init the disk cache + if (directory != nil) { + _diskCachePath = [directory stringByAppendingPathComponent:fullNamespace]; + } else { + NSString *path = [self makeDiskCachePath:ns]; + _diskCachePath = path; + } + + dispatch_sync(_ioQueue, ^{ + self.fileManager = [NSFileManager new]; + }); + +#if SD_UIKIT + // Subscribe to app events + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(deleteOldFiles) + name:UIApplicationWillTerminateNotification + object:nil]; + + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(backgroundDeleteOldFiles) + name:UIApplicationDidEnterBackgroundNotification + object:nil]; +#endif + } + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +#pragma mark - Cache paths + +- (void)addReadOnlyCachePath:(nonnull NSString *)path { + if (!self.customPaths) { + self.customPaths = [NSMutableArray new]; + } + + if (![self.customPaths containsObject:path]) { + [self.customPaths addObject:path]; + } +} + +- (nullable NSString *)cachePathForKey:(nullable NSString *)key inPath:(nonnull NSString *)path { + NSString *filename = [self cachedFileNameForKey:key]; + return [path stringByAppendingPathComponent:filename]; +} + +- (nullable NSString *)defaultCachePathForKey:(nullable NSString *)key { + return [self cachePathForKey:key inPath:self.diskCachePath]; +} + +- (nullable NSString *)cachedFileNameForKey:(nullable NSString *)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; + 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; +} + +- (nullable NSString *)makeDiskCachePath:(nonnull NSString*)fullNamespace { + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); + return [paths[0] stringByAppendingPathComponent:fullNamespace]; +} + +#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 { + if (!image || !key) { + if (completionBlock) { + completionBlock(); + } + return; + } + // if memory cache is enabled + if (self.config.shouldCacheImagesInMemory) { + NSUInteger cost = SDCacheCostForImage(image); + [self.memCache 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 (SDCGImageRefContainsAlpha(image.CGImage)) { + format = SDImageFormatPNG; + } else { + format = SDImageFormatJPEG; + } + data = [[SDWebImageCodersManager sharedInstance] encodedDataWithImage:image format:format]; + } + [self _storeImageDataToDisk:data forKey:key]; + } + + if (completionBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + completionBlock(); + }); + } + }); + } else { + if (completionBlock) { + completionBlock(); + } + } +} + +- (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; + } + + if (![self.fileManager fileExistsAtPath:_diskCachePath]) { + [self.fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL]; + } + + // get cache Path for image key + NSString *cachePathForKey = [self defaultCachePathForKey:key]; + // transform to NSUrl + NSURL *fileURL = [NSURL fileURLWithPath:cachePathForKey]; + + [imageData writeToURL:fileURL options:self.config.diskCacheWritingOptions error:nil]; + + // disable iCloud backup + if (self.config.shouldDisableiCloud) { + [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil]; + } +} + +#pragma mark - Query and Retrieve Ops + +- (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDWebImageCheckCacheCompletionBlock)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; + } + BOOL exists = [self.fileManager fileExistsAtPath:[self defaultCachePathForKey:key]]; + + // 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:[self defaultCachePathForKey:key].stringByDeletingPathExtension]; + } + + return exists; +} + +- (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.memCache objectForKey:key]; +} + +- (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key { + UIImage *diskImage = [self diskImageForKey:key]; + if (diskImage && self.config.shouldCacheImagesInMemory) { + NSUInteger cost = SDCacheCostForImage(diskImage); + [self.memCache 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 { + NSString *defaultPath = [self defaultCachePathForKey:key]; + NSData *data = [NSData dataWithContentsOfFile:defaultPath 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:defaultPath.stringByDeletingPathExtension options:self.config.diskCacheReadingOptions error:nil]; + if (data) { + return data; + } + + NSArray *customPaths = [self.customPaths copy]; + for (NSString *path in customPaths) { + NSString *filePath = [self cachePathForKey:key inPath:path]; + NSData *imageData = [NSData dataWithContentsOfFile:filePath options:self.config.diskCacheReadingOptions error:nil]; + if (imageData) { + return imageData; + } + + // 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 + imageData = [NSData dataWithContentsOfFile:filePath.stringByDeletingPathExtension options:self.config.diskCacheReadingOptions error:nil]; + if (imageData) { + return imageData; + } + } + + return nil; +} + +- (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]; +} + +- (nullable UIImage *)diskImageForKey:(nullable NSString *)key data:(nullable NSData *)data options:(SDImageCacheOptions)options { + if (data) { + UIImage *image = [[SDWebImageCodersManager sharedInstance] decodedImageWithData:data]; + image = [self scaledImageForKey:key image:image]; + if (self.config.shouldDecompressImages) { + BOOL shouldScaleDown = options & SDImageCacheScaleDownLargeImages; + image = [[SDWebImageCodersManager sharedInstance] decompressedImageWithImage:image data:&data options:@{SDWebImageCoderScaleDownLargeImagesKey: @(shouldScaleDown)}]; + } + return image; + } else { + return nil; + } +} + +- (nullable UIImage *)scaledImageForKey:(nullable NSString *)key image:(nullable UIImage *)image { + return SDScaledImageForKey(key, image); +} + +- (NSOperation *)queryCacheOperationForKey:(NSString *)key done:(SDCacheQueryCompletedBlock)doneBlock { + return [self queryCacheOperationForKey:key options:0 done:doneBlock]; +} + +- (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options done:(nullable SDCacheQueryCompletedBlock)doneBlock { + if (!key) { + if (doneBlock) { + doneBlock(nil, nil, SDImageCacheTypeNone); + } + return nil; + } + + // First check the in-memory cache... + UIImage *image = [self imageFromMemoryCacheForKey:key]; + BOOL shouldQueryMemoryOnly = (image && !(options & SDImageCacheQueryDataWhenInMemory)); + if (shouldQueryMemoryOnly) { + if (doneBlock) { + doneBlock(image, nil, SDImageCacheTypeMemory); + } + return nil; + } + + NSOperation *operation = [NSOperation new]; + void(^queryDiskBlock)(void) = ^{ + if (operation.isCancelled) { + // do not call the completion if cancelled + return; + } + + @autoreleasepool { + NSData *diskData = [self diskImageDataBySearchingAllPathsForKey:key]; + UIImage *diskImage; + SDImageCacheType cacheType = SDImageCacheTypeDisk; + if (image) { + // the image is from in-memory cache + diskImage = image; + cacheType = SDImageCacheTypeMemory; + } else if (diskData) { + // decode image data only if in-memory cache missed + diskImage = [self diskImageForKey:key data:diskData options:options]; + if (diskImage && self.config.shouldCacheImagesInMemory) { + NSUInteger cost = SDCacheCostForImage(diskImage); + [self.memCache setObject:diskImage forKey:key cost:cost]; + } + } + + if (doneBlock) { + if (options & SDImageCacheQueryDiskSync) { + doneBlock(diskImage, diskData, cacheType); + } else { + dispatch_async(dispatch_get_main_queue(), ^{ + doneBlock(diskImage, diskData, cacheType); + }); + } + } + } + }; + + if (options & SDImageCacheQueryDiskSync) { + 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 { + if (key == nil) { + return; + } + + if (self.config.shouldCacheImagesInMemory) { + [self.memCache removeObjectForKey:key]; + } + + if (fromDisk) { + dispatch_async(self.ioQueue, ^{ + [self.fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil]; + + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(); + }); + } + }); + } else if (completion){ + completion(); + } + +} + +# pragma mark - Mem Cache settings + +- (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost { + self.memCache.totalCostLimit = maxMemoryCost; +} + +- (NSUInteger)maxMemoryCost { + return self.memCache.totalCostLimit; +} + +- (NSUInteger)maxMemoryCountLimit { + return self.memCache.countLimit; +} + +- (void)setMaxMemoryCountLimit:(NSUInteger)maxCountLimit { + self.memCache.countLimit = maxCountLimit; +} + +#pragma mark - Cache clean Ops + +- (void)clearMemory { + [self.memCache removeAllObjects]; +} + +- (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion { + dispatch_async(self.ioQueue, ^{ + [self.fileManager removeItemAtPath:self.diskCachePath error:nil]; + [self.fileManager createDirectoryAtPath:self.diskCachePath + withIntermediateDirectories:YES + attributes:nil + error:NULL]; + + if (completion) { + dispatch_async(dispatch_get_main_queue(), ^{ + completion(); + }); + } + }); +} + +- (void)deleteOldFiles { + [self deleteOldFilesWithCompletionBlock:nil]; +} + +- (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock { + dispatch_async(self.ioQueue, ^{ + 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; + + 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 = [NSDate dateWithTimeIntervalSinceNow:-self.config.maxCacheAge]; + 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 ([[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. + if (self.config.maxCacheSize > 0 && currentCacheSize > self.config.maxCacheSize) { + // Target half of our maximum cache size for this cleanup pass. + const NSUInteger desiredCacheSize = self.config.maxCacheSize / 2; + + // Sort the remaining cache files by their last modification time (oldest first). + NSArray *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent + usingComparator:^NSComparisonResult(id obj1, id obj2) { + return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]]; + }]; + + // 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; + } + } + } + } + if (completionBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + completionBlock(); + }); + } + }); +} + +#if SD_UIKIT +- (void)backgroundDeleteOldFiles { + 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)getSize { + __block NSUInteger size = 0; + dispatch_sync(self.ioQueue, ^{ + 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)getDiskCount { + __block NSUInteger count = 0; + dispatch_sync(self.ioQueue, ^{ + NSDirectoryEnumerator *fileEnumerator = [self.fileManager enumeratorAtPath:self.diskCachePath]; + count = fileEnumerator.allObjects.count; + }); + return count; +} + +- (void)calculateSizeWithCompletionBlock:(nullable SDWebImageCalculateSizeBlock)completionBlock { + NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES]; + + dispatch_async(self.ioQueue, ^{ + NSUInteger fileCount = 0; + NSUInteger totalSize = 0; + + NSDirectoryEnumerator *fileEnumerator = [self.fileManager enumeratorAtURL:diskCacheURL + includingPropertiesForKeys:@[NSFileSize] + options:NSDirectoryEnumerationSkipsHiddenFiles + errorHandler:NULL]; + + for (NSURL *fileURL in fileEnumerator) { + NSNumber *fileSize; + [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL]; + totalSize += fileSize.unsignedIntegerValue; + fileCount += 1; + } + + if (completionBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + completionBlock(fileCount, totalSize); + }); + } + }); +} + +@end + diff --git a/Pods/SDWebImage/SDWebImage/SDImageCacheConfig.h b/Pods/SDWebImage/SDWebImage/SDImageCacheConfig.h new file mode 100644 index 0000000..c0de688 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDImageCacheConfig.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 +#import "SDWebImageCompat.h" + +typedef NS_ENUM(NSUInteger, SDImageCacheConfigExpireType) { + /** + * When the image is accessed it will update this value + */ + SDImageCacheConfigExpireTypeAccessDate, + /** + * The image was obtained from the disk cache (Default) + */ + SDImageCacheConfigExpireTypeModificationDate +}; + +@interface SDImageCacheConfig : NSObject + +/** + * Decompressing images that are downloaded and cached can improve performance but can consume lot of memory. + * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. + */ +@property (assign, nonatomic) BOOL shouldDecompressImages; + +/** + * 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 instacnce, 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; + +/** + * 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 cache, in seconds. + */ +@property (assign, nonatomic) NSInteger maxCacheAge; + +/** + * The maximum size of the cache, in bytes. + */ +@property (assign, nonatomic) NSUInteger maxCacheSize; + +/** + * The attribute which the clear cache will be checked against when clearing the disk cache + * Default is Modified Date + */ +@property (assign, nonatomic) SDImageCacheConfigExpireType diskCacheExpireType; + +@end diff --git a/Pods/SDWebImage/SDWebImage/SDImageCacheConfig.m b/Pods/SDWebImage/SDWebImage/SDImageCacheConfig.m new file mode 100644 index 0000000..d4f4dd2 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDImageCacheConfig.m @@ -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 "SDImageCacheConfig.h" + +static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week + +@implementation SDImageCacheConfig + +- (instancetype)init { + if (self = [super init]) { + _shouldDecompressImages = YES; + _shouldDisableiCloud = YES; + _shouldCacheImagesInMemory = YES; + _shouldUseWeakMemoryCache = YES; + _diskCacheReadingOptions = 0; + _diskCacheWritingOptions = NSDataWritingAtomic; + _maxCacheAge = kDefaultCacheMaxCacheAge; + _maxCacheSize = 0; + _diskCacheExpireType = SDImageCacheConfigExpireTypeModificationDate; + } + return self; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageCoder.h b/Pods/SDWebImage/SDWebImage/SDWebImageCoder.h new file mode 100644 index 0000000..7c0a63f --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageCoder.h @@ -0,0 +1,119 @@ +/* + * 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" + +/** + A Boolean value indicating whether to scale down large images during decompressing. (NSNumber) + */ +FOUNDATION_EXPORT NSString * _Nonnull const SDWebImageCoderScaleDownLargeImagesKey; + +/** + Return the shared device-dependent RGB color space created with CGColorSpaceCreateDeviceRGB. + + @return The device-dependent RGB color space + */ +CG_EXTERN CGColorSpaceRef _Nonnull SDCGColorSpaceGetDeviceRGB(void); + +/** + Check whether CGImageRef contains alpha channel. + + @param imageRef The CGImageRef + @return Return YES if CGImageRef contains alpha channel, otherwise return NO + */ +CG_EXTERN BOOL SDCGImageRefContainsAlpha(_Nullable CGImageRef imageRef); + + +/** + 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 SDWebImageCoder + +@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. + + @param data The image data to be decoded + @return The decoded image from data + */ +- (nullable UIImage *)decodedImageWithData:(nullable NSData *)data; + +/** + Decompress the image with original image and image data. + + @param image The original image to be decompressed + @param data The pointer to original image data. The pointer itself is nonnull but image data can be null. This data will set to cache if needed. If you do not need to modify data at the sametime, ignore this param. + @param optionsDict A dictionary containing any decompressing options. Pass {SDWebImageCoderScaleDownLargeImagesKey: @(YES)} to scale down large images + @return The decompressed image + */ +- (nullable UIImage *)decompressedImageWithImage:(nullable UIImage *)image + data:(NSData * _Nullable * _Nonnull)data + options:(nullable NSDictionary*)optionsDict; + +#pragma mark - Encoding + +/** + Returns YES if this coder can encode some image. Otherwise, it should be passed to another coder. + + @param format The image format + @return YES if this coder can encode the image, NO otherwise + */ +- (BOOL)canEncodeToFormat:(SDImageFormat)format; + +/** + Encode the image to image data. + + @param image The image to be encoded + @param format The image format to encode, you should note `SDImageFormatUndefined` format is also possible + @return The encoded image data + */ +- (nullable NSData *)encodedDataWithImage:(nullable UIImage *)image format:(SDImageFormat)format; + +@end + + +/** + 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 SDWebImageProgressiveCoder + +@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)canIncrementallyDecodeFromData:(nullable NSData *)data; + +/** + Incremental decode the image data to image. + + @param data The image data has been downloaded so far + @param finished Whether the download has finished + @warning 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 + @return The decoded image from data + */ +- (nullable UIImage *)incrementallyDecodedImageWithData:(nullable NSData *)data finished:(BOOL)finished; + +@end diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageCoder.m b/Pods/SDWebImage/SDWebImage/SDWebImageCoder.m new file mode 100644 index 0000000..9357fe5 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageCoder.m @@ -0,0 +1,31 @@ +/* + * 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 "SDWebImageCoder.h" + +NSString * const SDWebImageCoderScaleDownLargeImagesKey = @"scaleDownLargeImages"; + +CGColorSpaceRef SDCGColorSpaceGetDeviceRGB(void) { + static CGColorSpaceRef colorSpace; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + colorSpace = CGColorSpaceCreateDeviceRGB(); + }); + return colorSpace; +} + +BOOL SDCGImageRefContainsAlpha(CGImageRef imageRef) { + if (!imageRef) { + return NO; + } + CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef); + BOOL hasAlpha = !(alphaInfo == kCGImageAlphaNone || + alphaInfo == kCGImageAlphaNoneSkipFirst || + alphaInfo == kCGImageAlphaNoneSkipLast); + return hasAlpha; +} diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageCoderHelper.h b/Pods/SDWebImage/SDWebImage/SDWebImageCoderHelper.h new file mode 100644 index 0000000..ad2fe85 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageCoderHelper.h @@ -0,0 +1,52 @@ +/* + * 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 "SDWebImageFrame.h" + +@interface SDWebImageCoderHelper : 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; + +#if SD_UIKIT || SD_WATCH +/** + Convert an EXIF image orientation to an iOS one. + + @param exifOrientation EXIF orientation + @return iOS orientation + */ ++ (UIImageOrientation)imageOrientationFromEXIFOrientation:(NSInteger)exifOrientation; +/** + Convert an iOS orientation to an EXIF image orientation. + + @param imageOrientation iOS orientation + @return EXIF orientation + */ ++ (NSInteger)exifOrientationFromImageOrientation:(UIImageOrientation)imageOrientation; +#endif + +@end diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageCoderHelper.m b/Pods/SDWebImage/SDWebImage/SDWebImageCoderHelper.m new file mode 100644 index 0000000..ea1dae1 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageCoderHelper.m @@ -0,0 +1,258 @@ +/* + * 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 "SDWebImageCoderHelper.h" +#import "SDWebImageFrame.h" +#import "UIImage+MultiFormat.h" +#import "NSImage+WebCache.h" +#import +#import "SDAnimatedImageRep.h" + +@implementation SDWebImageCoderHelper + ++ (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:^(SDWebImageFrame * _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_UTTypeFromSDImageFormat: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 { + SDWebImageFrame *frame = frames[i]; + float 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); + SDAnimatedImageRep *imageRep = [[SDAnimatedImageRep alloc] initWithData:imageData]; + animatedImage = [[NSImage alloc] initWithSize:imageRep.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 { + SDWebImageFrame *frame = [SDWebImageFrame frameWithImage:previousImage duration:avgDuration * repeatCount]; + [frames addObject:frame]; + repeatCount = 1; + index++; + } + previousImage = image; + // last one + if (idx == frameCount - 1) { + SDWebImageFrame *frame = [SDWebImageFrame frameWithImage:previousImage duration:avgDuration * repeatCount]; + [frames addObject:frame]; + } + }]; + +#else + + NSBitmapImageRep *bitmapRep; + for (NSImageRep *imageRep in animatedImage.representations) { + if ([imageRep isKindOfClass:[NSBitmapImageRep class]]) { + bitmapRep = (NSBitmapImageRep *)imageRep; + break; + } + } + if (bitmapRep) { + frameCount = [[bitmapRep valueForProperty:NSImageFrameCount] unsignedIntegerValue]; + } + + if (frameCount == 0) { + return nil; + } + + for (size_t i = 0; i < frameCount; i++) { + @autoreleasepool { + // NSBitmapImageRep need to manually change frame. "Good taste" API + [bitmapRep setProperty:NSImageCurrentFrame withValue:@(i)]; + float frameDuration = [[bitmapRep valueForProperty:NSImageCurrentFrameDuration] floatValue]; + NSImage *frameImage = [[NSImage alloc] initWithCGImage:bitmapRep.CGImage size:CGSizeZero]; + SDWebImageFrame *frame = [SDWebImageFrame frameWithImage:frameImage duration:frameDuration]; + [frames addObject:frame]; + } + } +#endif + + return frames; +} + +#if SD_UIKIT || SD_WATCH +// Convert an EXIF image orientation to an iOS one. ++ (UIImageOrientation)imageOrientationFromEXIFOrientation:(NSInteger)exifOrientation { + // CGImagePropertyOrientation is available on iOS 8 above. Currently kept for compatibility + UIImageOrientation imageOrientation = UIImageOrientationUp; + switch (exifOrientation) { + case 1: + imageOrientation = UIImageOrientationUp; + break; + case 3: + imageOrientation = UIImageOrientationDown; + break; + case 8: + imageOrientation = UIImageOrientationLeft; + break; + case 6: + imageOrientation = UIImageOrientationRight; + break; + case 2: + imageOrientation = UIImageOrientationUpMirrored; + break; + case 4: + imageOrientation = UIImageOrientationDownMirrored; + break; + case 5: + imageOrientation = UIImageOrientationLeftMirrored; + break; + case 7: + imageOrientation = UIImageOrientationRightMirrored; + break; + default: + break; + } + return imageOrientation; +} + +// Convert an iOS orientation to an EXIF image orientation. ++ (NSInteger)exifOrientationFromImageOrientation:(UIImageOrientation)imageOrientation { + // CGImagePropertyOrientation is available on iOS 8 above. Currently kept for compatibility + NSInteger exifOrientation = 1; + switch (imageOrientation) { + case UIImageOrientationUp: + exifOrientation = 1; + break; + case UIImageOrientationDown: + exifOrientation = 3; + break; + case UIImageOrientationLeft: + exifOrientation = 8; + break; + case UIImageOrientationRight: + exifOrientation = 6; + break; + case UIImageOrientationUpMirrored: + exifOrientation = 2; + break; + case UIImageOrientationDownMirrored: + exifOrientation = 4; + break; + case UIImageOrientationLeftMirrored: + exifOrientation = 5; + break; + case UIImageOrientationRightMirrored: + exifOrientation = 7; + break; + default: + break; + } + return exifOrientation; +} +#endif + +#pragma mark - Helper Fuction +#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/Pods/SDWebImage/SDWebImage/SDWebImageCodersManager.h b/Pods/SDWebImage/SDWebImage/SDWebImageCodersManager.h new file mode 100644 index 0000000..ca68748 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageCodersManager.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 "SDWebImageCoder.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`, `WebPCoder`. (`GIFCoder` is not recommended to add only if you want to get GIF support without `FLAnimatedImage`) + - calling `coders` will return `@[WebPCoder, IOCoder]` + - call `[addCoder:[MyCrazyCoder new]]` + - calling `coders` now returns `@[MyCrazyCoder, WebPCoder, IOCoder]` + + Coders + ------ + A coder must conform to the `SDWebImageCoder` protocol or even to `SDWebImageProgressiveCoder` 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 SDWebImageCodersManager : NSObject + +/** + Shared reusable instance + */ ++ (nonnull instancetype)sharedInstance; + +/** + 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, readwrite, 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/Pods/SDWebImage/SDWebImage/SDWebImageCodersManager.m b/Pods/SDWebImage/SDWebImage/SDWebImageCodersManager.m new file mode 100644 index 0000000..883d1fd --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageCodersManager.m @@ -0,0 +1,148 @@ +/* + * 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 "SDWebImageCodersManager.h" +#import "SDWebImageImageIOCoder.h" +#import "SDWebImageGIFCoder.h" +#ifdef SD_WEBP +#import "SDWebImageWebPCoder.h" +#endif +#import "UIImage+MultiFormat.h" + +#define LOCK(lock) dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER); +#define UNLOCK(lock) dispatch_semaphore_signal(lock); + +@interface SDWebImageCodersManager () + +@property (nonatomic, strong, nonnull) dispatch_semaphore_t codersLock; + +@end + +@implementation SDWebImageCodersManager + ++ (nonnull instancetype)sharedInstance { + 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 + NSMutableArray> *mutableCoders = [@[[SDWebImageImageIOCoder sharedCoder]] mutableCopy]; +#ifdef SD_WEBP + [mutableCoders addObject:[SDWebImageWebPCoder sharedCoder]]; +#endif + _coders = [mutableCoders copy]; + _codersLock = dispatch_semaphore_create(1); + } + return self; +} + +#pragma mark - Coder IO operations + +- (void)addCoder:(nonnull id)coder { + if (![coder conformsToProtocol:@protocol(SDWebImageCoder)]) { + return; + } + LOCK(self.codersLock); + NSMutableArray> *mutableCoders = [self.coders mutableCopy]; + if (!mutableCoders) { + mutableCoders = [NSMutableArray array]; + } + [mutableCoders addObject:coder]; + self.coders = [mutableCoders copy]; + UNLOCK(self.codersLock); +} + +- (void)removeCoder:(nonnull id)coder { + if (![coder conformsToProtocol:@protocol(SDWebImageCoder)]) { + return; + } + LOCK(self.codersLock); + NSMutableArray> *mutableCoders = [self.coders mutableCopy]; + [mutableCoders removeObject:coder]; + self.coders = [mutableCoders copy]; + UNLOCK(self.codersLock); +} + +#pragma mark - SDWebImageCoder +- (BOOL)canDecodeFromData:(NSData *)data { + LOCK(self.codersLock); + NSArray> *coders = self.coders; + UNLOCK(self.codersLock); + for (id coder in coders.reverseObjectEnumerator) { + if ([coder canDecodeFromData:data]) { + return YES; + } + } + return NO; +} + +- (BOOL)canEncodeToFormat:(SDImageFormat)format { + LOCK(self.codersLock); + NSArray> *coders = self.coders; + UNLOCK(self.codersLock); + for (id coder in coders.reverseObjectEnumerator) { + if ([coder canEncodeToFormat:format]) { + return YES; + } + } + return NO; +} + +- (UIImage *)decodedImageWithData:(NSData *)data { + LOCK(self.codersLock); + NSArray> *coders = self.coders; + UNLOCK(self.codersLock); + for (id coder in coders.reverseObjectEnumerator) { + if ([coder canDecodeFromData:data]) { + return [coder decodedImageWithData:data]; + } + } + return nil; +} + +- (UIImage *)decompressedImageWithImage:(UIImage *)image + data:(NSData *__autoreleasing _Nullable *)data + options:(nullable NSDictionary*)optionsDict { + if (!image) { + return nil; + } + LOCK(self.codersLock); + NSArray> *coders = self.coders; + UNLOCK(self.codersLock); + for (id coder in coders.reverseObjectEnumerator) { + if ([coder canDecodeFromData:*data]) { + UIImage *decompressedImage = [coder decompressedImageWithImage:image data:data options:optionsDict]; + decompressedImage.sd_imageFormat = image.sd_imageFormat; + return decompressedImage; + } + } + return nil; +} + +- (NSData *)encodedDataWithImage:(UIImage *)image format:(SDImageFormat)format { + if (!image) { + return nil; + } + LOCK(self.codersLock); + NSArray> *coders = self.coders; + UNLOCK(self.codersLock); + for (id coder in coders.reverseObjectEnumerator) { + if ([coder canEncodeToFormat:format]) { + return [coder encodedDataWithImage:image format:format]; + } + } + return nil; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageCompat.h b/Pods/SDWebImage/SDWebImage/SDWebImageCompat.h new file mode 100644 index 0000000..a4493ae --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageCompat.h @@ -0,0 +1,107 @@ +/* + * 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 + +// Apple's defines from TargetConditionals.h are a bit weird. +// Seems like TARGET_OS_MAC is always defined (on all platforms). +// To determine if we are running on OSX, we can only rely on TARGET_OS_IPHONE=0 and all the other platforms +#if !TARGET_OS_IPHONE && !TARGET_OS_IOS && !TARGET_OS_TV && !TARGET_OS_WATCH + #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 +#else + #if __IPHONE_OS_VERSION_MIN_REQUIRED != 20000 && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_5_0 + #error SDWebImage doesn't support Deployment Target version < 5.0 + #endif + + #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 + +FOUNDATION_EXPORT UIImage *SDScaledImageForKey(NSString *key, UIImage *image); + +typedef void(^SDWebImageNoParamsBlock)(void); + +FOUNDATION_EXPORT NSString *const SDWebImageErrorDomain; + +#ifndef dispatch_queue_async_safe +#define dispatch_queue_async_safe(queue, block)\ + if (dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL) == dispatch_queue_get_label(queue)) {\ + block();\ + } else {\ + dispatch_async(queue, block);\ + } +#endif + +#ifndef dispatch_main_async_safe +#define dispatch_main_async_safe(block) dispatch_queue_async_safe(dispatch_get_main_queue(), block) +#endif diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageCompat.m b/Pods/SDWebImage/SDWebImage/SDWebImageCompat.m new file mode 100644 index 0000000..daee7fc --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageCompat.m @@ -0,0 +1,69 @@ +/* + * 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+MultiFormat.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 + +inline UIImage *SDScaledImageForKey(NSString * _Nullable key, UIImage * _Nullable image) { + if (!image) { + return nil; + } + +#if SD_MAC + return image; +#elif SD_UIKIT || SD_WATCH + if ((image.images).count > 0) { + NSMutableArray *scaledImages = [NSMutableArray array]; + + for (UIImage *tempImage in image.images) { + [scaledImages addObject:SDScaledImageForKey(key, tempImage)]; + } + + UIImage *animatedImage = [UIImage animatedImageWithImages:scaledImages duration:image.duration]; + if (animatedImage) { + animatedImage.sd_imageLoopCount = image.sd_imageLoopCount; + animatedImage.sd_imageFormat = image.sd_imageFormat; + } + return animatedImage; + } else { +#if SD_WATCH + if ([[WKInterfaceDevice currentDevice] respondsToSelector:@selector(screenScale)]) { +#elif SD_UIKIT + if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) { +#endif + CGFloat scale = 1; + if (key.length >= 8) { + NSRange range = [key rangeOfString:@"@2x."]; + if (range.location != NSNotFound) { + scale = 2.0; + } + + range = [key rangeOfString:@"@3x."]; + if (range.location != NSNotFound) { + scale = 3.0; + } + } + + UIImage *scaledImage = [[UIImage alloc] initWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation]; + scaledImage.sd_imageFormat = image.sd_imageFormat; + image = scaledImage; + } + return image; + } +#endif +} + +NSString *const SDWebImageErrorDomain = @"SDWebImageErrorDomain"; diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageDownloader.h b/Pods/SDWebImage/SDWebImage/SDWebImageDownloader.h new file mode 100644 index 0000000..b5911af --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageDownloader.h @@ -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 +#import "SDWebImageCompat.h" +#import "SDWebImageOperation.h" + +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. + */ + SDWebImageDownloaderProgressiveDownload = 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 + * (to 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, + + /** + * Scale down the image + */ + SDWebImageDownloaderScaleDownLargeImages = 1 << 8, +}; + +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 +}; + +FOUNDATION_EXPORT NSString * _Nonnull const SDWebImageDownloadStartNotification; +FOUNDATION_EXPORT NSString * _Nonnull const SDWebImageDownloadStopNotification; + +typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL); + +typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished); + +typedef NSDictionary SDHTTPHeadersDictionary; +typedef NSMutableDictionary SDHTTPHeadersMutableDictionary; + +typedef SDHTTPHeadersDictionary * _Nullable (^SDWebImageDownloaderHeadersFilterBlock)(NSURL * _Nullable url, SDHTTPHeadersDictionary * _Nullable headers); + +/** + * A token associated with each download. Can be used to cancel a download + */ +@interface SDWebImageDownloadToken : NSObject + +/** + The download's URL. This should be readonly and you should not modify + */ +@property (nonatomic, strong, nullable) NSURL *url; +/** + The cancel token taken from `addHandlersForProgress:completed`. This should be readonly and you should not modify + @note use `-[SDWebImageDownloadToken cancel]` to cancel the token + */ +@property (nonatomic, strong, nullable) id downloadOperationCancelToken; + +@end + + +/** + * Asynchronous downloader dedicated and optimized for image loading. + */ +@interface SDWebImageDownloader : NSObject + +/** + * Decompressing images that are downloaded and cached can improve performance but can consume lot of memory. + * Defaults to YES. Set this to NO if you are experiencing a crash due to excessive memory consumption. + */ +@property (assign, nonatomic) BOOL shouldDecompressImages; + +/** + * The maximum number of concurrent downloads + */ +@property (assign, nonatomic) NSInteger maxConcurrentDownloads; + +/** + * Shows the current amount of downloads that still need to be downloaded + */ +@property (readonly, nonatomic) NSUInteger currentDownloadCount; + +/** + * The timeout value (in seconds) for the download operation. Default: 15.0. + */ +@property (assign, nonatomic) NSTimeInterval downloadTimeout; + +/** + * The configuration in use by the internal NSURLSession. + * Mutating this object directly has no effect. + * + * @see createNewSessionWithConfiguration: + */ +@property (readonly, nonatomic, nonnull) NSURLSessionConfiguration *sessionConfiguration; + + +/** + * Changes download operations execution order. Default value is `SDWebImageDownloaderFIFOExecutionOrder`. + */ +@property (assign, nonatomic) SDWebImageDownloaderExecutionOrder executionOrder; + +/** + * Singleton method, returns the shared instance + * + * @return global shared instance of downloader class + */ ++ (nonnull instancetype)sharedDownloader; + +/** + * Set the default URL credential to be set for request operations. + */ +@property (strong, nonatomic, nullable) NSURLCredential *urlCredential; + +/** + * Set username + */ +@property (strong, nonatomic, nullable) NSString *username; + +/** + * Set password + */ +@property (strong, nonatomic, nullable) NSString *password; + +/** + * Set filter to pick headers for downloading image HTTP request. + * + * This block will be invoked for each downloading image request, returned + * NSDictionary will be used as headers in corresponding HTTP request. + */ +@property (nonatomic, copy, nullable) SDWebImageDownloaderHeadersFilterBlock headersFilter; + +/** + * Creates an instance of a downloader with specified session configuration. + * @note `timeoutIntervalForRequest` is going to be overwritten. + * @return new instance of downloader class + */ +- (nonnull instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)sessionConfiguration 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. + * @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; + +/** + * Sets a subclass of `SDWebImageDownloaderOperation` as the default + * `NSOperation` to be used each time SDWebImage constructs a request + * operation to download an image. + * + * @param operationClass The subclass of `SDWebImageDownloaderOperation` to set + * as default. Passing `nil` will revert to `SDWebImageDownloaderOperation`. + */ +- (void)setOperationClass:(nullable Class)operationClass; + +/** + * 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 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 passed to -cancel: to cancel this operation + */ +- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url + options:(SDWebImageDownloaderOptions)options + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; + +/** + * Cancels a download that was previously queued using -downloadImageWithURL:options:progress:completed: + * + * @param token The token received from -downloadImageWithURL:options:progress:completed: that should be canceled. + */ +- (void)cancel:(nullable SDWebImageDownloadToken *)token; + +/** + * Sets the download queue suspension state + */ +- (void)setSuspended:(BOOL)suspended; + +/** + * Cancels all download operations in the queue + */ +- (void)cancelAllDownloads; + +/** + * Forces SDWebImageDownloader to create and use a new NSURLSession that is + * initialized with the given configuration. + * @note All existing download operations in the queue will be cancelled. + * @note `timeoutIntervalForRequest` is going to be overwritten. + * + * @param sessionConfiguration The configuration to use for the new NSURLSession + */ +- (void)createNewSessionWithConfiguration:(nonnull NSURLSessionConfiguration *)sessionConfiguration; + +/** + * 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 diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageDownloader.m b/Pods/SDWebImage/SDWebImage/SDWebImageDownloader.m new file mode 100644 index 0000000..76291a1 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageDownloader.m @@ -0,0 +1,409 @@ +/* + * 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 "SDWebImageDownloaderOperation.h" + +#define LOCK(lock) dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER); +#define UNLOCK(lock) dispatch_semaphore_signal(lock); + +@interface SDWebImageDownloadToken () + +@property (nonatomic, weak, nullable) NSOperation *downloadOperation; + +@end + +@implementation SDWebImageDownloadToken + +- (void)cancel { + if (self.downloadOperation) { + SDWebImageDownloadToken *cancelToken = self.downloadOperationCancelToken; + if (cancelToken) { + [self.downloadOperation cancel:cancelToken]; + } + } +} + +@end + + +@interface SDWebImageDownloader () + +@property (strong, nonatomic, nonnull) NSOperationQueue *downloadQueue; +@property (weak, nonatomic, nullable) NSOperation *lastAddedOperation; +@property (assign, nonatomic, nullable) Class operationClass; +@property (strong, nonatomic, nonnull) NSMutableDictionary *URLOperations; +@property (strong, nonatomic, nullable) SDHTTPHeadersMutableDictionary *HTTPHeaders; +@property (strong, nonatomic, nonnull) dispatch_semaphore_t operationsLock; // a lock to keep the access to `URLOperations` thread-safe +@property (strong, nonatomic, nonnull) dispatch_semaphore_t headersLock; // a lock to keep the access to `HTTPHeaders` 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 initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; +} + +- (nonnull instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)sessionConfiguration { + if ((self = [super init])) { + _operationClass = [SDWebImageDownloaderOperation class]; + _shouldDecompressImages = YES; + _executionOrder = SDWebImageDownloaderFIFOExecutionOrder; + _downloadQueue = [NSOperationQueue new]; + _downloadQueue.maxConcurrentOperationCount = 6; + _downloadQueue.name = @"com.hackemist.SDWebImageDownloader"; + _URLOperations = [NSMutableDictionary new]; +#ifdef SD_WEBP + _HTTPHeaders = [@{@"Accept": @"image/webp,image/*;q=0.8"} mutableCopy]; +#else + _HTTPHeaders = [@{@"Accept": @"image/*;q=0.8"} mutableCopy]; +#endif + _operationsLock = dispatch_semaphore_create(1); + _headersLock = dispatch_semaphore_create(1); + _downloadTimeout = 15.0; + + [self createNewSessionWithConfiguration:sessionConfiguration]; + } + return self; +} + +- (void)createNewSessionWithConfiguration:(NSURLSessionConfiguration *)sessionConfiguration { + [self cancelAllDownloads]; + + if (self.session) { + [self.session invalidateAndCancel]; + } + + sessionConfiguration.timeoutIntervalForRequest = self.downloadTimeout; + + /** + * 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. + */ + self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration + delegate:self + delegateQueue:nil]; +} + +- (void)invalidateSessionAndCancel:(BOOL)cancelPendingOperations { + if (self == [SDWebImageDownloader sharedDownloader]) { + return; + } + if (cancelPendingOperations) { + [self.session invalidateAndCancel]; + } else { + [self.session finishTasksAndInvalidate]; + } +} + +- (void)dealloc { + [self.session invalidateAndCancel]; + self.session = nil; + + [self.downloadQueue cancelAllOperations]; +} + +- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field { + LOCK(self.headersLock); + if (value) { + self.HTTPHeaders[field] = value; + } else { + [self.HTTPHeaders removeObjectForKey:field]; + } + UNLOCK(self.headersLock); +} + +- (nullable NSString *)valueForHTTPHeaderField:(nullable NSString *)field { + if (!field) { + return nil; + } + return [[self allHTTPHeaderFields] objectForKey:field]; +} + +- (nonnull SDHTTPHeadersDictionary *)allHTTPHeaderFields { + LOCK(self.headersLock); + SDHTTPHeadersDictionary *allHTTPHeaderFields = [self.HTTPHeaders copy]; + UNLOCK(self.headersLock); + return allHTTPHeaderFields; +} + +- (void)setMaxConcurrentDownloads:(NSInteger)maxConcurrentDownloads { + _downloadQueue.maxConcurrentOperationCount = maxConcurrentDownloads; +} + +- (NSUInteger)currentDownloadCount { + return _downloadQueue.operationCount; +} + +- (NSInteger)maxConcurrentDownloads { + return _downloadQueue.maxConcurrentOperationCount; +} + +- (NSURLSessionConfiguration *)sessionConfiguration { + return self.session.configuration; +} + +- (void)setOperationClass:(nullable Class)operationClass { + if (operationClass && [operationClass isSubclassOfClass:[NSOperation class]] && [operationClass conformsToProtocol:@protocol(SDWebImageDownloaderOperationInterface)]) { + _operationClass = operationClass; + } else { + _operationClass = [SDWebImageDownloaderOperation class]; + } +} + +- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url + options:(SDWebImageDownloaderOptions)options + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock { + __weak SDWebImageDownloader *wself = self; + + return [self addProgressCallback:progressBlock completedBlock:completedBlock forURL:url createCallback:^SDWebImageDownloaderOperation *{ + __strong __typeof (wself) sself = wself; + NSTimeInterval timeoutInterval = sself.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 *request = [[NSMutableURLRequest alloc] initWithURL:url + cachePolicy:cachePolicy + timeoutInterval:timeoutInterval]; + + request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies); + request.HTTPShouldUsePipelining = YES; + if (sself.headersFilter) { + request.allHTTPHeaderFields = sself.headersFilter(url, [sself allHTTPHeaderFields]); + } + else { + request.allHTTPHeaderFields = [sself allHTTPHeaderFields]; + } + SDWebImageDownloaderOperation *operation = [[sself.operationClass alloc] initWithRequest:request inSession:sself.session options:options]; + operation.shouldDecompressImages = sself.shouldDecompressImages; + + if (sself.urlCredential) { + operation.credential = sself.urlCredential; + } else if (sself.username && sself.password) { + operation.credential = [NSURLCredential credentialWithUser:sself.username password:sself.password persistence:NSURLCredentialPersistenceForSession]; + } + + if (options & SDWebImageDownloaderHighPriority) { + operation.queuePriority = NSOperationQueuePriorityHigh; + } else if (options & SDWebImageDownloaderLowPriority) { + operation.queuePriority = NSOperationQueuePriorityLow; + } + + if (sself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) { + // Emulate LIFO execution order by systematically adding new operations as last operation's dependency + [sself.lastAddedOperation addDependency:operation]; + sself.lastAddedOperation = operation; + } + + return operation; + }]; +} + +- (void)cancel:(nullable SDWebImageDownloadToken *)token { + NSURL *url = token.url; + if (!url) { + return; + } + LOCK(self.operationsLock); + SDWebImageDownloaderOperation *operation = [self.URLOperations objectForKey:url]; + if (operation) { + BOOL canceled = [operation cancel:token.downloadOperationCancelToken]; + if (canceled) { + [self.URLOperations removeObjectForKey:url]; + } + } + UNLOCK(self.operationsLock); +} + +- (nullable SDWebImageDownloadToken *)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock + completedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock + forURL:(nullable NSURL *)url + createCallback:(SDWebImageDownloaderOperation *(^)(void))createCallback { + // 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 != nil) { + completedBlock(nil, nil, nil, NO); + } + return nil; + } + + LOCK(self.operationsLock); + SDWebImageDownloaderOperation *operation = [self.URLOperations objectForKey:url]; + // There is a case that the operation may be marked as finished, but not been removed from `self.URLOperations`. + if (!operation || operation.isFinished) { + operation = createCallback(); + __weak typeof(self) wself = self; + operation.completionBlock = ^{ + __strong typeof(wself) sself = wself; + if (!sself) { + return; + } + LOCK(sself.operationsLock); + [sself.URLOperations removeObjectForKey:url]; + UNLOCK(sself.operationsLock); + }; + [self.URLOperations setObject:operation forKey:url]; + // 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]; + } + UNLOCK(self.operationsLock); + + id downloadOperationCancelToken = [operation addHandlersForProgress:progressBlock completed:completedBlock]; + + SDWebImageDownloadToken *token = [SDWebImageDownloadToken new]; + token.downloadOperation = operation; + token.url = url; + token.downloadOperationCancelToken = downloadOperationCancelToken; + + return token; +} + +- (void)setSuspended:(BOOL)suspended { + self.downloadQueue.suspended = suspended; +} + +- (void)cancelAllDownloads { + [self.downloadQueue cancelAllOperations]; +} + +#pragma mark Helper methods + +- (SDWebImageDownloaderOperation *)operationWithTask:(NSURLSessionTask *)task { + SDWebImageDownloaderOperation *returnOperation = nil; + for (SDWebImageDownloaderOperation *operation in self.downloadQueue.operations) { + if (operation.dataTask.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 + SDWebImageDownloaderOperation *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 + SDWebImageDownloaderOperation *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 + SDWebImageDownloaderOperation *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 + SDWebImageDownloaderOperation *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 + SDWebImageDownloaderOperation *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 + SDWebImageDownloaderOperation *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 diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.h b/Pods/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.h new file mode 100644 index 0000000..d0c5815 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.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 "SDWebImageDownloader.h" +#import "SDWebImageOperation.h" + +FOUNDATION_EXPORT NSString * _Nonnull const SDWebImageDownloadStartNotification; +FOUNDATION_EXPORT NSString * _Nonnull const SDWebImageDownloadReceiveResponseNotification; +FOUNDATION_EXPORT NSString * _Nonnull const SDWebImageDownloadStopNotification; +FOUNDATION_EXPORT NSString * _Nonnull const SDWebImageDownloadFinishNotification; + + + +/** + 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` + */ +@protocol SDWebImageDownloaderOperationInterface + +- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request + inSession:(nullable NSURLSession *)session + options:(SDWebImageDownloaderOptions)options; + +- (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock; + +- (BOOL)shouldDecompressImages; +- (void)setShouldDecompressImages:(BOOL)value; + +- (nullable NSURLCredential *)credential; +- (void)setCredential:(nullable NSURLCredential *)value; + +- (BOOL)cancel:(nullable id)token; + +@end + + +@interface SDWebImageDownloaderOperation : NSOperation + +/** + * The request used by the operation's task. + */ +@property (strong, nonatomic, readonly, nullable) NSURLRequest *request; + +/** + * The operation's task + */ +@property (strong, nonatomic, readonly, nullable) NSURLSessionTask *dataTask; + + +@property (assign, nonatomic) BOOL shouldDecompressImages; + +/** + * Was used to determine whether the URL connection should consult the credential storage for authenticating the connection. + * @deprecated Not used for a couple of versions + */ +@property (nonatomic, assign) BOOL shouldUseCredentialStorage __deprecated_msg("Property deprecated. Does nothing. Kept only for backwards compatibility"); + +/** + * 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 (nonatomic, strong, nullable) NSURLCredential *credential; + +/** + * The SDWebImageDownloaderOptions for the receiver. + */ +@property (assign, nonatomic, readonly) SDWebImageDownloaderOptions options; + +/** + * The expected size of data. + */ +@property (assign, nonatomic) NSInteger expectedSize; + +/** + * The response returned by the operation's task. + */ +@property (strong, nonatomic, nullable) NSURLResponse *response; + +/** + * 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 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/Pods/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.m b/Pods/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.m new file mode 100644 index 0000000..722645f --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageDownloaderOperation.m @@ -0,0 +1,516 @@ +/* + * 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 "SDWebImageManager.h" +#import "NSImage+WebCache.h" +#import "SDWebImageCodersManager.h" + +#define LOCK(lock) dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER); +#define UNLOCK(lock) dispatch_semaphore_signal(lock); + +// 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) +const float NSURLSessionTaskPriorityHigh = 0.75; +const float NSURLSessionTaskPriorityDefault = 0.5; +const float NSURLSessionTaskPriorityLow = 0.25; +#endif + +NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification"; +NSString *const SDWebImageDownloadReceiveResponseNotification = @"SDWebImageDownloadReceiveResponseNotification"; +NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification"; +NSString *const SDWebImageDownloadFinishNotification = @"SDWebImageDownloadFinishNotification"; + +static NSString *const kProgressCallbackKey = @"progress"; +static NSString *const kCompletedCallbackKey = @"completed"; + +typedef NSMutableDictionary SDCallbacksDictionary; + +@interface SDWebImageDownloaderOperation () + +@property (strong, nonatomic, nonnull) NSMutableArray *callbackBlocks; + +@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` + +// 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_semaphore_t callbacksLock; // a lock to keep the access to `callbackBlocks` thread-safe + +@property (strong, nonatomic, nonnull) dispatch_queue_t coderQueue; // the queue to do image decoding +#if SD_UIKIT +@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskId; +#endif + +@property (strong, nonatomic, nullable) id progressiveCoder; + +@end + +@implementation SDWebImageDownloaderOperation + +@synthesize executing = _executing; +@synthesize finished = _finished; + +- (nonnull instancetype)init { + return [self initWithRequest:nil inSession:nil options:0]; +} + +- (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request + inSession:(nullable NSURLSession *)session + options:(SDWebImageDownloaderOptions)options { + if ((self = [super init])) { + _request = [request copy]; + _shouldDecompressImages = YES; + _options = options; + _callbackBlocks = [NSMutableArray new]; + _executing = NO; + _finished = NO; + _expectedSize = 0; + _unownedSession = session; + _callbacksLock = dispatch_semaphore_create(1); + _coderQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderOperationCoderQueue", DISPATCH_QUEUE_SERIAL); + } + 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]; + LOCK(self.callbacksLock); + [self.callbackBlocks addObject:callbacks]; + UNLOCK(self.callbacksLock); + return callbacks; +} + +- (nullable NSArray *)callbacksForKey:(NSString *)key { + LOCK(self.callbacksLock); + NSMutableArray *callbacks = [[self.callbackBlocks valueForKey:key] mutableCopy]; + UNLOCK(self.callbacksLock); + // 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 { + BOOL shouldCancel = NO; + LOCK(self.callbacksLock); + [self.callbackBlocks removeObjectIdenticalTo:token]; + if (self.callbackBlocks.count == 0) { + shouldCancel = YES; + } + UNLOCK(self.callbacksLock); + if (shouldCancel) { + [self cancel]; + } + return shouldCancel; +} + +- (void)start { + @synchronized (self) { + if (self.isCancelled) { + self.finished = YES; + [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:^{ + __strong __typeof (wself) sself = wself; + + if (sself) { + [sself cancel]; + + [app endBackgroundTask:sself.backgroundTaskId]; + sself.backgroundTaskId = UIBackgroundTaskInvalid; + } + }]; + } +#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) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" + if ([self.dataTask respondsToSelector:@selector(setPriority:)]) { + if (self.options & SDWebImageDownloaderHighPriority) { + self.dataTask.priority = NSURLSessionTaskPriorityHigh; + } else if (self.options & SDWebImageDownloaderLowPriority) { + self.dataTask.priority = NSURLSessionTaskPriorityLow; + } + } +#pragma clang diagnostic pop + [self.dataTask resume]; + for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) { + progressBlock(0, NSURLResponseUnknownLength, self.request.URL); + } + __weak typeof(self) weakSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:weakSelf]; + }); + } else { + [self callCompletionBlocksWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorUnknown userInfo:@{NSLocalizedDescriptionKey : @"Task can't be initialized"}]]; + [self done]; + return; + } + +#if SD_UIKIT + Class UIApplicationClass = NSClassFromString(@"UIApplication"); + if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) { + return; + } + if (self.backgroundTaskId != UIBackgroundTaskInvalid) { + UIApplication * app = [UIApplication performSelector:@selector(sharedApplication)]; + [app endBackgroundTask:self.backgroundTaskId]; + self.backgroundTaskId = UIBackgroundTaskInvalid; + } +#endif +} + +- (void)cancel { + @synchronized (self) { + [self cancelInternal]; + } +} + +- (void)cancelInternal { + if (self.isFinished) return; + [super cancel]; + + if (self.dataTask) { + [self.dataTask cancel]; + __weak typeof(self) weakSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:weakSelf]; + }); + + // 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; + } + + [self reset]; +} + +- (void)done { + self.finished = YES; + self.executing = NO; + [self reset]; +} + +- (void)reset { + LOCK(self.callbacksLock); + [self.callbackBlocks removeAllObjects]; + UNLOCK(self.callbacksLock); + self.dataTask = nil; + + if (self.ownedSession) { + [self.ownedSession invalidateAndCancel]; + self.ownedSession = nil; + } +} + +- (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; + 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; + BOOL valid = statusCode < 400; + //'304 Not Modified' is an exceptional one. It should be treated as cancelled if no cache data + //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; + } + + 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; + } + + __weak typeof(self) weakSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadReceiveResponseNotification object:weakSelf]; + }); + + 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]; + + if ((self.options & SDWebImageDownloaderProgressiveDownload) && self.expectedSize > 0) { + // Get the image data + __block NSData *imageData = [self.imageData copy]; + // Get the total bytes downloaded + const NSInteger totalSize = imageData.length; + // Get the finish status + BOOL finished = (totalSize >= self.expectedSize); + + if (!self.progressiveCoder) { + // We need to create a new instance for progressive decoding to avoid conflicts + for (idcoder in [SDWebImageCodersManager sharedInstance].coders) { + if ([coder conformsToProtocol:@protocol(SDWebImageProgressiveCoder)] && + [((id)coder) canIncrementallyDecodeFromData:imageData]) { + self.progressiveCoder = [[[coder class] alloc] init]; + break; + } + } + } + + // progressive decode the image in coder queue + dispatch_async(self.coderQueue, ^{ + UIImage *image = [self.progressiveCoder incrementallyDecodedImageWithData:imageData finished:finished]; + if (image) { + NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL]; + image = [self scaledImageForKey:key image:image]; + if (self.shouldDecompressImages) { + image = [[SDWebImageCodersManager sharedInstance] decompressedImageWithImage:image data:&imageData options:@{SDWebImageCoderScaleDownLargeImagesKey: @(NO)}]; + } + + // 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.imageData.length, 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 { + @synchronized(self) { + self.dataTask = nil; + __weak typeof(self) weakSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:weakSelf]; + if (!error) { + [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadFinishNotification object:weakSelf]; + } + }); + } + + // make sure to call `[self done]` to mark operation as finished + if (error) { + [self callCompletionBlocksWithError:error]; + [self done]; + } else { + if ([self callbacksForKey:kCompletedCallbackKey].count > 0) { + /** + * If you specified to use `NSURLCache`, then the response you get here is what you need. + */ + __block NSData *imageData = [self.imageData copy]; + 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]) { + // call completion block with nil + [self callCompletionBlocksWithImage:nil imageData:nil error:nil finished:YES]; + [self done]; + } else { + // decode the image in coder queue + dispatch_async(self.coderQueue, ^{ + UIImage *image = [[SDWebImageCodersManager sharedInstance] decodedImageWithData:imageData]; + NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:self.request.URL]; + image = [self scaledImageForKey:key image:image]; + + BOOL shouldDecode = YES; + // Do not force decoding animated GIFs and WebPs + if (image.images) { + shouldDecode = NO; + } else { +#ifdef SD_WEBP + SDImageFormat imageFormat = [NSData sd_imageFormatForImageData:imageData]; + if (imageFormat == SDImageFormatWebP) { + shouldDecode = NO; + } +#endif + } + + if (shouldDecode) { + if (self.shouldDecompressImages) { + BOOL shouldScaleDown = self.options & SDWebImageDownloaderScaleDownLargeImages; + image = [[SDWebImageCodersManager sharedInstance] decompressedImageWithImage:image data:&imageData options:@{SDWebImageCoderScaleDownLargeImagesKey: @(shouldScaleDown)}]; + } + } + CGSize imageSize = image.size; + if (imageSize.width == 0 || imageSize.height == 0) { + [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:0 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:0 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 +- (nullable UIImage *)scaledImageForKey:(nullable NSString *)key image:(nullable UIImage *)image { + return SDScaledImageForKey(key, image); +} + +- (BOOL)shouldContinueWhenAppEntersBackground { + return 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/Pods/SDWebImage/SDWebImage/SDWebImageFrame.h b/Pods/SDWebImage/SDWebImage/SDWebImageFrame.h new file mode 100644 index 0000000..c3a0f71 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageFrame.h @@ -0,0 +1,34 @@ +/* + * 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 SDWebImageFrame : NSObject + +// This class is used for creating animated images via `animatedImageWithFrames` in `SDWebImageCoderHelper`. Attention if you need to specify animated images loop count, use `sd_imageLoopCount` property in `UIImage+MultiFormat`. + +/** + 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/Pods/SDWebImage/SDWebImage/SDWebImageFrame.m b/Pods/SDWebImage/SDWebImage/SDWebImageFrame.m new file mode 100644 index 0000000..b0aefe5 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageFrame.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 "SDWebImageFrame.h" + +@interface SDWebImageFrame () + +@property (nonatomic, strong, readwrite, nonnull) UIImage *image; +@property (nonatomic, readwrite, assign) NSTimeInterval duration; + +@end + +@implementation SDWebImageFrame + ++ (instancetype)frameWithImage:(UIImage *)image duration:(NSTimeInterval)duration { + SDWebImageFrame *frame = [[SDWebImageFrame alloc] init]; + frame.image = image; + frame.duration = duration; + + return frame; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageGIFCoder.h b/Pods/SDWebImage/SDWebImage/SDWebImageGIFCoder.h new file mode 100644 index 0000000..30521f9 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageGIFCoder.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 "SDWebImageCoder.h" + +/** + Built in coder using ImageIO that supports GIF encoding/decoding + @note `SDWebImageIOCoder` supports GIF but only as static (will use the 1st frame). + @note Use `SDWebImageGIFCoder` for fully animated GIFs - less performant than `FLAnimatedImage` + @note If you decide to make all `UIImageView`(including `FLAnimatedImageView`) instance support GIF. You should add this coder to `SDWebImageCodersManager` and make sure that it has a higher priority than `SDWebImageIOCoder` + @note The recommended approach for animated GIFs is using `FLAnimatedImage`. It's more performant than `UIImageView` for GIF displaying + */ +@interface SDWebImageGIFCoder : NSObject + ++ (nonnull instancetype)sharedCoder; + +@end diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageGIFCoder.m b/Pods/SDWebImage/SDWebImage/SDWebImageGIFCoder.m new file mode 100644 index 0000000..e43b773 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageGIFCoder.m @@ -0,0 +1,184 @@ +/* + * 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 "SDWebImageGIFCoder.h" +#import "NSImage+WebCache.h" +#import +#import "NSData+ImageContentType.h" +#import "UIImage+MultiFormat.h" +#import "SDWebImageCoderHelper.h" +#import "SDAnimatedImageRep.h" + +@implementation SDWebImageGIFCoder + ++ (instancetype)sharedCoder { + static SDWebImageGIFCoder *coder; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + coder = [[SDWebImageGIFCoder alloc] init]; + }); + return coder; +} + +#pragma mark - Decode +- (BOOL)canDecodeFromData:(nullable NSData *)data { + return ([NSData sd_imageFormatForImageData:data] == SDImageFormatGIF); +} + +- (UIImage *)decodedImageWithData:(NSData *)data { + if (!data) { + return nil; + } + +#if SD_MAC + SDAnimatedImageRep *imageRep = [[SDAnimatedImageRep alloc] initWithData:data]; + NSImage *animatedImage = [[NSImage alloc] initWithSize:imageRep.size]; + [animatedImage addRepresentation:imageRep]; + return animatedImage; +#else + + CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL); + if (!source) { + return nil; + } + size_t count = CGImageSourceGetCount(source); + + UIImage *animatedImage; + + if (count <= 1) { + animatedImage = [[UIImage alloc] initWithData:data]; + } else { + NSMutableArray *frames = [NSMutableArray array]; + + for (size_t i = 0; i < count; i++) { + CGImageRef imageRef = CGImageSourceCreateImageAtIndex(source, i, NULL); + if (!imageRef) { + continue; + } + + float duration = [self sd_frameDurationAtIndex:i source:source]; + UIImage *image = [[UIImage alloc] initWithCGImage:imageRef]; + CGImageRelease(imageRef); + + SDWebImageFrame *frame = [SDWebImageFrame frameWithImage:image duration:duration]; + [frames addObject:frame]; + } + + NSUInteger loopCount = 1; + NSDictionary *imageProperties = (__bridge_transfer NSDictionary *)CGImageSourceCopyProperties(source, nil); + NSDictionary *gifProperties = [imageProperties valueForKey:(__bridge NSString *)kCGImagePropertyGIFDictionary]; + if (gifProperties) { + NSNumber *gifLoopCount = [gifProperties valueForKey:(__bridge NSString *)kCGImagePropertyGIFLoopCount]; + if (gifLoopCount != nil) { + loopCount = gifLoopCount.unsignedIntegerValue; + } + } + + animatedImage = [SDWebImageCoderHelper animatedImageWithFrames:frames]; + animatedImage.sd_imageLoopCount = loopCount; + animatedImage.sd_imageFormat = SDImageFormatGIF; + } + + CFRelease(source); + + return animatedImage; +#endif +} + +- (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source { + float frameDuration = 0.1f; + CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil); + if (!cfFrameProperties) { + return frameDuration; + } + NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties; + NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary]; + + NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime]; + if (delayTimeUnclampedProp != nil) { + frameDuration = [delayTimeUnclampedProp floatValue]; + } else { + NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime]; + if (delayTimeProp != nil) { + frameDuration = [delayTimeProp floatValue]; + } + } + + // 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.011f) { + frameDuration = 0.100f; + } + + CFRelease(cfFrameProperties); + return frameDuration; +} + +- (UIImage *)decompressedImageWithImage:(UIImage *)image + data:(NSData *__autoreleasing _Nullable *)data + options:(nullable NSDictionary*)optionsDict { + // GIF do not decompress + return image; +} + +#pragma mark - Encode +- (BOOL)canEncodeToFormat:(SDImageFormat)format { + return (format == SDImageFormatGIF); +} + +- (NSData *)encodedDataWithImage:(UIImage *)image format:(SDImageFormat)format { + if (!image) { + return nil; + } + + if (format != SDImageFormatGIF) { + return nil; + } + + NSMutableData *imageData = [NSMutableData data]; + CFStringRef imageUTType = [NSData sd_UTTypeFromSDImageFormat:SDImageFormatGIF]; + NSArray *frames = [SDWebImageCoderHelper framesFromAnimatedImage:image]; + + // Create an image destination. GIF does not support EXIF image orientation + CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, imageUTType, frames.count, NULL); + if (!imageDestination) { + // Handle failure. + return nil; + } + if (frames.count == 0) { + // for static single GIF images + CGImageDestinationAddImage(imageDestination, image.CGImage, nil); + } else { + // for animated GIF images + NSUInteger loopCount = image.sd_imageLoopCount; + NSDictionary *gifProperties = @{(__bridge NSString *)kCGImagePropertyGIFDictionary: @{(__bridge NSString *)kCGImagePropertyGIFLoopCount : @(loopCount)}}; + CGImageDestinationSetProperties(imageDestination, (__bridge CFDictionaryRef)gifProperties); + + for (size_t i = 0; i < frames.count; i++) { + SDWebImageFrame *frame = frames[i]; + float 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. + imageData = nil; + } + + CFRelease(imageDestination); + + return [imageData copy]; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageImageIOCoder.h b/Pods/SDWebImage/SDWebImage/SDWebImageImageIOCoder.h new file mode 100644 index 0000000..04f68fb --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageImageIOCoder.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 "SDWebImageCoder.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 `FLAnimatedImage` or our less performant `SDWebImageGIFCoder` + + 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 SDWebImageImageIOCoder : NSObject + ++ (nonnull instancetype)sharedCoder; + +@end diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageImageIOCoder.m b/Pods/SDWebImage/SDWebImage/SDWebImageImageIOCoder.m new file mode 100644 index 0000000..1d0238e --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageImageIOCoder.m @@ -0,0 +1,510 @@ +/* + * 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 "SDWebImageImageIOCoder.h" +#import "SDWebImageCoderHelper.h" +#import "NSImage+WebCache.h" +#import +#import "NSData+ImageContentType.h" +#import "UIImage+MultiFormat.h" + +#if SD_UIKIT || SD_WATCH +static const size_t kBytesPerPixel = 4; +static const size_t kBitsPerComponent = 8; + +/* + * 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. + */ +static const CGFloat kDestImageSizeMB = 60.0f; + +/* + * Defines the maximum size in MB of a tile used to decode image when the flag `SDWebImageScaleDownLargeImages` is set + * Suggested value for iPad1 and iPhone 3GS: 20. + * Suggested value for iPad2 and iPhone 4: 40. + * Suggested value for iPhone 3G and iPod 2 and earlier devices: 10. + */ +static const CGFloat kSourceImageTileSizeMB = 20.0f; + +static const CGFloat kBytesPerMB = 1024.0f * 1024.0f; +static const CGFloat kPixelsPerMB = kBytesPerMB / kBytesPerPixel; +static const CGFloat kDestTotalPixels = kDestImageSizeMB * kPixelsPerMB; +static const CGFloat kTileTotalPixels = kSourceImageTileSizeMB * kPixelsPerMB; + +static const CGFloat kDestSeemOverlap = 2.0f; // the numbers of pixels to overlap the seems where tiles meet. +#endif + +@implementation SDWebImageImageIOCoder { + size_t _width, _height; +#if SD_UIKIT || SD_WATCH + UIImageOrientation _orientation; +#endif + CGImageSourceRef _imageSource; +} + +- (void)dealloc { + if (_imageSource) { + CFRelease(_imageSource); + _imageSource = NULL; + } +} + ++ (instancetype)sharedCoder { + static SDWebImageImageIOCoder *coder; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + coder = [[SDWebImageImageIOCoder 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 [[self class] canDecodeFromHEICFormat]; + default: + return YES; + } +} + +- (BOOL)canIncrementallyDecodeFromData:(NSData *)data { + switch ([NSData sd_imageFormatForImageData:data]) { + case SDImageFormatWebP: + // Do not support WebP progressive decoding + return NO; + case SDImageFormatHEIC: + // Check HEIC decoding compatibility + return [[self class] canDecodeFromHEICFormat]; + default: + return YES; + } +} + +- (UIImage *)decodedImageWithData:(NSData *)data { + if (!data) { + return nil; + } + + UIImage *image = [[UIImage alloc] initWithData:data]; + image.sd_imageFormat = [NSData sd_imageFormatForImageData:data]; + + return image; +} + +- (UIImage *)incrementallyDecodedImageWithData:(NSData *)data finished:(BOOL)finished { + if (!_imageSource) { + _imageSource = CGImageSourceCreateIncremental(NULL); + } + UIImage *image; + + // 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. +#if SD_UIKIT || SD_WATCH + _orientation = [SDWebImageCoderHelper imageOrientationFromEXIFOrientation:orientationValue]; +#endif + } + } + + if (_width + _height > 0) { + // Create the image + CGImageRef partialImageRef = CGImageSourceCreateImageAtIndex(_imageSource, 0, NULL); + + if (partialImageRef) { +#if SD_UIKIT || SD_WATCH + image = [[UIImage alloc] initWithCGImage:partialImageRef scale:1 orientation:_orientation]; +#elif SD_MAC + image = [[UIImage alloc] initWithCGImage:partialImageRef size:NSZeroSize]; +#endif + CGImageRelease(partialImageRef); + image.sd_imageFormat = [NSData sd_imageFormatForImageData:data]; + } + } + + if (finished) { + if (_imageSource) { + CFRelease(_imageSource); + _imageSource = NULL; + } + } + + return image; +} + +- (UIImage *)decompressedImageWithImage:(UIImage *)image + data:(NSData *__autoreleasing _Nullable *)data + options:(nullable NSDictionary*)optionsDict { +#if SD_MAC + return image; +#endif +#if SD_UIKIT || SD_WATCH + BOOL shouldScaleDown = NO; + if (optionsDict != nil) { + NSNumber *scaleDownLargeImagesOption = nil; + if ([optionsDict[SDWebImageCoderScaleDownLargeImagesKey] isKindOfClass:[NSNumber class]]) { + scaleDownLargeImagesOption = (NSNumber *)optionsDict[SDWebImageCoderScaleDownLargeImagesKey]; + } + if (scaleDownLargeImagesOption != nil) { + shouldScaleDown = [scaleDownLargeImagesOption boolValue]; + } + } + if (!shouldScaleDown) { + return [self sd_decompressedImageWithImage:image]; + } else { + UIImage *scaledDownImage = [self sd_decompressedAndScaledDownImageWithImage:image]; + if (scaledDownImage && !CGSizeEqualToSize(scaledDownImage.size, image.size)) { + // if the image is scaled down, need to modify the data pointer as well + SDImageFormat format = [NSData sd_imageFormatForImageData:*data]; + NSData *imageData = [self encodedDataWithImage:scaledDownImage format:format]; + if (imageData) { + *data = imageData; + } + } + return scaledDownImage; + } +#endif +} + +#if SD_UIKIT || SD_WATCH +- (nullable UIImage *)sd_decompressedImageWithImage:(nullable UIImage *)image { + if (![[self class] shouldDecodeImage:image]) { + return image; + } + + // 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 imageRef = image.CGImage; + // device color space + CGColorSpaceRef colorspaceRef = SDCGColorSpaceGetDeviceRGB(); + BOOL hasAlpha = SDCGImageRefContainsAlpha(imageRef); + // iOS display alpha info (BRGA8888/BGRX8888) + CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Host; + bitmapInfo |= hasAlpha ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaNoneSkipFirst; + + size_t width = CGImageGetWidth(imageRef); + size_t height = CGImageGetHeight(imageRef); + + // kCGImageAlphaNone is not supported in CGBitmapContextCreate. + // Since the original image here has no alpha info, use kCGImageAlphaNoneSkipLast + // to create bitmap graphics contexts without alpha info. + CGContextRef context = CGBitmapContextCreate(NULL, + width, + height, + kBitsPerComponent, + 0, + colorspaceRef, + bitmapInfo); + if (context == NULL) { + return image; + } + + // Draw the image into the context and retrieve the new bitmap image without alpha + CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef); + CGImageRef imageRefWithoutAlpha = CGBitmapContextCreateImage(context); + UIImage *imageWithoutAlpha = [[UIImage alloc] initWithCGImage:imageRefWithoutAlpha scale:image.scale orientation:image.imageOrientation]; + CGContextRelease(context); + CGImageRelease(imageRefWithoutAlpha); + + return imageWithoutAlpha; + } +} + +- (nullable UIImage *)sd_decompressedAndScaledDownImageWithImage:(nullable UIImage *)image { + if (![[self class] shouldDecodeImage:image]) { + return image; + } + + if (![[self class] shouldScaleDownImage:image]) { + return [self sd_decompressedImageWithImage:image]; + } + + 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); + float 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. + float imageScale = kDestTotalPixels / sourceTotalPixels; + CGSize destResolution = CGSizeZero; + destResolution.width = (int)(sourceResolution.width*imageScale); + destResolution.height = (int)(sourceResolution.height*imageScale); + + // device color space + CGColorSpaceRef colorspaceRef = SDCGColorSpaceGetDeviceRGB(); + BOOL hasAlpha = SDCGImageRefContainsAlpha(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 kCGImageAlphaNoneSkipLast + // 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)(kTileTotalPixels / 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; + } + UIImage *destImage = [[UIImage alloc] initWithCGImage:destImageRef scale:image.scale orientation:image.imageOrientation]; + CGImageRelease(destImageRef); + if (destImage == nil) { + return image; + } + return destImage; + } +} +#endif + +#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 [[self class] canEncodeToHEICFormat]; + default: + return YES; + } +} + +- (NSData *)encodedDataWithImage:(UIImage *)image format:(SDImageFormat)format { + if (!image) { + return nil; + } + + if (format == SDImageFormatUndefined) { + BOOL hasAlpha = SDCGImageRefContainsAlpha(image.CGImage); + if (hasAlpha) { + format = SDImageFormatPNG; + } else { + format = SDImageFormatJPEG; + } + } + + NSMutableData *imageData = [NSMutableData data]; + CFStringRef imageUTType = [NSData sd_UTTypeFromSDImageFormat: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 + NSInteger exifOrientation = [SDWebImageCoderHelper exifOrientationFromImageOrientation:image.imageOrientation]; + [properties setValue:@(exifOrientation) forKey:(__bridge NSString *)kCGImagePropertyOrientation]; +#endif + + // 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]; +} + +#pragma mark - Helper ++ (BOOL)shouldDecodeImage:(nullable UIImage *)image { + // Prevent "CGBitmapContextCreateImage: invalid context 0x0" error + if (image == nil) { + return NO; + } + + // do not decode animated images + if (image.images != nil) { + return NO; + } + + return YES; +} + ++ (BOOL)canDecodeFromHEICFormat { + static BOOL canDecode = NO; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" +#if TARGET_OS_SIMULATOR || SD_WATCH + canDecode = NO; +#elif SD_MAC + NSProcessInfo *processInfo = [NSProcessInfo processInfo]; + if ([processInfo respondsToSelector:@selector(operatingSystemVersion)]) { + // macOS 10.13+ + canDecode = processInfo.operatingSystemVersion.minorVersion >= 13; + } else { + canDecode = NO; + } +#elif SD_UIKIT + NSProcessInfo *processInfo = [NSProcessInfo processInfo]; + if ([processInfo respondsToSelector:@selector(operatingSystemVersion)]) { + // iOS 11+ && tvOS 11+ + canDecode = processInfo.operatingSystemVersion.majorVersion >= 11; + } else { + canDecode = NO; + } +#endif +#pragma clang diagnostic pop + }); + return canDecode; +} + ++ (BOOL)canEncodeToHEICFormat { + static BOOL canEncode = NO; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSMutableData *imageData = [NSMutableData data]; + CFStringRef imageUTType = [NSData sd_UTTypeFromSDImageFormat:SDImageFormatHEIC]; + + // Create an image destination. + CGImageDestinationRef imageDestination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)imageData, imageUTType, 1, NULL); + if (!imageDestination) { + // Can't encode to HEIC + canEncode = NO; + } else { + // Can encode to HEIC + CFRelease(imageDestination); + canEncode = YES; + } + }); + return canEncode; +} + +#if SD_UIKIT || SD_WATCH ++ (BOOL)shouldScaleDownImage:(nonnull UIImage *)image { + BOOL shouldScaleDown = YES; + + CGImageRef sourceImageRef = image.CGImage; + CGSize sourceResolution = CGSizeZero; + sourceResolution.width = CGImageGetWidth(sourceImageRef); + sourceResolution.height = CGImageGetHeight(sourceImageRef); + float sourceTotalPixels = sourceResolution.width * sourceResolution.height; + float imageScale = kDestTotalPixels / sourceTotalPixels; + if (imageScale < 1) { + shouldScaleDown = YES; + } else { + shouldScaleDown = NO; + } + + return shouldScaleDown; +} +#endif + +@end diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageManager.h b/Pods/SDWebImage/SDWebImage/SDWebImageManager.h new file mode 100644 index 0000000..9168021 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageManager.h @@ -0,0 +1,328 @@ +/* + * 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 "SDWebImageDownloader.h" +#import "SDImageCache.h" + +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 disables on-disk caching after the download finished, only cache in memory + */ + SDWebImageCacheMemoryOnly = 1 << 2, + + /** + * 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. + */ + SDWebImageProgressiveDownload = 1 << 3, + + /** + * 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 << 4, + + /** + * 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 << 5, + + /** + * Handles cookies stored in NSHTTPCookieStore by setting + * NSMutableURLRequest.HTTPShouldHandleCookies = YES; + */ + SDWebImageHandleCookies = 1 << 6, + + /** + * Enable to allow untrusted SSL certificates. + * Useful for testing purposes. Use with caution in production. + */ + SDWebImageAllowInvalidSSLCertificates = 1 << 7, + + /** + * 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 << 8, + + /** + * 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 << 9, + + /** + * We usually don't call transformDownloadedImage delegate method on animated images, + * as most transformation code would mangle it. + * Use this flag to transform them anyway. + */ + SDWebImageTransformAnimatedImage = 1 << 10, + + /** + * 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 << 11, + + /** + * 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. + * If `SDWebImageProgressiveDownload` flag is set the scale down is deactivated. + */ + SDWebImageScaleDownLargeImages = 1 << 12, + + /** + * By default, we do not query disk data when the image is cached in memory. This mask can force to query disk data at the same time. + * This flag is recommend to be used with `SDWebImageQueryDiskSync` to ensure the image is loaded in the same runloop. + */ + SDWebImageQueryDataWhenInMemory = 1 << 13, + + /** + * By default, we query the memory cache synchronously, disk cache asynchronously. This mask can force to query disk cache synchronously to ensure that image is loaded in the same runloop. + * This flag can avoid flashing during cell reuse if you disable memory cache or in some other cases. + */ + SDWebImageQueryDiskSync = 1 << 14, + + /** + * By default, when the cache missed, the image is download from the network. This flag can prevent network to load from cache only. + */ + SDWebImageFromCacheOnly = 1 << 15, + /** + * 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 << 16 +}; + +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); + +typedef NSString * _Nullable(^SDWebImageCacheKeyFilterBlock)(NSURL * _Nullable url); + +typedef NSData * _Nullable(^SDWebImageCacheSerializerBlock)(UIImage * _Nonnull image, NSData * _Nullable data, NSURL * _Nullable imageURL); + + +@class SDWebImageManager; + +@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:(nullable 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; + +/** + * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. + * NOTE: This method is called from a global queue in order to not to block the main thread. + * + * @param imageManager The current `SDWebImageManager` + * @param image The image to transform + * @param imageURL The url of the image to transform + * + * @return The transformed image object. + */ +- (nullable UIImage *)imageManager:(nonnull SDWebImageManager *)imageManager transformDownloadedImage:(nullable UIImage *)image withURL:(nullable NSURL *)imageURL; + +@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, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + if (image) { + // do something with image + } + }]; + + * @endcode + */ +@interface SDWebImageManager : NSObject + +@property (weak, nonatomic, nullable) id delegate; + +@property (strong, nonatomic, readonly, nullable) SDImageCache *imageCache; +@property (strong, nonatomic, readonly, nullable) SDWebImageDownloader *imageDownloader; + +/** + * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can + * be used to remove dynamic part of an image URL. + * + * 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 = ^(NSURL * _Nullable url) { + url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; + return [url absoluteString]; +}; + + * @endcode + */ +@property (nonatomic, copy, nullable) SDWebImageCacheKeyFilterBlock cacheKeyFilter; + +/** + * The cache serializer is a block 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 = ^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, copy, nullable) SDWebImageCacheSerializerBlock cacheSerializer; + +/** + * Returns global SDWebImageManager instance. + * + * @return SDWebImageManager shared instance + */ ++ (nonnull instancetype)sharedManager; + +/** + * Allows to specify instance of cache and image downloader used with image manager. + * @return new instance of `SDWebImageManager` with specified cache and downloader. + */ +- (nonnull instancetype)initWithCache:(nonnull SDImageCache *)cache downloader:(nonnull SDWebImageDownloader *)downloader 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 SDWebImageProgressiveDownload 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 NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation + */ +- (nullable id )loadImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDInternalCompletionBlock)completedBlock; + +/** + * Saves image to cache for given URL + * + * @param image The image to cache + * @param url The URL to the image + * + */ + +- (void)saveImageToCache:(nullable UIImage *)image forURL:(nullable NSURL *)url; + +/** + * Cancel all current operations + */ +- (void)cancelAll; + +/** + * Check one or more operations running + */ +- (BOOL)isRunning; + +/** + * Async check if image has already been cached + * + * @param url image url + * @param completionBlock the block to be executed when the check is finished + * + * @note the completion block is always executed on the main queue + */ +- (void)cachedImageExistsForURL:(nullable NSURL *)url + completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock; + +/** + * Async check if image has already been cached on disk only + * + * @param url image url + * @param completionBlock the block to be executed when the check is finished + * + * @note the completion block is always executed on the main queue + */ +- (void)diskImageExistsForURL:(nullable NSURL *)url + completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock; + + +/** + *Return the cache key for a given URL + */ +- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url; + +@end diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageManager.m b/Pods/SDWebImage/SDWebImage/SDWebImageManager.m new file mode 100644 index 0000000..24da020 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageManager.m @@ -0,0 +1,366 @@ +/* + * 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 "NSImage+WebCache.h" +#import + +#define LOCK(lock) dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER); +#define UNLOCK(lock) dispatch_semaphore_signal(lock); + +@interface SDWebImageCombinedOperation : NSObject + +@property (assign, nonatomic, getter = isCancelled) BOOL cancelled; +@property (strong, nonatomic, nullable) SDWebImageDownloadToken *downloadToken; +@property (strong, nonatomic, nullable) NSOperation *cacheOperation; +@property (weak, nonatomic, nullable) SDWebImageManager *manager; + +@end + +@interface SDWebImageManager () + +@property (strong, nonatomic, readwrite, nonnull) SDImageCache *imageCache; +@property (strong, nonatomic, readwrite, nonnull) SDWebImageDownloader *imageDownloader; +@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 + ++ (nonnull instancetype)sharedManager { + static dispatch_once_t once; + static id instance; + dispatch_once(&once, ^{ + instance = [self new]; + }); + return instance; +} + +- (nonnull instancetype)init { + SDImageCache *cache = [SDImageCache sharedImageCache]; + SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader]; + return [self initWithCache:cache downloader:downloader]; +} + +- (nonnull instancetype)initWithCache:(nonnull SDImageCache *)cache downloader:(nonnull SDWebImageDownloader *)downloader { + if ((self = [super init])) { + _imageCache = cache; + _imageDownloader = downloader; + _failedURLs = [NSMutableSet new]; + _failedURLsLock = dispatch_semaphore_create(1); + _runningOperations = [NSMutableSet new]; + _runningOperationsLock = dispatch_semaphore_create(1); + } + return self; +} + +- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url { + if (!url) { + return @""; + } + + if (self.cacheKeyFilter) { + return self.cacheKeyFilter(url); + } else { + return url.absoluteString; + } +} + +- (nullable UIImage *)scaledImageForKey:(nullable NSString *)key image:(nullable UIImage *)image { + return SDScaledImageForKey(key, image); +} + +- (void)cachedImageExistsForURL:(nullable NSURL *)url + completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock { + NSString *key = [self cacheKeyForURL:url]; + + BOOL isInMemoryCache = ([self.imageCache imageFromMemoryCacheForKey:key] != nil); + + if (isInMemoryCache) { + // making sure we call the completion block on the main queue + dispatch_async(dispatch_get_main_queue(), ^{ + if (completionBlock) { + completionBlock(YES); + } + }); + return; + } + + [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { + // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch + if (completionBlock) { + completionBlock(isInDiskCache); + } + }]; +} + +- (void)diskImageExistsForURL:(nullable NSURL *)url + completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock { + NSString *key = [self cacheKeyForURL:url]; + + [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) { + // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch + if (completionBlock) { + completionBlock(isInDiskCache); + } + }]; +} + +- (id )loadImageWithURL:(nullable NSURL *)url + options:(SDWebImageOptions)options + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable 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) { + LOCK(self.failedURLsLock); + isFailedUrl = [self.failedURLs containsObject:url]; + UNLOCK(self.failedURLsLock); + } + + if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) { + [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil] url:url]; + return operation; + } + + LOCK(self.runningOperationsLock); + [self.runningOperations addObject:operation]; + UNLOCK(self.runningOperationsLock); + NSString *key = [self cacheKeyForURL:url]; + + SDImageCacheOptions cacheOptions = 0; + if (options & SDWebImageQueryDataWhenInMemory) cacheOptions |= SDImageCacheQueryDataWhenInMemory; + if (options & SDWebImageQueryDiskSync) cacheOptions |= SDImageCacheQueryDiskSync; + if (options & SDWebImageScaleDownLargeImages) cacheOptions |= SDImageCacheScaleDownLargeImages; + + __weak SDWebImageCombinedOperation *weakOperation = operation; + operation.cacheOperation = [self.imageCache queryCacheOperationForKey:key options:cacheOptions done:^(UIImage *cachedImage, NSData *cachedData, SDImageCacheType cacheType) { + __strong __typeof(weakOperation) strongOperation = weakOperation; + if (!strongOperation || strongOperation.isCancelled) { + [self safelyRemoveOperationFromRunning:strongOperation]; + return; + } + + // Check whether we should download image from network + BOOL shouldDownload = (!(options & SDWebImageFromCacheOnly)) + && (!cachedImage || options & SDWebImageRefreshCached) + && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL: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:strongOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url]; + } + + // download if no image or requested to refresh anyway, and download allowed by delegate + SDWebImageDownloaderOptions downloaderOptions = 0; + if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority; + if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload; + 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 (cachedImage && options & SDWebImageRefreshCached) { + // force progressive off if image already cached but forced refreshing + downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload; + // ignore image read from NSURLCache if image if cached but force refreshing + downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse; + } + + // `SDWebImageCombinedOperation` -> `SDWebImageDownloadToken` -> `downloadOperationCancelToken`, which is a `SDCallbacksDictionary` and retain the completed block below, so we need weak-strong again to avoid retain cycle + __weak typeof(strongOperation) weakSubOperation = strongOperation; + strongOperation.downloadToken = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *downloadedData, NSError *error, BOOL finished) { + __strong typeof(weakSubOperation) strongSubOperation = weakSubOperation; + if (!strongSubOperation || strongSubOperation.isCancelled) { + // Do nothing if the operation was cancelled + // See #699 for more details + // if we would call the completedBlock, there could be a race condition between this block and another completedBlock for the same object, so if this one is called second, we will overwrite the new data + } else if (error) { + [self callCompletionBlockForOperation:strongSubOperation completion:completedBlock error:error url:url]; + BOOL shouldBlockFailedURL; + // Check whether we should block failed url + if ([self.delegate respondsToSelector:@selector(imageManager:shouldBlockFailedURL:withError:)]) { + shouldBlockFailedURL = [self.delegate imageManager:self shouldBlockFailedURL:url withError:error]; + } else { + 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); + } + + if (shouldBlockFailedURL) { + LOCK(self.failedURLsLock); + [self.failedURLs addObject:url]; + UNLOCK(self.failedURLsLock); + } + } + else { + if ((options & SDWebImageRetryFailed)) { + LOCK(self.failedURLsLock); + [self.failedURLs removeObject:url]; + UNLOCK(self.failedURLsLock); + } + + BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly); + + // We've done the scale process in SDWebImageDownloader with the shared manager, this is used for custom manager and avoid extra scale. + if (self != [SDWebImageManager sharedManager] && self.cacheKeyFilter && downloadedImage) { + downloadedImage = [self scaledImageForKey:key image:downloadedImage]; + } + + if (options & SDWebImageRefreshCached && cachedImage && !downloadedImage) { + // Image refresh hit the NSURLCache cache, do not call the completion block + } else if (downloadedImage && (!downloadedImage.images || (options & SDWebImageTransformAnimatedImage)) && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ + UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url]; + + if (transformedImage && finished) { + BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage]; + NSData *cacheData; + // pass nil if the image was transformed, so we can recalculate the data from the image + if (self.cacheSerializer) { + cacheData = self.cacheSerializer(transformedImage, (imageWasTransformed ? nil : downloadedData), url); + } else { + cacheData = (imageWasTransformed ? nil : downloadedData); + } + [self.imageCache storeImage:transformedImage imageData:cacheData forKey:key toDisk:cacheOnDisk completion:nil]; + } + + [self callCompletionBlockForOperation:strongSubOperation completion:completedBlock image:transformedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url]; + }); + } else { + if (downloadedImage && finished) { + if (self.cacheSerializer) { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ + NSData *cacheData = self.cacheSerializer(downloadedImage, downloadedData, url); + [self.imageCache storeImage:downloadedImage imageData:cacheData forKey:key toDisk:cacheOnDisk completion:nil]; + }); + } else { + [self.imageCache storeImage:downloadedImage imageData:downloadedData forKey:key toDisk:cacheOnDisk completion:nil]; + } + } + [self callCompletionBlockForOperation:strongSubOperation completion:completedBlock image:downloadedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url]; + } + } + + if (finished) { + [self safelyRemoveOperationFromRunning:strongSubOperation]; + } + }]; + } else if (cachedImage) { + [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url]; + [self safelyRemoveOperationFromRunning:strongOperation]; + } else { + // Image not in cache and download disallowed by delegate + [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:nil data:nil error:nil cacheType:SDImageCacheTypeNone finished:YES url:url]; + [self safelyRemoveOperationFromRunning:strongOperation]; + } + }]; + + return operation; +} + +- (void)saveImageToCache:(nullable UIImage *)image forURL:(nullable NSURL *)url { + if (image && url) { + NSString *key = [self cacheKeyForURL:url]; + [self.imageCache storeImage:image forKey:key toDisk:YES completion:nil]; + } +} + +- (void)cancelAll { + LOCK(self.runningOperationsLock); + NSSet *copiedOperations = [self.runningOperations copy]; + UNLOCK(self.runningOperationsLock); + [copiedOperations makeObjectsPerformSelector:@selector(cancel)]; // This will call `safelyRemoveOperationFromRunning:` and remove from the array +} + +- (BOOL)isRunning { + BOOL isRunning = NO; + LOCK(self.runningOperationsLock); + isRunning = (self.runningOperations.count > 0); + UNLOCK(self.runningOperationsLock); + return isRunning; +} + +- (void)safelyRemoveOperationFromRunning:(nullable SDWebImageCombinedOperation*)operation { + if (!operation) { + return; + } + LOCK(self.runningOperationsLock); + [self.runningOperations removeObject:operation]; + UNLOCK(self.runningOperationsLock); +} + +- (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 (operation && !operation.isCancelled && completionBlock) { + completionBlock(image, data, error, cacheType, finished, url); + } + }); +} + +@end + + +@implementation SDWebImageCombinedOperation + +- (void)cancel { + @synchronized(self) { + self.cancelled = YES; + if (self.cacheOperation) { + [self.cacheOperation cancel]; + self.cacheOperation = nil; + } + if (self.downloadToken) { + [self.manager.imageDownloader cancel:self.downloadToken]; + } + [self.manager safelyRemoveOperationFromRunning:self]; + } +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageOperation.h b/Pods/SDWebImage/SDWebImage/SDWebImageOperation.h new file mode 100644 index 0000000..71094ee --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageOperation.h @@ -0,0 +1,15 @@ +/* + * 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 + +@protocol SDWebImageOperation + +- (void)cancel; + +@end diff --git a/Pods/SDWebImage/SDWebImage/SDWebImagePrefetcher.h b/Pods/SDWebImage/SDWebImage/SDWebImagePrefetcher.h new file mode 100644 index 0000000..93357f4 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImagePrefetcher.h @@ -0,0 +1,112 @@ +/* + * 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; + +@protocol SDWebImagePrefetcherDelegate + +@optional + +/** + * Called when an image was prefetched. + * + * @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. + * @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 + */ +@property (strong, nonatomic, readonly, nonnull) SDWebImageManager *manager; + +/** + * Maximum number of URLs to prefetch at the same time. Defaults to 3. + */ +@property (nonatomic, assign) NSUInteger maxConcurrentDownloads; + +/** + * SDWebImageOptions for prefetcher. Defaults to SDWebImageLowPriority. + */ +@property (nonatomic, assign) SDWebImageOptions options; + +/** + * Queue options for Prefetcher. Defaults to Main Queue. + */ +@property (strong, nonatomic, nonnull) dispatch_queue_t prefetcherQueue; + +@property (weak, nonatomic, nullable) id delegate; + +/** + * Return the global image prefetcher instance. + */ ++ (nonnull instancetype)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, + * currently one image is downloaded at a time, + * and skips images for failed downloads and proceed to the next image in the list. + * Any previously-running prefetch operations are canceled. + * + * @param urls list of URLs to prefetch + */ +- (void)prefetchURLs:(nullable NSArray *)urls; + +/** + * Assign list of URLs to let SDWebImagePrefetcher to queue the prefetching, + * currently one image is downloaded at a time, + * and skips images for failed downloads and proceed to the next image in the list. + * Any previously-running prefetch operations are canceled. + * + * @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 prefetching is completed + * first param is the number of completed (successful or not) requests, + * second parameter is the number of skipped requests + */ +- (void)prefetchURLs:(nullable NSArray *)urls + progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock + completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock; + +/** + * Remove and cancel queued list + */ +- (void)cancelPrefetching; + + +@end diff --git a/Pods/SDWebImage/SDWebImage/SDWebImagePrefetcher.m b/Pods/SDWebImage/SDWebImage/SDWebImagePrefetcher.m new file mode 100644 index 0000000..18c433e --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImagePrefetcher.m @@ -0,0 +1,144 @@ +/* + * 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" + +@interface SDWebImagePrefetcher () + +@property (strong, nonatomic, nonnull) SDWebImageManager *manager; +@property (strong, atomic, nullable) NSArray *prefetchURLs; // may be accessed from different queue +@property (assign, nonatomic) NSUInteger requestedCount; +@property (assign, nonatomic) NSUInteger skippedCount; +@property (assign, nonatomic) NSUInteger finishedCount; +@property (assign, nonatomic) NSTimeInterval startedTime; +@property (copy, nonatomic, nullable) SDWebImagePrefetcherCompletionBlock completionBlock; +@property (copy, nonatomic, nullable) SDWebImagePrefetcherProgressBlock progressBlock; + +@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; + _options = SDWebImageLowPriority; + _prefetcherQueue = dispatch_get_main_queue(); + self.maxConcurrentDownloads = 3; + } + return self; +} + +- (void)setMaxConcurrentDownloads:(NSUInteger)maxConcurrentDownloads { + self.manager.imageDownloader.maxConcurrentDownloads = maxConcurrentDownloads; +} + +- (NSUInteger)maxConcurrentDownloads { + return self.manager.imageDownloader.maxConcurrentDownloads; +} + +- (void)startPrefetchingAtIndex:(NSUInteger)index { + NSURL *currentURL; + @synchronized(self) { + if (index >= self.prefetchURLs.count) return; + currentURL = self.prefetchURLs[index]; + self.requestedCount++; + } + [self.manager loadImageWithURL:currentURL options:self.options progress:nil completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + if (!finished) return; + self.finishedCount++; + + if (self.progressBlock) { + self.progressBlock(self.finishedCount,(self.prefetchURLs).count); + } + if (!image) { + // Add last failed + self.skippedCount++; + } + if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)]) { + [self.delegate imagePrefetcher:self + didPrefetchURL:currentURL + finishedCount:self.finishedCount + totalCount:self.prefetchURLs.count + ]; + } + if (self.prefetchURLs.count > self.requestedCount) { + dispatch_async(self.prefetcherQueue, ^{ + // we need dispatch to avoid function recursion call. This can prevent stack overflow even for huge urls list + [self startPrefetchingAtIndex:self.requestedCount]; + }); + } else if (self.finishedCount == self.requestedCount) { + [self reportStatus]; + if (self.completionBlock) { + self.completionBlock(self.finishedCount, self.skippedCount); + self.completionBlock = nil; + } + self.progressBlock = nil; + } + }]; +} + +- (void)reportStatus { + NSUInteger total = (self.prefetchURLs).count; + if ([self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)]) { + [self.delegate imagePrefetcher:self + didFinishWithTotalCount:(total - self.skippedCount) + skippedCount:self.skippedCount + ]; + } +} + +- (void)prefetchURLs:(nullable NSArray *)urls { + [self prefetchURLs:urls progress:nil completed:nil]; +} + +- (void)prefetchURLs:(nullable NSArray *)urls + progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock + completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock { + [self cancelPrefetching]; // Prevent duplicate prefetch request + self.startedTime = CFAbsoluteTimeGetCurrent(); + self.prefetchURLs = urls; + self.completionBlock = completionBlock; + self.progressBlock = progressBlock; + + if (urls.count == 0) { + if (completionBlock) { + completionBlock(0,0); + } + } else { + // Starts prefetching from the very first image on the list with the max allowed concurrency + NSUInteger listCount = self.prefetchURLs.count; + for (NSUInteger i = 0; i < self.maxConcurrentDownloads && self.requestedCount < listCount; i++) { + [self startPrefetchingAtIndex:i]; + } + } +} + +- (void)cancelPrefetching { + @synchronized(self) { + self.prefetchURLs = nil; + self.skippedCount = 0; + self.requestedCount = 0; + self.finishedCount = 0; + } + [self.manager cancelAll]; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageTransition.h b/Pods/SDWebImage/SDWebImage/SDWebImageTransition.h new file mode 100644 index 0000000..6740108 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/SDWebImageTransition.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 "SDWebImageCompat.h" + +#if SD_UIKIT || SD_MAC +#import "SDImageCache.h" + +// 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. +// 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. + +#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); + +@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 NS_AVAILABLE_MAC(10_7); +/** + 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) + +// class property is available in Xcode 8. We will drop the Xcode 7.3 support in 5.x +#if __has_feature(objc_class_property) +/// 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; +#else ++ (nonnull instancetype)fadeTransition; ++ (nonnull instancetype)flipFromLeftTransition; ++ (nonnull instancetype)flipFromRightTransition; ++ (nonnull instancetype)flipFromTopTransition; ++ (nonnull instancetype)flipFromBottomTransition; ++ (nonnull instancetype)curlUpTransition; ++ (nonnull instancetype)curlDownTransition; +#endif + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/SDWebImageTransition.m b/Pods/SDWebImage/SDWebImage/SDWebImageTransition.m new file mode 100644 index 0000000..b04a4c3 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/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/Pods/SDWebImage/SDWebImage/UIButton+WebCache.h b/Pods/SDWebImage/SDWebImage/UIButton+WebCache.h new file mode 100644 index 0000000..61fada6 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/UIButton+WebCache.h @@ -0,0 +1,255 @@ +/* + * 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 UIButtonView. + */ +@interface UIButton (WebCache) + +#pragma mark - Image + +/** + * Get the current image URL. + */ +- (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 imageView `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 imageView `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 imageView `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 imageView `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 imageView `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 imageView `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; + +#pragma mark - Background Image + +/** + * Get the current background image URL. + */ +- (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 backgroundImageView `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_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state NS_REFINED_FOR_SWIFT; + +/** + * Set the backgroundImageView `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_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder NS_REFINED_FOR_SWIFT; + +/** + * Set the backgroundImageView `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_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options NS_REFINED_FOR_SWIFT; + +/** + * Set the backgroundImageView `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_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the backgroundImageView `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_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + completed:(nullable SDExternalCompletionBlock)completedBlock NS_REFINED_FOR_SWIFT; + +/** + * Set the backgroundImageView `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_setBackgroundImageWithURL:(nullable NSURL *)url + forState:(UIControlState)state + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + 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/Pods/SDWebImage/SDWebImage/UIButton+WebCache.m b/Pods/SDWebImage/SDWebImage/UIButton+WebCache.m new file mode 100644 index 0000000..8cdadb6 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/UIButton+WebCache.m @@ -0,0 +1,181 @@ +/* + * 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" + +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 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 { + if (!url) { + [self.sd_imageURLStorage removeObjectForKey:imageURLKeyForState(state)]; + } else { + self.sd_imageURLStorage[imageURLKeyForState(state)] = url; + } + + __weak typeof(self)weakSelf = self; + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + operationKey:imageOperationKeyForState(state) + setImageBlock:^(UIImage *image, NSData *imageData) { + [weakSelf setImage:image forState:state]; + } + progress:nil + completed:completedBlock]; +} + +#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 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 { + if (!url) { + [self.sd_imageURLStorage removeObjectForKey:backgroundImageURLKeyForState(state)]; + } else { + self.sd_imageURLStorage[backgroundImageURLKeyForState(state)] = url; + } + + __weak typeof(self)weakSelf = self; + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + operationKey:backgroundImageOperationKeyForState(state) + setImageBlock:^(UIImage *image, NSData *imageData) { + [weakSelf setBackgroundImage:image forState:state]; + } + progress:nil + completed:completedBlock]; +} + +#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/Pods/SDWebImage/SDWebImage/UIImage+ForceDecode.h b/Pods/SDWebImage/SDWebImage/UIImage+ForceDecode.h new file mode 100644 index 0000000..708c37b --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/UIImage+ForceDecode.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 "SDWebImageCompat.h" + +@interface UIImage (ForceDecode) + ++ (nullable UIImage *)decodedImageWithImage:(nullable UIImage *)image; + ++ (nullable UIImage *)decodedAndScaledDownImageWithImage:(nullable UIImage *)image; + +@end diff --git a/Pods/SDWebImage/SDWebImage/UIImage+ForceDecode.m b/Pods/SDWebImage/SDWebImage/UIImage+ForceDecode.m new file mode 100644 index 0000000..ee55aee --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/UIImage+ForceDecode.m @@ -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 "UIImage+ForceDecode.h" +#import "SDWebImageCodersManager.h" + +@implementation UIImage (ForceDecode) + ++ (UIImage *)decodedImageWithImage:(UIImage *)image { + if (!image) { + return nil; + } + NSData *tempData; + return [[SDWebImageCodersManager sharedInstance] decompressedImageWithImage:image data:&tempData options:@{SDWebImageCoderScaleDownLargeImagesKey: @(NO)}]; +} + ++ (UIImage *)decodedAndScaledDownImageWithImage:(UIImage *)image { + if (!image) { + return nil; + } + NSData *tempData; + return [[SDWebImageCodersManager sharedInstance] decompressedImageWithImage:image data:&tempData options:@{SDWebImageCoderScaleDownLargeImagesKey: @(YES)}]; +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/UIImage+GIF.h b/Pods/SDWebImage/SDWebImage/UIImage+GIF.h new file mode 100644 index 0000000..a3a6646 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/UIImage+GIF.h @@ -0,0 +1,25 @@ +/* + * 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" + +@interface UIImage (GIF) + +/** + * Creates an animated UIImage from an NSData. + * For static GIF, will create an UIImage with `images` array set to nil. For animated GIF, will create an UIImage with valid `images` array. + */ ++ (UIImage *)sd_animatedGIFWithData:(NSData *)data; + +/** + * Checks if an UIImage instance is a GIF. Will use the `images` array. + */ +- (BOOL)isGIF; + +@end diff --git a/Pods/SDWebImage/SDWebImage/UIImage+GIF.m b/Pods/SDWebImage/SDWebImage/UIImage+GIF.m new file mode 100644 index 0000000..6fbca7a --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/UIImage+GIF.m @@ -0,0 +1,27 @@ +/* + * 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 "SDWebImageGIFCoder.h" +#import "NSImage+WebCache.h" + +@implementation UIImage (GIF) + ++ (UIImage *)sd_animatedGIFWithData:(NSData *)data { + if (!data) { + return nil; + } + return [[SDWebImageGIFCoder sharedCoder] decodedImageWithData:data]; +} + +- (BOOL)isGIF { + return (self.images != nil); +} + +@end diff --git a/Pods/SDWebImage/SDWebImage/UIImage+MultiFormat.h b/Pods/SDWebImage/SDWebImage/UIImage+MultiFormat.h new file mode 100644 index 0000000..5c6f473 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/UIImage+MultiFormat.h @@ -0,0 +1,37 @@ +/* + * 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" + +@interface UIImage (MultiFormat) + +/** + * UIKit: + * For static image format, this value is always 0. + * For animated image format, 0 means infinite looping. + * @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. + * 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; + +/** + * 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; + ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data; +- (nullable NSData *)sd_imageData; +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat; + +@end diff --git a/Pods/SDWebImage/SDWebImage/UIImage+MultiFormat.m b/Pods/SDWebImage/SDWebImage/UIImage+MultiFormat.m new file mode 100644 index 0000000..d3198d2 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/UIImage+MultiFormat.m @@ -0,0 +1,95 @@ +/* + * 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 "NSImage+WebCache.h" +#import "SDWebImageCodersManager.h" +#import "objc/runtime.h" + +@implementation UIImage (MultiFormat) + +#if SD_MAC +- (NSUInteger)sd_imageLoopCount { + NSUInteger imageLoopCount = 0; + for (NSImageRep *rep in self.representations) { + if ([rep isKindOfClass:[NSBitmapImageRep class]]) { + NSBitmapImageRep *bitmapRep = (NSBitmapImageRep *)rep; + imageLoopCount = [[bitmapRep valueForProperty:NSImageLoopCount] unsignedIntegerValue]; + break; + } + } + return imageLoopCount; +} + +- (void)setSd_imageLoopCount:(NSUInteger)sd_imageLoopCount { + for (NSImageRep *rep in self.representations) { + if ([rep isKindOfClass:[NSBitmapImageRep class]]) { + NSBitmapImageRep *bitmapRep = (NSBitmapImageRep *)rep; + [bitmapRep setProperty:NSImageLoopCount withValue:@(sd_imageLoopCount)]; + break; + } + } +} + +#else + +- (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); +} +#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 +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunguarded-availability" + if (&CGImageGetUTType != NULL) { + CFStringRef uttype = CGImageGetUTType(self.CGImage); + imageFormat = [NSData sd_imageFormatFromUTType:uttype]; + } +#pragma clang diagnostic pop + return imageFormat; +} + +- (void)setSd_imageFormat:(SDImageFormat)sd_imageFormat { + objc_setAssociatedObject(self, @selector(sd_imageFormat), @(sd_imageFormat), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + ++ (nullable UIImage *)sd_imageWithData:(nullable NSData *)data { + return [[SDWebImageCodersManager sharedInstance] decodedImageWithData:data]; +} + +- (nullable NSData *)sd_imageData { + return [self sd_imageDataAsFormat:SDImageFormatUndefined]; +} + +- (nullable NSData *)sd_imageDataAsFormat:(SDImageFormat)imageFormat { + NSData *imageData = nil; + if (self) { + imageData = [[SDWebImageCodersManager sharedInstance] encodedDataWithImage:self format:imageFormat]; + } + return imageData; +} + + +@end diff --git a/Pods/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.h b/Pods/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.h new file mode 100644 index 0000000..c806e5f --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.h @@ -0,0 +1,94 @@ +/* + * 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`. + * + * 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 SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.m b/Pods/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.m new file mode 100644 index 0000000..fb13bd8 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/UIImageView+HighlightedWebCache.m @@ -0,0 +1,52 @@ +/* + * 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" + +@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 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:(nullable NSURL *)url + options:(SDWebImageOptions)options + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + __weak typeof(self)weakSelf = self; + [self sd_internalSetImageWithURL:url + placeholderImage:nil + options:options + operationKey:@"UIImageViewImageOperationHighlighted" + setImageBlock:^(UIImage *image, NSData *imageData) { + weakSelf.highlightedImage = image; + } + progress:progressBlock + completed:completedBlock]; +} + +@end + +#endif diff --git a/Pods/SDWebImage/SDWebImage/UIImageView+WebCache.h b/Pods/SDWebImage/SDWebImage/UIImageView+WebCache.h new file mode 100644 index 0000000..d2992cb --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/UIImageView+WebCache.h @@ -0,0 +1,193 @@ +/* + * 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" + +/** + * Integrates SDWebImage async downloading and caching of remote images with UIImageView. + * + * 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: 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 + */ +@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`. + * + * 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 SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * Set the imageView `image` with an `url` and custom options. The placeholder image is from previous cached image and will use the provided one instead if the query failed. + * This method was designed to ensure that placeholder and query cache process happened in the same runloop to avoid flashing on cell during two `setImage:` call. But it's really misunderstanding and deprecated. + * This can be done by using `sd_setImageWithURL:` with `SDWebImageQueryDiskSync`. But take care that if the memory cache missed, query disk cache synchronously may reduce the frame rate + * + * 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. + * @deprecated consider using `SDWebImageQueryDiskSync` options with `sd_setImageWithURL:` instead + */ +- (void)sd_setImageWithPreviousCachedImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock __deprecated_msg("This method is misunderstanding and deprecated, consider using `SDWebImageQueryDiskSync` options with `sd_setImageWithURL:` instead"); + +#if SD_UIKIT + +#pragma mark - Animation of multiple images + +/** + * Download an array of images and starts them in an animation loop + * + * @param arrayOfURLs An array of NSURL + */ +- (void)sd_setAnimationImagesWithURLs:(nonnull NSArray *)arrayOfURLs; + +- (void)sd_cancelCurrentAnimationImagesLoad; + +#endif + +@end diff --git a/Pods/SDWebImage/SDWebImage/UIImageView+WebCache.m b/Pods/SDWebImage/SDWebImage/UIImageView+WebCache.m new file mode 100644 index 0000000..1baea5d --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/UIImageView+WebCache.m @@ -0,0 +1,139 @@ +/* + * 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 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 SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + [self sd_internalSetImageWithURL:url + placeholderImage:placeholder + options:options + operationKey:nil + setImageBlock:nil + progress:progressBlock + completed:completedBlock]; +} + +- (void)sd_setImageWithPreviousCachedImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:url]; + UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromCacheForKey:key]; + + [self sd_setImageWithURL:url placeholderImage:lastPreviousCachedImage ?: placeholder options:options progress:progressBlock completed:completedBlock]; +} + +#if SD_UIKIT + +#pragma mark - Animation of multiple images + +- (void)sd_setAnimationImagesWithURLs:(nonnull NSArray *)arrayOfURLs { + [self sd_cancelCurrentAnimationImagesLoad]; + NSPointerArray *operationsArray = [self sd_animationOperationArray]; + + [arrayOfURLs enumerateObjectsUsingBlock:^(NSURL *logoImageURL, NSUInteger idx, BOOL * _Nonnull stop) { + __weak __typeof(self) wself = self; + id operation = [[SDWebImageManager sharedManager] loadImageWithURL:logoImageURL options:0 progress:nil completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + __strong typeof(wself) sself = wself; + if (!sself) return; + dispatch_main_async_safe(^{ + [sself stopAnimating]; + if (sself && image) { + NSMutableArray *currentImages = [[sself animationImages] mutableCopy]; + if (!currentImages) { + currentImages = [[NSMutableArray alloc] init]; + } + + // We know what index objects should be at when they are returned so + // we will put the object at the index, filling any empty indexes + // with the image that was returned too "early". These images will + // be overwritten. (does not require additional sorting datastructure) + while ([currentImages count] < idx) { + [currentImages addObject:image]; + } + + currentImages[idx] = image; + + sself.animationImages = currentImages; + [sself setNeedsLayout]; + } + [sself startAnimating]; + }); + }]; + @synchronized (self) { + [operationsArray addPointer:(__bridge void *)(operation)]; + } + }]; +} + +static char animationLoadOperationKey; + +// element 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 +- (NSPointerArray *)sd_animationOperationArray { + @synchronized(self) { + NSPointerArray *operationsArray = objc_getAssociatedObject(self, &animationLoadOperationKey); + if (operationsArray) { + return operationsArray; + } + operationsArray = [NSPointerArray weakObjectsPointerArray]; + objc_setAssociatedObject(self, &animationLoadOperationKey, operationsArray, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + return operationsArray; + } +} + +- (void)sd_cancelCurrentAnimationImagesLoad { + NSPointerArray *operationsArray = [self sd_animationOperationArray]; + if (operationsArray) { + @synchronized (self) { + for (id operation in operationsArray) { + if ([operation conformsToProtocol:@protocol(SDWebImageOperation)]) { + [operation cancel]; + } + } + operationsArray.count = 0; + } + } +} +#endif + +@end diff --git a/Pods/SDWebImage/SDWebImage/UIView+WebCache.h b/Pods/SDWebImage/SDWebImage/UIView+WebCache.h new file mode 100644 index 0000000..026f1b3 --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/UIView+WebCache.h @@ -0,0 +1,139 @@ +/* + * 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" +#import "SDWebImageTransition.h" + +/** + A Dispatch group to maintain setImageBlock and completionBlock. This key should be used only internally and may be changed in the future. (dispatch_group_t) + */ +FOUNDATION_EXPORT NSString * _Nonnull const SDWebImageInternalSetImageGroupKey __deprecated_msg("Key Deprecated. Does nothing. This key should be used only internally"); +/** + 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 NSString * _Nonnull const SDWebImageExternalCustomManagerKey; +/** + 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); + +@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. + */ +- (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. You can also set a custom progress instance and let it been updated during image loading + * @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 operationKey A string to be used as the operation key. If nil, will use the class name + * @param setImageBlock Block used for custom set image code + * @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_internalSetImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + operationKey:(nullable NSString *)operationKey + setImageBlock:(nullable SDSetImageBlock)setImageBlock + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock; + +/** + * 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 operationKey A string to be used as the operation key. If nil, will use the class name + * @param setImageBlock Block used for custom set image code + * @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. + * @param context A context with extra information to perform specify changes or processes. + */ +- (void)sd_internalSetImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + operationKey:(nullable NSString *)operationKey + setImageBlock:(nullable SDSetImageBlock)setImageBlock + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock + context:(nullable NSDictionary *)context; + +/** + * 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; + +#if SD_UIKIT + +#pragma mark - Activity indicator + +/** + * Show activity UIActivityIndicatorView + */ +- (void)sd_setShowActivityIndicatorView:(BOOL)show; + +/** + * set desired UIActivityIndicatorViewStyle + * + * @param style The style of the UIActivityIndicatorView + */ +- (void)sd_setIndicatorStyle:(UIActivityIndicatorViewStyle)style; + +- (BOOL)sd_showActivityIndicatorView; +- (void)sd_addActivityIndicator; +- (void)sd_removeActivityIndicator; + +#endif + +#endif + +@end diff --git a/Pods/SDWebImage/SDWebImage/UIView+WebCache.m b/Pods/SDWebImage/SDWebImage/UIView+WebCache.m new file mode 100644 index 0000000..953415b --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/UIView+WebCache.m @@ -0,0 +1,351 @@ +/* + * 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" + +NSString * const SDWebImageInternalSetImageGroupKey = @"internalSetImageGroup"; +NSString * const SDWebImageExternalCustomManagerKey = @"externalCustomManager"; + +const int64_t SDWebImageProgressUnitCountUnknown = 1LL; + +static char imageURLKey; + +#if SD_UIKIT +static char TAG_ACTIVITY_INDICATOR; +static char TAG_ACTIVITY_STYLE; +static char TAG_ACTIVITY_SHOW; +#endif + +@implementation UIView (WebCache) + +- (nullable NSURL *)sd_imageURL { + return objc_getAssociatedObject(self, &imageURLKey); +} + +- (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 + operationKey:(nullable NSString *)operationKey + setImageBlock:(nullable SDSetImageBlock)setImageBlock + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock { + return [self sd_internalSetImageWithURL:url placeholderImage:placeholder options:options operationKey:operationKey setImageBlock:setImageBlock progress:progressBlock completed:completedBlock context:nil]; +} + +- (void)sd_internalSetImageWithURL:(nullable NSURL *)url + placeholderImage:(nullable UIImage *)placeholder + options:(SDWebImageOptions)options + operationKey:(nullable NSString *)operationKey + setImageBlock:(nullable SDSetImageBlock)setImageBlock + progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock + completed:(nullable SDExternalCompletionBlock)completedBlock + context:(nullable NSDictionary *)context { + NSString *validOperationKey = operationKey ?: NSStringFromClass([self class]); + [self sd_cancelImageLoadOperationWithKey:validOperationKey]; + objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + if (!(options & SDWebImageDelayPlaceholder)) { + dispatch_main_async_safe(^{ + [self sd_setImage:placeholder imageData:nil basedOnClassOrViaCustomSetImageBlock:setImageBlock]; + }); + } + + if (url) { +#if SD_UIKIT + // check if activityView is enabled or not + if ([self sd_showActivityIndicatorView]) { + [self sd_addActivityIndicator]; + } +#endif + + // reset the progress + self.sd_imageProgress.totalUnitCount = 0; + self.sd_imageProgress.completedUnitCount = 0; + + SDWebImageManager *manager; + if ([context valueForKey:SDWebImageExternalCustomManagerKey]) { + manager = (SDWebImageManager *)[context valueForKey:SDWebImageExternalCustomManagerKey]; + } else { + manager = [SDWebImageManager sharedManager]; + } + + __weak __typeof(self)wself = self; + SDWebImageDownloaderProgressBlock combinedProgressBlock = ^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) { + wself.sd_imageProgress.totalUnitCount = expectedSize; + wself.sd_imageProgress.completedUnitCount = receivedSize; + if (progressBlock) { + progressBlock(receivedSize, expectedSize, targetURL); + } + }; + id operation = [manager loadImageWithURL:url options:options progress:combinedProgressBlock completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { + __strong __typeof (wself) sself = wself; + if (!sself) { return; } +#if SD_UIKIT + [sself sd_removeActivityIndicator]; +#endif + // if the progress not been updated, mark it to complete state + if (finished && !error && sself.sd_imageProgress.totalUnitCount == 0 && sself.sd_imageProgress.completedUnitCount == 0) { + sself.sd_imageProgress.totalUnitCount = SDWebImageProgressUnitCountUnknown; + sself.sd_imageProgress.completedUnitCount = SDWebImageProgressUnitCountUnknown; + } + BOOL shouldCallCompletedBlock = finished || (options & SDWebImageAvoidAutoSetImage); + BOOL shouldNotSetImage = ((image && (options & SDWebImageAvoidAutoSetImage)) || + (!image && !(options & SDWebImageDelayPlaceholder))); + SDWebImageNoParamsBlock callCompletedBlockClojure = ^{ + if (!sself) { return; } + if (!shouldNotSetImage) { + [sself sd_setNeedsLayout]; + } + if (completedBlock && shouldCallCompletedBlock) { + completedBlock(image, error, cacheType, 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 = sself.sd_imageTransition; + } +#endif + dispatch_main_async_safe(^{ +#if SD_UIKIT || SD_MAC + [sself sd_setImage:targetImage imageData:targetData basedOnClassOrViaCustomSetImageBlock:setImageBlock transition:transition cacheType:cacheType imageURL:imageURL]; +#else + [sself sd_setImage:targetImage imageData:targetData basedOnClassOrViaCustomSetImageBlock:setImageBlock]; +#endif + callCompletedBlockClojure(); + }); + }]; + [self sd_setImageLoadOperation:operation forKey:validOperationKey]; + } else { + dispatch_main_async_safe(^{ +#if SD_UIKIT + [self sd_removeActivityIndicator]; +#endif + if (completedBlock) { + NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; + completedBlock(nil, error, SDImageCacheTypeNone, url); + } + }); + } +} + +- (void)sd_cancelCurrentImageLoad { + [self sd_cancelImageLoadOperationWithKey:NSStringFromClass([self class])]; +} + +- (void)sd_setImage:(UIImage *)image imageData:(NSData *)imageData basedOnClassOrViaCustomSetImageBlock:(SDSetImageBlock)setImageBlock { +#if SD_UIKIT || SD_MAC + [self sd_setImage:image imageData:imageData basedOnClassOrViaCustomSetImageBlock:setImageBlock transition:nil cacheType:0 imageURL:nil]; +#else + // watchOS does not support view transition. Simplify the logic + if (setImageBlock) { + setImageBlock(image, imageData); + } 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) { + imageView.image = setImage; + }; + } +#if SD_UIKIT + else if ([view isKindOfClass:[UIButton class]]) { + UIButton *button = (UIButton *)view; + finalSetImageBlock = ^(UIImage *setImage, NSData *setImageData){ + [button setImage:setImage forState:UIControlStateNormal]; + }; + } +#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); + } + 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 = (transition.animationOptions & SDWebImageAnimationOptionAllowsImplicitAnimation); + if (finalSetImageBlock && !transition.avoidAutoSetImage) { + finalSetImageBlock(image, imageData); + } + if (transition.animations) { + transition.animations(view, image); + } + } completionHandler:^{ + if (transition.completion) { + transition.completion(YES); + } + }]; + }]; +#endif + } else { + if (finalSetImageBlock) { + finalSetImageBlock(image, imageData); + } + } +} +#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); +} + +#if SD_UIKIT + +#pragma mark - Activity indicator +- (UIActivityIndicatorView *)activityIndicator { + return (UIActivityIndicatorView *)objc_getAssociatedObject(self, &TAG_ACTIVITY_INDICATOR); +} + +- (void)setActivityIndicator:(UIActivityIndicatorView *)activityIndicator { + objc_setAssociatedObject(self, &TAG_ACTIVITY_INDICATOR, activityIndicator, OBJC_ASSOCIATION_RETAIN); +} + +- (void)sd_setShowActivityIndicatorView:(BOOL)show { + objc_setAssociatedObject(self, &TAG_ACTIVITY_SHOW, @(show), OBJC_ASSOCIATION_RETAIN); +} + +- (BOOL)sd_showActivityIndicatorView { + return [objc_getAssociatedObject(self, &TAG_ACTIVITY_SHOW) boolValue]; +} + +- (void)sd_setIndicatorStyle:(UIActivityIndicatorViewStyle)style{ + objc_setAssociatedObject(self, &TAG_ACTIVITY_STYLE, [NSNumber numberWithInt:style], OBJC_ASSOCIATION_RETAIN); +} + +- (int)sd_getIndicatorStyle{ + return [objc_getAssociatedObject(self, &TAG_ACTIVITY_STYLE) intValue]; +} + +- (void)sd_addActivityIndicator { + dispatch_main_async_safe(^{ + if (!self.activityIndicator) { + self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:[self sd_getIndicatorStyle]]; + self.activityIndicator.translatesAutoresizingMaskIntoConstraints = NO; + + [self addSubview:self.activityIndicator]; + + [self addConstraint:[NSLayoutConstraint constraintWithItem:self.activityIndicator + attribute:NSLayoutAttributeCenterX + relatedBy:NSLayoutRelationEqual + toItem:self + attribute:NSLayoutAttributeCenterX + multiplier:1.0 + constant:0.0]]; + [self addConstraint:[NSLayoutConstraint constraintWithItem:self.activityIndicator + attribute:NSLayoutAttributeCenterY + relatedBy:NSLayoutRelationEqual + toItem:self + attribute:NSLayoutAttributeCenterY + multiplier:1.0 + constant:0.0]]; + } + [self.activityIndicator startAnimating]; + }); +} + +- (void)sd_removeActivityIndicator { + dispatch_main_async_safe(^{ + if (self.activityIndicator) { + [self.activityIndicator removeFromSuperview]; + self.activityIndicator = nil; + } + }); +} + +#endif + +#endif + +@end diff --git a/Pods/SDWebImage/SDWebImage/UIView+WebCacheOperation.h b/Pods/SDWebImage/SDWebImage/UIView+WebCacheOperation.h new file mode 100644 index 0000000..0be284b --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/UIView+WebCacheOperation.h @@ -0,0 +1,38 @@ +/* + * 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) + +/** + * 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/Pods/SDWebImage/SDWebImage/UIView+WebCacheOperation.m b/Pods/SDWebImage/SDWebImage/UIView+WebCacheOperation.m new file mode 100644 index 0000000..cd769be --- /dev/null +++ b/Pods/SDWebImage/SDWebImage/UIView+WebCacheOperation.m @@ -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 "UIView+WebCacheOperation.h" +#import "objc/runtime.h" + +static char loadOperationKey; + +// key is copy, 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; + } +} + +- (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/Pods/SocketRocket/LICENSE b/Pods/SocketRocket/LICENSE new file mode 100644 index 0000000..c01a79c --- /dev/null +++ b/Pods/SocketRocket/LICENSE @@ -0,0 +1,15 @@ + + Copyright 2012 Square Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/Pods/SocketRocket/README.rst b/Pods/SocketRocket/README.rst new file mode 100644 index 0000000..033c9dd --- /dev/null +++ b/Pods/SocketRocket/README.rst @@ -0,0 +1,246 @@ +SocketRocket Objective-C WebSocket Client (beta) +================================================ +A conforming WebSocket (`RFC 6455 `_) +client library. + +`Test results for SocketRocket here `_. +You can compare to what `modern browsers look like here +`_. + +SocketRocket currently conforms to all ~300 of `Autobahn +`_'s fuzzing tests (aside from +two UTF-8 ones where it is merely *non-strict*. tests 6.4.2 and 6.4.4) + +Features/Design +--------------- +- TLS (wss) support. It uses CFStream so we get this for *free* +- Uses NSStream/CFNetworking. Earlier implementations used ``dispatch_io``, + however, this proved to be make TLS nearly impossible. Also I wanted this to + work in iOS 4.x. (SocketRocket only supports 5.0 and above now) +- Uses ARC. It uses the 4.0 compatible subset (no weak refs). +- Seems to perform quite well +- Parallel architecture. Most of the work is done in background worker queues. +- Delegate-based. Had older versions that could use blocks too, but I felt it + didn't blend well with retain cycles and just objective C in general. + +Changes +------- + +v0.3.1-beta2 - 2013-01-12 +````````````````````````` + +- Stability fix for ``closeWithCode:reason:`` (Thanks @michaelpetrov!) +- Actually clean up the NSStreams and remove them from their runloops +- ``_SRRunLoopThread``'s ``main`` wasn't correctly wrapped with + ``@autoreleasepool`` + +v0.3.1-beta1 - 2013-01-12 +````````````````````````` + +- Cleaned up GCD so OS_OBJECT_USE_OBJC_RETAIN_RELEASE is optional +- Removed deprecated ``dispatch_get_current_queue`` in favor of ``dispatch_queue_set_specific`` and ``dispatch_get_specific`` +- Dropping support for iOS 4.0 (it may still work) + + +Installing (iOS) +---------------- +There's a few options. Choose one, or just figure it out + +- You can copy all the files in the SocketRocket group into your app. +- Include SocketRocket as a subproject and use libSocketRocket + + If you do this, you must add -ObjC to your "other linker flags" option + +- For OS X you will have to repackage make a .framework target. I will take + contributions. Message me if you are interested. + + +Depending on how you configure your project you may need to ``#import`` either +```` or ``"SRWebSocket.h"`` + +Framework Dependencies +`````````````````````` +Your .app must be linked against the following frameworks/dylibs + +- libicucore.dylib +- CFNetwork.framework +- Security.framework +- Foundation.framework + +Installing (OS X) +----------------- +SocketRocket now has (64-bit only) OS X support. ``SocketRocket.framework`` +inside Xcode project is for OS X only. It should be identical in function aside +from the unicode validation. ICU isn't shipped with OS X which is what the +original implementation used for unicode validation. The workaround is much +more rudimentary and less robust. + +1. Add SocketRocket.xcodeproj as either a subproject of your app or in your workspace. +2. Add ``SocketRocket.framework`` to the link libraries +3. If you don't have a "copy files" step for ``Framework``, create one +4. Add ``SocketRocket.framework`` to the "copy files" step. + +API +--- +The classes + +``SRWebSocket`` +``````````````` +The Web Socket. + +.. note:: ``SRWebSocket`` will retain itself between ``-(void)open`` and when it + closes, errors, or fails. This is similar to how ``NSURLConnection`` behaves. + (unlike ``NSURLConnection``, ``SRWebSocket`` won't retain the delegate) + +What you need to know + +.. code-block:: objective-c + + @interface SRWebSocket : NSObject + + // Make it with this + - (id)initWithURLRequest:(NSURLRequest *)request; + + // Set this before opening + @property (nonatomic, assign) id delegate; + + - (void)open; + + // Close it with this + - (void)close; + + // Send a UTF8 String or Data + - (void)send:(id)data; + + @end + +``SRWebSocketDelegate`` +``````````````````````` +You implement this + +.. code-block:: objective-c + + @protocol SRWebSocketDelegate + + - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message; + + @optional + + - (void)webSocketDidOpen:(SRWebSocket *)webSocket; + - (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error; + - (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean; + + @end + +Known Issues/Server Todo's +-------------------------- +- Needs auth delegates (like in NSURLConnection) +- Move the streams off the main runloop (most of the work is backgrounded uses + GCD, but I just haven't gotten around to moving it off the main loop since I + converted it from dispatch_io) +- Re-implement server. I removed an existing implementation as well because it + wasn't being used and I wasn't super happy with the interface. Will revisit + this. +- Separate framer and client logic. This will make it nicer when having a + server. + +Testing +------- +Included are setup scripts for the python testing environment. It comes +packaged with vitualenv so all the dependencies are installed in userland. + +To run the short test from the command line, run:: + + make test + +To run all the tests, run:: + + make test_all + +The short tests don't include the performance tests. (the test harness is +actually the bottleneck, not SocketRocket). + +The first time this is run, it may take a while to install the dependencies. It +will be smooth sailing after that. After the test runs the makefile will open +the results page in your browser. If nothing comes up, you failed. Working on +making this interface a bit nicer. + +To run from the app, choose the ``SocketRocket`` target and run the test action +(``cmd+u``). It runs the same thing, but makes it easier to debug. There is +some serious pre/post hooks in the Test action. You can edit it to customize +behavior. + +.. note:: Xcode only up to version 4.4 is currently supported for the test + harness + +TestChat Demo Application +------------------------- +SocketRocket includes a demo app, TestChat. It will "chat" with a listening +websocket on port 9900. + +It's a simple project. Uses storyboard. Storyboard is sweet. + + +TestChat Server +``````````````` +We've included a small server for the chat app. It has a simple function. +It will take a message and broadcast it to all other connected clients. + +We have to get some dependencies. We also want to reuse the virtualenv we made +when we ran the tests. If you haven't run the tests yet, go into the +SocketRocket root directory and type:: + + make test + +This will set up your `virtualenv `_. +Now, in your terminal:: + + source .env/bin/activate + pip install git+https://github.com/tornadoweb/tornado.git + +In the same terminal session, start the chatroom server:: + + python TestChatServer/py/chatroom.py + +There's also a Go implementation (with the latest weekly) where you can:: + + cd TestChatServer/go + go run chatroom.go + +Chatting +```````` +Now, start TestChat.app (just run the target in the Xcode project). If you had +it started already you can hit the refresh button to reconnect. It should say +"Connected!" on top. + +To talk with the app, open up your browser to `http://localhost:9000 `_ and +start chatting. + + +WebSocket Server Implementation Recommendations +----------------------------------------------- +SocketRocket has been used with the following libraries: + +- `Tornado `_ +- Go's `WebSocket package `_ or Gorilla's `version `_ +- `Autobahn `_ (using its fuzzing + client) + +The Tornado one is dirt simple and works like a charm. (`IPython notebook +`_ uses it +too). It's much easier to configure handlers and routes than in +Autobahn/twisted. + +As far as Go's goes, it works in my limited testing. I much prefer go's +concurrency model as well. Try it! You may like it. +It could use some more control over things such as pings, etc., but I +am sure it will come in time. + +Autobahn is a great test suite. The Python server code is good, and conforms +well (obviously). However for me, twisted would be a deal-breaker for writing +something new. I find it a bit too complex and heavy for a simple service. If +you are already using twisted though, Autobahn is probably for you. + +Contributing +------------ +We’re glad you’re interested in SocketRocket, and we’d love to see where you take it. Please read our `contributing guidelines `_ prior to submitting a Pull Request. \ No newline at end of file diff --git a/Pods/SocketRocket/SocketRocket/SRWebSocket.h b/Pods/SocketRocket/SocketRocket/SRWebSocket.h new file mode 100644 index 0000000..ca3a2c0 --- /dev/null +++ b/Pods/SocketRocket/SocketRocket/SRWebSocket.h @@ -0,0 +1,154 @@ +// +// Copyright 2012 Square Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#import +#import + +typedef NS_ENUM(NSInteger, SRReadyState) { + SR_CONNECTING = 0, + SR_OPEN = 1, + SR_CLOSING = 2, + SR_CLOSED = 3, +}; + +typedef enum SRStatusCode : NSInteger { + // 0–999: Reserved and not used. + SRStatusCodeNormal = 1000, + SRStatusCodeGoingAway = 1001, + SRStatusCodeProtocolError = 1002, + SRStatusCodeUnhandledType = 1003, + // 1004 reserved. + SRStatusNoStatusReceived = 1005, + SRStatusCodeAbnormal = 1006, + SRStatusCodeInvalidUTF8 = 1007, + SRStatusCodePolicyViolated = 1008, + SRStatusCodeMessageTooBig = 1009, + SRStatusCodeMissingExtension = 1010, + SRStatusCodeInternalError = 1011, + SRStatusCodeServiceRestart = 1012, + SRStatusCodeTryAgainLater = 1013, + // 1014: Reserved for future use by the WebSocket standard. + SRStatusCodeTLSHandshake = 1015, + // 1016–1999: Reserved for future use by the WebSocket standard. + // 2000–2999: Reserved for use by WebSocket extensions. + // 3000–3999: Available for use by libraries and frameworks. May not be used by applications. Available for registration at the IANA via first-come, first-serve. + // 4000–4999: Available for use by applications. +} SRStatusCode; + +@class SRWebSocket; + +extern NSString *const SRWebSocketErrorDomain; +extern NSString *const SRHTTPResponseErrorKey; + +#pragma mark - SRWebSocketDelegate + +@protocol SRWebSocketDelegate; + +#pragma mark - SRWebSocket + +@interface SRWebSocket : NSObject + +@property (nonatomic, weak) id delegate; + +@property (nonatomic, readonly) SRReadyState readyState; +@property (nonatomic, readonly, retain) NSURL *url; + + +@property (nonatomic, readonly) CFHTTPMessageRef receivedHTTPHeaders; + +// Optional array of cookies (NSHTTPCookie objects) to apply to the connections +@property (nonatomic, readwrite) NSArray * requestCookies; + +// This returns the negotiated protocol. +// It will be nil until after the handshake completes. +@property (nonatomic, readonly, copy) NSString *protocol; + +// Protocols should be an array of strings that turn into Sec-WebSocket-Protocol. +- (id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates; +- (id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols; +- (id)initWithURLRequest:(NSURLRequest *)request; + +// Some helper constructors. +- (id)initWithURL:(NSURL *)url protocols:(NSArray *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates; +- (id)initWithURL:(NSURL *)url protocols:(NSArray *)protocols; +- (id)initWithURL:(NSURL *)url; + +// Delegate queue will be dispatch_main_queue by default. +// You cannot set both OperationQueue and dispatch_queue. +- (void)setDelegateOperationQueue:(NSOperationQueue*) queue; +- (void)setDelegateDispatchQueue:(dispatch_queue_t) queue; + +// By default, it will schedule itself on +[NSRunLoop SR_networkRunLoop] using defaultModes. +- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; +- (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; + +// SRWebSockets are intended for one-time-use only. Open should be called once and only once. +- (void)open; + +- (void)close; +- (void)closeWithCode:(NSInteger)code reason:(NSString *)reason; + +// Send a UTF8 String or Data. +- (void)send:(id)data; + +// Send Data (can be nil) in a ping message. +- (void)sendPing:(NSData *)data; + +@end + +#pragma mark - SRWebSocketDelegate + +@protocol SRWebSocketDelegate + +// message will either be an NSString if the server is using text +// or NSData if the server is using binary. +- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message; + +@optional + +- (void)webSocketDidOpen:(SRWebSocket *)webSocket; +- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error; +- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean; +- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload; + +// Return YES to convert messages sent as Text to an NSString. Return NO to skip NSData -> NSString conversion for Text messages. Defaults to YES. +- (BOOL)webSocketShouldConvertTextFrameToString:(SRWebSocket *)webSocket; + +@end + +#pragma mark - NSURLRequest (SRCertificateAdditions) + +@interface NSURLRequest (SRCertificateAdditions) + +@property (nonatomic, retain, readonly) NSArray *SR_SSLPinnedCertificates; + +@end + +#pragma mark - NSMutableURLRequest (SRCertificateAdditions) + +@interface NSMutableURLRequest (SRCertificateAdditions) + +@property (nonatomic, retain) NSArray *SR_SSLPinnedCertificates; + +@end + +#pragma mark - NSRunLoop (SRWebSocket) + +@interface NSRunLoop (SRWebSocket) + ++ (NSRunLoop *)SR_networkRunLoop; + +@end diff --git a/Pods/SocketRocket/SocketRocket/SRWebSocket.m b/Pods/SocketRocket/SocketRocket/SRWebSocket.m new file mode 100644 index 0000000..b078dd2 --- /dev/null +++ b/Pods/SocketRocket/SocketRocket/SRWebSocket.m @@ -0,0 +1,1916 @@ +// +// Copyright 2012 Square Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + + +#import "SRWebSocket.h" + +#if TARGET_OS_IPHONE +#define HAS_ICU +#endif + +#ifdef HAS_ICU +#import +#endif + +#if TARGET_OS_IPHONE +#import +#else +#import +#endif + +#import +#import + +#if OS_OBJECT_USE_OBJC_RETAIN_RELEASE +#define sr_dispatch_retain(x) +#define sr_dispatch_release(x) +#define maybe_bridge(x) ((__bridge void *) x) +#else +#define sr_dispatch_retain(x) dispatch_retain(x) +#define sr_dispatch_release(x) dispatch_release(x) +#define maybe_bridge(x) (x) +#endif + +#if !__has_feature(objc_arc) +#error SocketRocket must be compiled with ARC enabled +#endif + + +typedef enum { + SROpCodeTextFrame = 0x1, + SROpCodeBinaryFrame = 0x2, + // 3-7 reserved. + SROpCodeConnectionClose = 0x8, + SROpCodePing = 0x9, + SROpCodePong = 0xA, + // B-F reserved. +} SROpCode; + +typedef struct { + BOOL fin; +// BOOL rsv1; +// BOOL rsv2; +// BOOL rsv3; + uint8_t opcode; + BOOL masked; + uint64_t payload_length; +} frame_header; + +static NSString *const SRWebSocketAppendToSecKeyString = @"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + +static inline int32_t validate_dispatch_data_partial_string(NSData *data); +static inline void SRFastLog(NSString *format, ...); + +@interface NSData (SRWebSocket) + +- (NSString *)stringBySHA1ThenBase64Encoding; + +@end + + +@interface NSString (SRWebSocket) + +- (NSString *)stringBySHA1ThenBase64Encoding; + +@end + + +@interface NSURL (SRWebSocket) + +// The origin isn't really applicable for a native application. +// So instead, just map ws -> http and wss -> https. +- (NSString *)SR_origin; + +@end + + +@interface _SRRunLoopThread : NSThread + +@property (nonatomic, readonly) NSRunLoop *runLoop; + +@end + + +static NSString *newSHA1String(const char *bytes, size_t length) { + uint8_t md[CC_SHA1_DIGEST_LENGTH]; + + assert(length >= 0); + assert(length <= UINT32_MAX); + CC_SHA1(bytes, (CC_LONG)length, md); + + NSData *data = [NSData dataWithBytes:md length:CC_SHA1_DIGEST_LENGTH]; + + if ([data respondsToSelector:@selector(base64EncodedStringWithOptions:)]) { + return [data base64EncodedStringWithOptions:0]; + } + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + return [data base64Encoding]; +#pragma clang diagnostic pop +} + +@implementation NSData (SRWebSocket) + +- (NSString *)stringBySHA1ThenBase64Encoding; +{ + return newSHA1String(self.bytes, self.length); +} + +@end + + +@implementation NSString (SRWebSocket) + +- (NSString *)stringBySHA1ThenBase64Encoding; +{ + return newSHA1String(self.UTF8String, self.length); +} + +@end + +NSString *const SRWebSocketErrorDomain = @"SRWebSocketErrorDomain"; +NSString *const SRHTTPResponseErrorKey = @"HTTPResponseStatusCode"; + +// Returns number of bytes consumed. Returning 0 means you didn't match. +// Sends bytes to callback handler; +typedef size_t (^stream_scanner)(NSData *collected_data); + +typedef void (^data_callback)(SRWebSocket *webSocket, NSData *data); + +@interface SRIOConsumer : NSObject { + stream_scanner _scanner; + data_callback _handler; + size_t _bytesNeeded; + BOOL _readToCurrentFrame; + BOOL _unmaskBytes; +} +@property (nonatomic, copy, readonly) stream_scanner consumer; +@property (nonatomic, copy, readonly) data_callback handler; +@property (nonatomic, assign) size_t bytesNeeded; +@property (nonatomic, assign, readonly) BOOL readToCurrentFrame; +@property (nonatomic, assign, readonly) BOOL unmaskBytes; + +@end + +// This class is not thread-safe, and is expected to always be run on the same queue. +@interface SRIOConsumerPool : NSObject + +- (id)initWithBufferCapacity:(NSUInteger)poolSize; + +- (SRIOConsumer *)consumerWithScanner:(stream_scanner)scanner handler:(data_callback)handler bytesNeeded:(size_t)bytesNeeded readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes; +- (void)returnConsumer:(SRIOConsumer *)consumer; + +@end + +@interface SRWebSocket () + +@property (nonatomic) SRReadyState readyState; + +@property (nonatomic) NSOperationQueue *delegateOperationQueue; +@property (nonatomic) dispatch_queue_t delegateDispatchQueue; + +// Specifies whether SSL trust chain should NOT be evaluated. +// By default this flag is set to NO, meaning only secure SSL connections are allowed. +// For DEBUG builds this flag is ignored, and SSL connections are allowed regardless +// of the certificate trust configuration +@property (nonatomic, readwrite) BOOL allowsUntrustedSSLCertificates; + +@end + + +@implementation SRWebSocket { + NSInteger _webSocketVersion; + + NSOperationQueue *_delegateOperationQueue; + dispatch_queue_t _delegateDispatchQueue; + + dispatch_queue_t _workQueue; + NSMutableArray *_consumers; + + NSInputStream *_inputStream; + NSOutputStream *_outputStream; + + NSMutableData *_readBuffer; + NSUInteger _readBufferOffset; + + NSMutableData *_outputBuffer; + NSUInteger _outputBufferOffset; + + uint8_t _currentFrameOpcode; + size_t _currentFrameCount; + size_t _readOpCount; + uint32_t _currentStringScanPosition; + NSMutableData *_currentFrameData; + + NSString *_closeReason; + + NSString *_secKey; + NSString *_basicAuthorizationString; + + BOOL _pinnedCertFound; + + uint8_t _currentReadMaskKey[4]; + size_t _currentReadMaskOffset; + + BOOL _consumerStopped; + + BOOL _closeWhenFinishedWriting; + BOOL _failed; + + BOOL _secure; + NSURLRequest *_urlRequest; + + BOOL _sentClose; + BOOL _didFail; + BOOL _cleanupScheduled; + int _closeCode; + + BOOL _isPumping; + + NSMutableSet *_scheduledRunloops; + + // We use this to retain ourselves. + __strong SRWebSocket *_selfRetain; + + NSArray *_requestedProtocols; + SRIOConsumerPool *_consumerPool; +} + +@synthesize delegate = _delegate; +@synthesize url = _url; +@synthesize readyState = _readyState; +@synthesize protocol = _protocol; + +static __strong NSData *CRLFCRLF; + ++ (void)initialize; +{ + CRLFCRLF = [[NSData alloc] initWithBytes:"\r\n\r\n" length:4]; +} + +- (id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates; +{ + self = [super init]; + if (self) { + assert(request.URL); + _url = request.URL; + _urlRequest = request; + _allowsUntrustedSSLCertificates = allowsUntrustedSSLCertificates; + + _requestedProtocols = [protocols copy]; + + [self _SR_commonInit]; + } + + return self; +} + +- (id)initWithURLRequest:(NSURLRequest *)request protocols:(NSArray *)protocols; +{ + return [self initWithURLRequest:request protocols:protocols allowsUntrustedSSLCertificates:NO]; +} + +- (id)initWithURLRequest:(NSURLRequest *)request; +{ + return [self initWithURLRequest:request protocols:nil]; +} + +- (id)initWithURL:(NSURL *)url; +{ + return [self initWithURL:url protocols:nil]; +} + +- (id)initWithURL:(NSURL *)url protocols:(NSArray *)protocols; +{ + NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; + return [self initWithURLRequest:request protocols:protocols]; +} + +- (id)initWithURL:(NSURL *)url protocols:(NSArray *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates; +{ + NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; + return [self initWithURLRequest:request protocols:protocols allowsUntrustedSSLCertificates:allowsUntrustedSSLCertificates]; +} + +- (void)_SR_commonInit; +{ + NSString *scheme = _url.scheme.lowercaseString; + assert([scheme isEqualToString:@"ws"] || [scheme isEqualToString:@"http"] || [scheme isEqualToString:@"wss"] || [scheme isEqualToString:@"https"]); + + if ([scheme isEqualToString:@"wss"] || [scheme isEqualToString:@"https"]) { + _secure = YES; + } + + _readyState = SR_CONNECTING; + _consumerStopped = YES; + _webSocketVersion = 13; + + _workQueue = dispatch_queue_create(NULL, DISPATCH_QUEUE_SERIAL); + + // Going to set a specific on the queue so we can validate we're on the work queue + dispatch_queue_set_specific(_workQueue, (__bridge void *)self, maybe_bridge(_workQueue), NULL); + + _delegateDispatchQueue = dispatch_get_main_queue(); + sr_dispatch_retain(_delegateDispatchQueue); + + _readBuffer = [[NSMutableData alloc] init]; + _outputBuffer = [[NSMutableData alloc] init]; + + _currentFrameData = [[NSMutableData alloc] init]; + + _consumers = [[NSMutableArray alloc] init]; + + _consumerPool = [[SRIOConsumerPool alloc] init]; + + _scheduledRunloops = [[NSMutableSet alloc] init]; + + [self _initializeStreams]; + + // default handlers +} + +- (void)assertOnWorkQueue; +{ + assert(dispatch_get_specific((__bridge void *)self) == maybe_bridge(_workQueue)); +} + +- (void)dealloc +{ + _inputStream.delegate = nil; + _outputStream.delegate = nil; + + [_inputStream close]; + [_outputStream close]; + + if (_workQueue) { + sr_dispatch_release(_workQueue); + _workQueue = NULL; + } + + if (_receivedHTTPHeaders) { + CFRelease(_receivedHTTPHeaders); + _receivedHTTPHeaders = NULL; + } + + if (_delegateDispatchQueue) { + sr_dispatch_release(_delegateDispatchQueue); + _delegateDispatchQueue = NULL; + } +} + +#ifndef NDEBUG + +- (void)setReadyState:(SRReadyState)aReadyState; +{ + assert(aReadyState > _readyState); + _readyState = aReadyState; +} + +#endif + +- (void)open; +{ + assert(_url); + NSAssert(_readyState == SR_CONNECTING, @"Cannot call -(void)open on SRWebSocket more than once"); + + _selfRetain = self; + + if (_urlRequest.timeoutInterval > 0) + { + dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, _urlRequest.timeoutInterval * NSEC_PER_SEC); + dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ + if (self.readyState == SR_CONNECTING) + [self _failWithError:[NSError errorWithDomain:@"com.squareup.SocketRocket" code:504 userInfo:@{NSLocalizedDescriptionKey: @"Timeout Connecting to Server"}]]; + }); + } + + [self openConnection]; +} + +// Calls block on delegate queue +- (void)_performDelegateBlock:(dispatch_block_t)block; +{ + if (_delegateOperationQueue) { + [_delegateOperationQueue addOperationWithBlock:block]; + } else { + assert(_delegateDispatchQueue); + dispatch_async(_delegateDispatchQueue, block); + } +} + +- (void)setDelegateDispatchQueue:(dispatch_queue_t)queue; +{ + if (queue) { + sr_dispatch_retain(queue); + } + + if (_delegateDispatchQueue) { + sr_dispatch_release(_delegateDispatchQueue); + } + + _delegateDispatchQueue = queue; +} + +- (BOOL)_checkHandshake:(CFHTTPMessageRef)httpMessage; +{ + NSString *acceptHeader = CFBridgingRelease(CFHTTPMessageCopyHeaderFieldValue(httpMessage, CFSTR("Sec-WebSocket-Accept"))); + + if (acceptHeader == nil) { + return NO; + } + + NSString *concattedString = [_secKey stringByAppendingString:SRWebSocketAppendToSecKeyString]; + NSString *expectedAccept = [concattedString stringBySHA1ThenBase64Encoding]; + + return [acceptHeader isEqualToString:expectedAccept]; +} + +- (void)_HTTPHeadersDidFinish; +{ + NSInteger responseCode = CFHTTPMessageGetResponseStatusCode(_receivedHTTPHeaders); + + if (responseCode >= 400) { + SRFastLog(@"Request failed with response code %d", responseCode); + [self _failWithError:[NSError errorWithDomain:SRWebSocketErrorDomain code:2132 userInfo:@{NSLocalizedDescriptionKey:[NSString stringWithFormat:@"received bad response code from server %ld", (long)responseCode], SRHTTPResponseErrorKey:@(responseCode)}]]; + return; + } + + if(![self _checkHandshake:_receivedHTTPHeaders]) { + [self _failWithError:[NSError errorWithDomain:SRWebSocketErrorDomain code:2133 userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Invalid Sec-WebSocket-Accept response"] forKey:NSLocalizedDescriptionKey]]]; + return; + } + + NSString *negotiatedProtocol = CFBridgingRelease(CFHTTPMessageCopyHeaderFieldValue(_receivedHTTPHeaders, CFSTR("Sec-WebSocket-Protocol"))); + if (negotiatedProtocol) { + // Make sure we requested the protocol + if ([_requestedProtocols indexOfObject:negotiatedProtocol] == NSNotFound) { + [self _failWithError:[NSError errorWithDomain:SRWebSocketErrorDomain code:2133 userInfo:[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Server specified Sec-WebSocket-Protocol that wasn't requested"] forKey:NSLocalizedDescriptionKey]]]; + return; + } + + _protocol = negotiatedProtocol; + } + + self.readyState = SR_OPEN; + + if (!_didFail) { + [self _readFrameNew]; + } + + [self _performDelegateBlock:^{ + if ([self.delegate respondsToSelector:@selector(webSocketDidOpen:)]) { + [self.delegate webSocketDidOpen:self]; + }; + }]; +} + + +- (void)_readHTTPHeader; +{ + if (_receivedHTTPHeaders == NULL) { + _receivedHTTPHeaders = CFHTTPMessageCreateEmpty(NULL, NO); + } + + [self _readUntilHeaderCompleteWithCallback:^(SRWebSocket *self, NSData *data) { + CFHTTPMessageAppendBytes(_receivedHTTPHeaders, (const UInt8 *)data.bytes, data.length); + + if (CFHTTPMessageIsHeaderComplete(_receivedHTTPHeaders)) { + SRFastLog(@"Finished reading headers %@", CFBridgingRelease(CFHTTPMessageCopyAllHeaderFields(_receivedHTTPHeaders))); + [self _HTTPHeadersDidFinish]; + } else { + [self _readHTTPHeader]; + } + }]; +} + +- (void)didConnect; +{ + SRFastLog(@"Connected"); + CFHTTPMessageRef request = CFHTTPMessageCreateRequest(NULL, CFSTR("GET"), (__bridge CFURLRef)_url, kCFHTTPVersion1_1); + + // Set host first so it defaults + CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Host"), (__bridge CFStringRef)(_url.port ? [NSString stringWithFormat:@"%@:%@", _url.host, _url.port] : _url.host)); + + NSMutableData *keyBytes = [[NSMutableData alloc] initWithLength:16]; + SecRandomCopyBytes(kSecRandomDefault, keyBytes.length, keyBytes.mutableBytes); + + if ([keyBytes respondsToSelector:@selector(base64EncodedStringWithOptions:)]) { + _secKey = [keyBytes base64EncodedStringWithOptions:0]; + } else { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + _secKey = [keyBytes base64Encoding]; +#pragma clang diagnostic pop + } + + assert([_secKey length] == 24); + + // Apply cookies if any have been provided + NSDictionary * cookies = [NSHTTPCookie requestHeaderFieldsWithCookies:[self requestCookies]]; + for (NSString * cookieKey in cookies) { + NSString * cookieValue = [cookies objectForKey:cookieKey]; + if ([cookieKey length] && [cookieValue length]) { + CFHTTPMessageSetHeaderFieldValue(request, (__bridge CFStringRef)cookieKey, (__bridge CFStringRef)cookieValue); + } + } + + // set header for http basic auth + if (_url.user.length && _url.password.length) { + NSData *userAndPassword = [[NSString stringWithFormat:@"%@:%@", _url.user, _url.password] dataUsingEncoding:NSUTF8StringEncoding]; + NSString *userAndPasswordBase64Encoded; + if ([keyBytes respondsToSelector:@selector(base64EncodedStringWithOptions:)]) { + userAndPasswordBase64Encoded = [userAndPassword base64EncodedStringWithOptions:0]; + } else { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + userAndPasswordBase64Encoded = [userAndPassword base64Encoding]; +#pragma clang diagnostic pop + } + _basicAuthorizationString = [NSString stringWithFormat:@"Basic %@", userAndPasswordBase64Encoded]; + CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Authorization"), (__bridge CFStringRef)_basicAuthorizationString); + } + + CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Upgrade"), CFSTR("websocket")); + CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Connection"), CFSTR("Upgrade")); + CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Sec-WebSocket-Key"), (__bridge CFStringRef)_secKey); + CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Sec-WebSocket-Version"), (__bridge CFStringRef)[NSString stringWithFormat:@"%ld", (long)_webSocketVersion]); + + CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Origin"), (__bridge CFStringRef)_url.SR_origin); + + if (_requestedProtocols) { + CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Sec-WebSocket-Protocol"), (__bridge CFStringRef)[_requestedProtocols componentsJoinedByString:@", "]); + } + + [_urlRequest.allHTTPHeaderFields enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + CFHTTPMessageSetHeaderFieldValue(request, (__bridge CFStringRef)key, (__bridge CFStringRef)obj); + }]; + + NSData *message = CFBridgingRelease(CFHTTPMessageCopySerializedMessage(request)); + + CFRelease(request); + + [self _writeData:message]; + [self _readHTTPHeader]; +} + +- (void)_initializeStreams; +{ + assert(_url.port.unsignedIntValue <= UINT32_MAX); + uint32_t port = _url.port.unsignedIntValue; + if (port == 0) { + if (!_secure) { + port = 80; + } else { + port = 443; + } + } + NSString *host = _url.host; + + CFReadStreamRef readStream = NULL; + CFWriteStreamRef writeStream = NULL; + + CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)host, port, &readStream, &writeStream); + + _outputStream = CFBridgingRelease(writeStream); + _inputStream = CFBridgingRelease(readStream); + + _inputStream.delegate = self; + _outputStream.delegate = self; +} + +- (void)_updateSecureStreamOptions; +{ + if (_secure) { + NSMutableDictionary *SSLOptions = [[NSMutableDictionary alloc] init]; + + [_outputStream setProperty:(__bridge id)kCFStreamSocketSecurityLevelNegotiatedSSL forKey:(__bridge id)kCFStreamPropertySocketSecurityLevel]; + + // If we're using pinned certs, don't validate the certificate chain + if ([_urlRequest SR_SSLPinnedCertificates].count) { + [SSLOptions setValue:@NO forKey:(__bridge id)kCFStreamSSLValidatesCertificateChain]; + } + +#if DEBUG + self.allowsUntrustedSSLCertificates = YES; +#endif + + if (self.allowsUntrustedSSLCertificates) { + [SSLOptions setValue:@NO forKey:(__bridge id)kCFStreamSSLValidatesCertificateChain]; + SRFastLog(@"Allowing connection to any root cert"); + } + + [_outputStream setProperty:SSLOptions + forKey:(__bridge id)kCFStreamPropertySSLSettings]; + } + + _inputStream.delegate = self; + _outputStream.delegate = self; + + [self setupNetworkServiceType:_urlRequest.networkServiceType]; +} + +- (void)setupNetworkServiceType:(NSURLRequestNetworkServiceType)requestNetworkServiceType +{ + NSString *networkServiceType; + switch (requestNetworkServiceType) { + case NSURLNetworkServiceTypeDefault: + break; + case NSURLNetworkServiceTypeVoIP: { + networkServiceType = NSStreamNetworkServiceTypeVoIP; +#if TARGET_OS_IPHONE && __IPHONE_9_0 + if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_8_3) { + static dispatch_once_t predicate; + dispatch_once(&predicate, ^{ + NSLog(@"SocketRocket: %@ - this service type is deprecated in favor of using PushKit for VoIP control", networkServiceType); + }); + } +#endif + break; + } + case NSURLNetworkServiceTypeVideo: + networkServiceType = NSStreamNetworkServiceTypeVideo; + break; + case NSURLNetworkServiceTypeBackground: + networkServiceType = NSStreamNetworkServiceTypeBackground; + break; + case NSURLNetworkServiceTypeVoice: + networkServiceType = NSStreamNetworkServiceTypeVoice; + break; + } + + if (networkServiceType != nil) { + [_inputStream setProperty:networkServiceType forKey:NSStreamNetworkServiceType]; + [_outputStream setProperty:networkServiceType forKey:NSStreamNetworkServiceType]; + } +} + +- (void)openConnection; +{ + [self _updateSecureStreamOptions]; + + if (!_scheduledRunloops.count) { + [self scheduleInRunLoop:[NSRunLoop SR_networkRunLoop] forMode:NSDefaultRunLoopMode]; + } + + + [_outputStream open]; + [_inputStream open]; +} + +- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; +{ + [_outputStream scheduleInRunLoop:aRunLoop forMode:mode]; + [_inputStream scheduleInRunLoop:aRunLoop forMode:mode]; + + [_scheduledRunloops addObject:@[aRunLoop, mode]]; +} + +- (void)unscheduleFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode; +{ + [_outputStream removeFromRunLoop:aRunLoop forMode:mode]; + [_inputStream removeFromRunLoop:aRunLoop forMode:mode]; + + [_scheduledRunloops removeObject:@[aRunLoop, mode]]; +} + +- (void)close; +{ + [self closeWithCode:SRStatusCodeNormal reason:nil]; +} + +- (void)closeWithCode:(NSInteger)code reason:(NSString *)reason; +{ + assert(code); + dispatch_async(_workQueue, ^{ + if (self.readyState == SR_CLOSING || self.readyState == SR_CLOSED) { + return; + } + + BOOL wasConnecting = self.readyState == SR_CONNECTING; + + self.readyState = SR_CLOSING; + + SRFastLog(@"Closing with code %d reason %@", code, reason); + + if (wasConnecting) { + [self closeConnection]; + return; + } + + size_t maxMsgSize = [reason maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + NSMutableData *mutablePayload = [[NSMutableData alloc] initWithLength:sizeof(uint16_t) + maxMsgSize]; + NSData *payload = mutablePayload; + + ((uint16_t *)mutablePayload.mutableBytes)[0] = EndianU16_BtoN(code); + + if (reason) { + NSRange remainingRange = {0}; + + NSUInteger usedLength = 0; + + BOOL success = [reason getBytes:(char *)mutablePayload.mutableBytes + sizeof(uint16_t) maxLength:payload.length - sizeof(uint16_t) usedLength:&usedLength encoding:NSUTF8StringEncoding options:NSStringEncodingConversionExternalRepresentation range:NSMakeRange(0, reason.length) remainingRange:&remainingRange]; + #pragma unused (success) + + assert(success); + assert(remainingRange.length == 0); + + if (usedLength != maxMsgSize) { + payload = [payload subdataWithRange:NSMakeRange(0, usedLength + sizeof(uint16_t))]; + } + } + + + [self _sendFrameWithOpcode:SROpCodeConnectionClose data:payload]; + }); +} + +- (void)_closeWithProtocolError:(NSString *)message; +{ + // Need to shunt this on the _callbackQueue first to see if they received any messages + [self _performDelegateBlock:^{ + [self closeWithCode:SRStatusCodeProtocolError reason:message]; + dispatch_async(_workQueue, ^{ + [self closeConnection]; + }); + }]; +} + +- (void)_failWithError:(NSError *)error; +{ + dispatch_async(_workQueue, ^{ + if (self.readyState != SR_CLOSED) { + _failed = YES; + [self _performDelegateBlock:^{ + if ([self.delegate respondsToSelector:@selector(webSocket:didFailWithError:)]) { + [self.delegate webSocket:self didFailWithError:error]; + } + }]; + + self.readyState = SR_CLOSED; + + SRFastLog(@"Failing with error %@", error.localizedDescription); + + [self closeConnection]; + [self _scheduleCleanup]; + } + }); +} + +- (void)_writeData:(NSData *)data; +{ + [self assertOnWorkQueue]; + + if (_closeWhenFinishedWriting) { + return; + } + [_outputBuffer appendData:data]; + [self _pumpWriting]; +} + +- (void)send:(id)data; +{ + NSAssert(self.readyState != SR_CONNECTING, @"Invalid State: Cannot call send: until connection is open"); + // TODO: maybe not copy this for performance + data = [data copy]; + dispatch_async(_workQueue, ^{ + if ([data isKindOfClass:[NSString class]]) { + [self _sendFrameWithOpcode:SROpCodeTextFrame data:[(NSString *)data dataUsingEncoding:NSUTF8StringEncoding]]; + } else if ([data isKindOfClass:[NSData class]]) { + [self _sendFrameWithOpcode:SROpCodeBinaryFrame data:data]; + } else if (data == nil) { + [self _sendFrameWithOpcode:SROpCodeTextFrame data:data]; + } else { + assert(NO); + } + }); +} + +- (void)sendPing:(NSData *)data; +{ + NSAssert(self.readyState == SR_OPEN, @"Invalid State: Cannot call send: until connection is open"); + // TODO: maybe not copy this for performance + data = [data copy] ?: [NSData data]; // It's okay for a ping to be empty + dispatch_async(_workQueue, ^{ + [self _sendFrameWithOpcode:SROpCodePing data:data]; + }); +} + +- (void)handlePing:(NSData *)pingData; +{ + // Need to pingpong this off _callbackQueue first to make sure messages happen in order + [self _performDelegateBlock:^{ + dispatch_async(_workQueue, ^{ + [self _sendFrameWithOpcode:SROpCodePong data:pingData]; + }); + }]; +} + +- (void)handlePong:(NSData *)pongData; +{ + SRFastLog(@"Received pong"); + [self _performDelegateBlock:^{ + if ([self.delegate respondsToSelector:@selector(webSocket:didReceivePong:)]) { + [self.delegate webSocket:self didReceivePong:pongData]; + } + }]; +} + +- (void)_handleMessage:(id)message +{ + SRFastLog(@"Received message"); + [self _performDelegateBlock:^{ + [self.delegate webSocket:self didReceiveMessage:message]; + }]; +} + + +static inline BOOL closeCodeIsValid(int closeCode) { + if (closeCode < 1000) { + return NO; + } + + if (closeCode >= 1000 && closeCode <= 1011) { + if (closeCode == 1004 || + closeCode == 1005 || + closeCode == 1006) { + return NO; + } + return YES; + } + + if (closeCode >= 3000 && closeCode <= 3999) { + return YES; + } + + if (closeCode >= 4000 && closeCode <= 4999) { + return YES; + } + + return NO; +} + +// Note from RFC: +// +// If there is a body, the first two +// bytes of the body MUST be a 2-byte unsigned integer (in network byte +// order) representing a status code with value /code/ defined in +// Section 7.4. Following the 2-byte integer the body MAY contain UTF-8 +// encoded data with value /reason/, the interpretation of which is not +// defined by this specification. + +- (void)handleCloseWithData:(NSData *)data; +{ + size_t dataSize = data.length; + __block uint16_t closeCode = 0; + + SRFastLog(@"Received close frame"); + + if (dataSize == 1) { + // TODO handle error + [self _closeWithProtocolError:@"Payload for close must be larger than 2 bytes"]; + return; + } else if (dataSize >= 2) { + [data getBytes:&closeCode length:sizeof(closeCode)]; + _closeCode = EndianU16_BtoN(closeCode); + if (!closeCodeIsValid(_closeCode)) { + [self _closeWithProtocolError:[NSString stringWithFormat:@"Cannot have close code of %d", _closeCode]]; + return; + } + if (dataSize > 2) { + _closeReason = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(2, dataSize - 2)] encoding:NSUTF8StringEncoding]; + if (!_closeReason) { + [self _closeWithProtocolError:@"Close reason MUST be valid UTF-8"]; + return; + } + } + } else { + _closeCode = SRStatusNoStatusReceived; + } + + [self assertOnWorkQueue]; + + if (self.readyState == SR_OPEN) { + [self closeWithCode:1000 reason:nil]; + } + dispatch_async(_workQueue, ^{ + [self closeConnection]; + }); +} + +- (void)closeConnection; +{ + [self assertOnWorkQueue]; + SRFastLog(@"Trying to disconnect"); + _closeWhenFinishedWriting = YES; + [self _pumpWriting]; +} + +- (void)_handleFrameWithData:(NSData *)frameData opCode:(NSInteger)opcode; +{ + // Check that the current data is valid UTF8 + + BOOL isControlFrame = (opcode == SROpCodePing || opcode == SROpCodePong || opcode == SROpCodeConnectionClose); + if (!isControlFrame) { + [self _readFrameNew]; + } else { + dispatch_async(_workQueue, ^{ + [self _readFrameContinue]; + }); + } + + //frameData will be copied before passing to handlers + //otherwise there can be misbehaviours when value at the pointer is changed + switch (opcode) { + case SROpCodeTextFrame: { + if ([self.delegate respondsToSelector:@selector(webSocketShouldConvertTextFrameToString:)] && ![self.delegate webSocketShouldConvertTextFrameToString:self]) { + [self _handleMessage:[frameData copy]]; + } else { + NSString *str = [[NSString alloc] initWithData:frameData encoding:NSUTF8StringEncoding]; + if (str == nil && frameData) { + [self closeWithCode:SRStatusCodeInvalidUTF8 reason:@"Text frames must be valid UTF-8"]; + dispatch_async(_workQueue, ^{ + [self closeConnection]; + }); + return; + } + [self _handleMessage:str]; + } + break; + } + case SROpCodeBinaryFrame: + [self _handleMessage:[frameData copy]]; + break; + case SROpCodeConnectionClose: + [self handleCloseWithData:[frameData copy]]; + break; + case SROpCodePing: + [self handlePing:[frameData copy]]; + break; + case SROpCodePong: + [self handlePong:[frameData copy]]; + break; + default: + [self _closeWithProtocolError:[NSString stringWithFormat:@"Unknown opcode %ld", (long)opcode]]; + // TODO: Handle invalid opcode + break; + } +} + +- (void)_handleFrameHeader:(frame_header)frame_header curData:(NSData *)curData; +{ + assert(frame_header.opcode != 0); + + if (self.readyState == SR_CLOSED) { + return; + } + + + BOOL isControlFrame = (frame_header.opcode == SROpCodePing || frame_header.opcode == SROpCodePong || frame_header.opcode == SROpCodeConnectionClose); + + if (isControlFrame && !frame_header.fin) { + [self _closeWithProtocolError:@"Fragmented control frames not allowed"]; + return; + } + + if (isControlFrame && frame_header.payload_length >= 126) { + [self _closeWithProtocolError:@"Control frames cannot have payloads larger than 126 bytes"]; + return; + } + + if (!isControlFrame) { + _currentFrameOpcode = frame_header.opcode; + _currentFrameCount += 1; + } + + if (frame_header.payload_length == 0) { + if (isControlFrame) { + [self _handleFrameWithData:curData opCode:frame_header.opcode]; + } else { + if (frame_header.fin) { + [self _handleFrameWithData:_currentFrameData opCode:frame_header.opcode]; + } else { + // TODO add assert that opcode is not a control; + [self _readFrameContinue]; + } + } + } else { + assert(frame_header.payload_length <= SIZE_T_MAX); + [self _addConsumerWithDataLength:(size_t)frame_header.payload_length callback:^(SRWebSocket *self, NSData *newData) { + if (isControlFrame) { + [self _handleFrameWithData:newData opCode:frame_header.opcode]; + } else { + if (frame_header.fin) { + [self _handleFrameWithData:self->_currentFrameData opCode:frame_header.opcode]; + } else { + // TODO add assert that opcode is not a control; + [self _readFrameContinue]; + } + + } + } readToCurrentFrame:!isControlFrame unmaskBytes:frame_header.masked]; + } +} + +/* From RFC: + + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-------+-+-------------+-------------------------------+ + |F|R|R|R| opcode|M| Payload len | Extended payload length | + |I|S|S|S| (4) |A| (7) | (16/64) | + |N|V|V|V| |S| | (if payload len==126/127) | + | |1|2|3| |K| | | + +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - + + | Extended payload length continued, if payload len == 127 | + + - - - - - - - - - - - - - - - +-------------------------------+ + | |Masking-key, if MASK set to 1 | + +-------------------------------+-------------------------------+ + | Masking-key (continued) | Payload Data | + +-------------------------------- - - - - - - - - - - - - - - - + + : Payload Data continued ... : + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + | Payload Data continued ... | + +---------------------------------------------------------------+ + */ + +static const uint8_t SRFinMask = 0x80; +static const uint8_t SROpCodeMask = 0x0F; +static const uint8_t SRRsvMask = 0x70; +static const uint8_t SRMaskMask = 0x80; +static const uint8_t SRPayloadLenMask = 0x7F; + + +- (void)_readFrameContinue; +{ + assert((_currentFrameCount == 0 && _currentFrameOpcode == 0) || (_currentFrameCount > 0 && _currentFrameOpcode > 0)); + + [self _addConsumerWithDataLength:2 callback:^(SRWebSocket *self, NSData *data) { + __block frame_header header = {0}; + + const uint8_t *headerBuffer = data.bytes; + assert(data.length >= 2); + + if (headerBuffer[0] & SRRsvMask) { + [self _closeWithProtocolError:@"Server used RSV bits"]; + return; + } + + uint8_t receivedOpcode = (SROpCodeMask & headerBuffer[0]); + + BOOL isControlFrame = (receivedOpcode == SROpCodePing || receivedOpcode == SROpCodePong || receivedOpcode == SROpCodeConnectionClose); + + if (!isControlFrame && receivedOpcode != 0 && self->_currentFrameCount > 0) { + [self _closeWithProtocolError:@"all data frames after the initial data frame must have opcode 0"]; + return; + } + + if (receivedOpcode == 0 && self->_currentFrameCount == 0) { + [self _closeWithProtocolError:@"cannot continue a message"]; + return; + } + + header.opcode = receivedOpcode == 0 ? self->_currentFrameOpcode : receivedOpcode; + + header.fin = !!(SRFinMask & headerBuffer[0]); + + + header.masked = !!(SRMaskMask & headerBuffer[1]); + header.payload_length = SRPayloadLenMask & headerBuffer[1]; + + headerBuffer = NULL; + + if (header.masked) { + [self _closeWithProtocolError:@"Client must receive unmasked data"]; + } + + size_t extra_bytes_needed = header.masked ? sizeof(_currentReadMaskKey) : 0; + + if (header.payload_length == 126) { + extra_bytes_needed += sizeof(uint16_t); + } else if (header.payload_length == 127) { + extra_bytes_needed += sizeof(uint64_t); + } + + if (extra_bytes_needed == 0) { + [self _handleFrameHeader:header curData:self->_currentFrameData]; + } else { + [self _addConsumerWithDataLength:extra_bytes_needed callback:^(SRWebSocket *self, NSData *data) { + size_t mapped_size = data.length; + #pragma unused (mapped_size) + const void *mapped_buffer = data.bytes; + size_t offset = 0; + + if (header.payload_length == 126) { + assert(mapped_size >= sizeof(uint16_t)); + uint16_t newLen = EndianU16_BtoN(*(uint16_t *)(mapped_buffer)); + header.payload_length = newLen; + offset += sizeof(uint16_t); + } else if (header.payload_length == 127) { + assert(mapped_size >= sizeof(uint64_t)); + header.payload_length = EndianU64_BtoN(*(uint64_t *)(mapped_buffer)); + offset += sizeof(uint64_t); + } else { + assert(header.payload_length < 126 && header.payload_length >= 0); + } + + if (header.masked) { + assert(mapped_size >= sizeof(_currentReadMaskOffset) + offset); + memcpy(self->_currentReadMaskKey, ((uint8_t *)mapped_buffer) + offset, sizeof(self->_currentReadMaskKey)); + } + + [self _handleFrameHeader:header curData:self->_currentFrameData]; + } readToCurrentFrame:NO unmaskBytes:NO]; + } + } readToCurrentFrame:NO unmaskBytes:NO]; +} + +- (void)_readFrameNew; +{ + dispatch_async(_workQueue, ^{ + [_currentFrameData setLength:0]; + + _currentFrameOpcode = 0; + _currentFrameCount = 0; + _readOpCount = 0; + _currentStringScanPosition = 0; + + [self _readFrameContinue]; + }); +} + +- (void)_pumpWriting; +{ + [self assertOnWorkQueue]; + + NSUInteger dataLength = _outputBuffer.length; + if (dataLength - _outputBufferOffset > 0 && _outputStream.hasSpaceAvailable) { + NSInteger bytesWritten = [_outputStream write:_outputBuffer.bytes + _outputBufferOffset maxLength:dataLength - _outputBufferOffset]; + if (bytesWritten == -1) { + [self _failWithError:[NSError errorWithDomain:SRWebSocketErrorDomain code:2145 userInfo:[NSDictionary dictionaryWithObject:@"Error writing to stream" forKey:NSLocalizedDescriptionKey]]]; + return; + } + + _outputBufferOffset += bytesWritten; + + if (_outputBufferOffset > 4096 && _outputBufferOffset > (_outputBuffer.length >> 1)) { + _outputBuffer = [[NSMutableData alloc] initWithBytes:(char *)_outputBuffer.bytes + _outputBufferOffset length:_outputBuffer.length - _outputBufferOffset]; + _outputBufferOffset = 0; + } + } + + if (_closeWhenFinishedWriting && + _outputBuffer.length - _outputBufferOffset == 0 && + (_inputStream.streamStatus != NSStreamStatusNotOpen && + _inputStream.streamStatus != NSStreamStatusClosed) && + !_sentClose) { + _sentClose = YES; + + @synchronized(self) { + [_outputStream close]; + [_inputStream close]; + + + for (NSArray *runLoop in [_scheduledRunloops copy]) { + [self unscheduleFromRunLoop:[runLoop objectAtIndex:0] forMode:[runLoop objectAtIndex:1]]; + } + } + + if (!_failed) { + [self _performDelegateBlock:^{ + if ([self.delegate respondsToSelector:@selector(webSocket:didCloseWithCode:reason:wasClean:)]) { + [self.delegate webSocket:self didCloseWithCode:_closeCode reason:_closeReason wasClean:YES]; + } + }]; + } + + [self _scheduleCleanup]; + } +} + +- (void)_addConsumerWithScanner:(stream_scanner)consumer callback:(data_callback)callback; +{ + [self assertOnWorkQueue]; + [self _addConsumerWithScanner:consumer callback:callback dataLength:0]; +} + +- (void)_addConsumerWithDataLength:(size_t)dataLength callback:(data_callback)callback readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes; +{ + [self assertOnWorkQueue]; + assert(dataLength); + + [_consumers addObject:[_consumerPool consumerWithScanner:nil handler:callback bytesNeeded:dataLength readToCurrentFrame:readToCurrentFrame unmaskBytes:unmaskBytes]]; + [self _pumpScanner]; +} + +- (void)_addConsumerWithScanner:(stream_scanner)consumer callback:(data_callback)callback dataLength:(size_t)dataLength; +{ + [self assertOnWorkQueue]; + [_consumers addObject:[_consumerPool consumerWithScanner:consumer handler:callback bytesNeeded:dataLength readToCurrentFrame:NO unmaskBytes:NO]]; + [self _pumpScanner]; +} + + +- (void)_scheduleCleanup +{ + @synchronized(self) { + if (_cleanupScheduled) { + return; + } + + _cleanupScheduled = YES; + + // Cleanup NSStream delegate's in the same RunLoop used by the streams themselves: + // This way we'll prevent race conditions between handleEvent and SRWebsocket's dealloc + NSTimer *timer = [NSTimer timerWithTimeInterval:(0.0f) target:self selector:@selector(_cleanupSelfReference:) userInfo:nil repeats:NO]; + [[NSRunLoop SR_networkRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; + } +} + +- (void)_cleanupSelfReference:(NSTimer *)timer +{ + @synchronized(self) { + // Nuke NSStream delegate's + _inputStream.delegate = nil; + _outputStream.delegate = nil; + + // Remove the streams, right now, from the networkRunLoop + [_inputStream close]; + [_outputStream close]; + } + + // Cleanup selfRetain in the same GCD queue as usual + dispatch_async(_workQueue, ^{ + _selfRetain = nil; + }); +} + + +static const char CRLFCRLFBytes[] = {'\r', '\n', '\r', '\n'}; + +- (void)_readUntilHeaderCompleteWithCallback:(data_callback)dataHandler; +{ + [self _readUntilBytes:CRLFCRLFBytes length:sizeof(CRLFCRLFBytes) callback:dataHandler]; +} + +- (void)_readUntilBytes:(const void *)bytes length:(size_t)length callback:(data_callback)dataHandler; +{ + // TODO optimize so this can continue from where we last searched + stream_scanner consumer = ^size_t(NSData *data) { + __block size_t found_size = 0; + __block size_t match_count = 0; + + size_t size = data.length; + const unsigned char *buffer = data.bytes; + for (size_t i = 0; i < size; i++ ) { + if (((const unsigned char *)buffer)[i] == ((const unsigned char *)bytes)[match_count]) { + match_count += 1; + if (match_count == length) { + found_size = i + 1; + break; + } + } else { + match_count = 0; + } + } + return found_size; + }; + [self _addConsumerWithScanner:consumer callback:dataHandler]; +} + + +// Returns true if did work +- (BOOL)_innerPumpScanner { + + BOOL didWork = NO; + + if (self.readyState >= SR_CLOSED) { + return didWork; + } + + if (!_consumers.count) { + return didWork; + } + + size_t curSize = _readBuffer.length - _readBufferOffset; + if (!curSize) { + return didWork; + } + + SRIOConsumer *consumer = [_consumers objectAtIndex:0]; + + size_t bytesNeeded = consumer.bytesNeeded; + + size_t foundSize = 0; + if (consumer.consumer) { + NSData *tempView = [NSData dataWithBytesNoCopy:(char *)_readBuffer.bytes + _readBufferOffset length:_readBuffer.length - _readBufferOffset freeWhenDone:NO]; + foundSize = consumer.consumer(tempView); + } else { + assert(consumer.bytesNeeded); + if (curSize >= bytesNeeded) { + foundSize = bytesNeeded; + } else if (consumer.readToCurrentFrame) { + foundSize = curSize; + } + } + + NSData *slice = nil; + if (consumer.readToCurrentFrame || foundSize) { + NSRange sliceRange = NSMakeRange(_readBufferOffset, foundSize); + slice = [_readBuffer subdataWithRange:sliceRange]; + + _readBufferOffset += foundSize; + + if (_readBufferOffset > 4096 && _readBufferOffset > (_readBuffer.length >> 1)) { + _readBuffer = [[NSMutableData alloc] initWithBytes:(char *)_readBuffer.bytes + _readBufferOffset length:_readBuffer.length - _readBufferOffset]; _readBufferOffset = 0; + } + + if (consumer.unmaskBytes) { + NSMutableData *mutableSlice = [slice mutableCopy]; + + NSUInteger len = mutableSlice.length; + uint8_t *bytes = mutableSlice.mutableBytes; + + for (NSUInteger i = 0; i < len; i++) { + bytes[i] = bytes[i] ^ _currentReadMaskKey[_currentReadMaskOffset % sizeof(_currentReadMaskKey)]; + _currentReadMaskOffset += 1; + } + + slice = mutableSlice; + } + + if (consumer.readToCurrentFrame) { + [_currentFrameData appendData:slice]; + + _readOpCount += 1; + + if (_currentFrameOpcode == SROpCodeTextFrame) { + // Validate UTF8 stuff. + size_t currentDataSize = _currentFrameData.length; + if (_currentFrameOpcode == SROpCodeTextFrame && currentDataSize > 0) { + // TODO: Optimize the crap out of this. Don't really have to copy all the data each time + + size_t scanSize = currentDataSize - _currentStringScanPosition; + + NSData *scan_data = [_currentFrameData subdataWithRange:NSMakeRange(_currentStringScanPosition, scanSize)]; + int32_t valid_utf8_size = validate_dispatch_data_partial_string(scan_data); + + if (valid_utf8_size == -1) { + [self closeWithCode:SRStatusCodeInvalidUTF8 reason:@"Text frames must be valid UTF-8"]; + dispatch_async(_workQueue, ^{ + [self closeConnection]; + }); + return didWork; + } else { + _currentStringScanPosition += valid_utf8_size; + } + } + + } + + consumer.bytesNeeded -= foundSize; + + if (consumer.bytesNeeded == 0) { + [_consumers removeObjectAtIndex:0]; + consumer.handler(self, nil); + [_consumerPool returnConsumer:consumer]; + didWork = YES; + } + } else if (foundSize) { + [_consumers removeObjectAtIndex:0]; + consumer.handler(self, slice); + [_consumerPool returnConsumer:consumer]; + didWork = YES; + } + } + return didWork; +} + +-(void)_pumpScanner; +{ + [self assertOnWorkQueue]; + + if (!_isPumping) { + _isPumping = YES; + } else { + return; + } + + while ([self _innerPumpScanner]) { + + } + + _isPumping = NO; +} + +//#define NOMASK + +static const size_t SRFrameHeaderOverhead = 32; + +- (void)_sendFrameWithOpcode:(SROpCode)opcode data:(id)data; +{ + [self assertOnWorkQueue]; + + if (nil == data) { + return; + } + + NSAssert([data isKindOfClass:[NSData class]] || [data isKindOfClass:[NSString class]], @"NSString or NSData"); + + size_t payloadLength = [data isKindOfClass:[NSString class]] ? [(NSString *)data lengthOfBytesUsingEncoding:NSUTF8StringEncoding] : [data length]; + + NSMutableData *frame = [[NSMutableData alloc] initWithLength:payloadLength + SRFrameHeaderOverhead]; + if (!frame) { + [self closeWithCode:SRStatusCodeMessageTooBig reason:@"Message too big"]; + return; + } + uint8_t *frame_buffer = (uint8_t *)[frame mutableBytes]; + + // set fin + frame_buffer[0] = SRFinMask | opcode; + + BOOL useMask = YES; +#ifdef NOMASK + useMask = NO; +#endif + + if (useMask) { + // set the mask and header + frame_buffer[1] |= SRMaskMask; + } + + size_t frame_buffer_size = 2; + + const uint8_t *unmasked_payload = NULL; + if ([data isKindOfClass:[NSData class]]) { + unmasked_payload = (uint8_t *)[data bytes]; + } else if ([data isKindOfClass:[NSString class]]) { + unmasked_payload = (const uint8_t *)[data UTF8String]; + } else { + return; + } + + if (payloadLength < 126) { + frame_buffer[1] |= payloadLength; + } else if (payloadLength <= UINT16_MAX) { + frame_buffer[1] |= 126; + *((uint16_t *)(frame_buffer + frame_buffer_size)) = EndianU16_BtoN((uint16_t)payloadLength); + frame_buffer_size += sizeof(uint16_t); + } else { + frame_buffer[1] |= 127; + *((uint64_t *)(frame_buffer + frame_buffer_size)) = EndianU64_BtoN((uint64_t)payloadLength); + frame_buffer_size += sizeof(uint64_t); + } + + if (!useMask) { + for (size_t i = 0; i < payloadLength; i++) { + frame_buffer[frame_buffer_size] = unmasked_payload[i]; + frame_buffer_size += 1; + } + } else { + uint8_t *mask_key = frame_buffer + frame_buffer_size; + SecRandomCopyBytes(kSecRandomDefault, sizeof(uint32_t), (uint8_t *)mask_key); + frame_buffer_size += sizeof(uint32_t); + + // TODO: could probably optimize this with SIMD + for (size_t i = 0; i < payloadLength; i++) { + frame_buffer[frame_buffer_size] = unmasked_payload[i] ^ mask_key[i % sizeof(uint32_t)]; + frame_buffer_size += 1; + } + } + + assert(frame_buffer_size <= [frame length]); + frame.length = frame_buffer_size; + + [self _writeData:frame]; +} + +- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode; +{ + __weak typeof(self) weakSelf = self; + + if (_secure && !_pinnedCertFound && (eventCode == NSStreamEventHasBytesAvailable || eventCode == NSStreamEventHasSpaceAvailable)) { + + NSArray *sslCerts = [_urlRequest SR_SSLPinnedCertificates]; + if (sslCerts) { + SecTrustRef secTrust = (__bridge SecTrustRef)[aStream propertyForKey:(__bridge id)kCFStreamPropertySSLPeerTrust]; + if (secTrust) { + NSInteger numCerts = SecTrustGetCertificateCount(secTrust); + for (NSInteger i = 0; i < numCerts && !_pinnedCertFound; i++) { + SecCertificateRef cert = SecTrustGetCertificateAtIndex(secTrust, i); + NSData *certData = CFBridgingRelease(SecCertificateCopyData(cert)); + + for (id ref in sslCerts) { + SecCertificateRef trustedCert = (__bridge SecCertificateRef)ref; + NSData *trustedCertData = CFBridgingRelease(SecCertificateCopyData(trustedCert)); + + if ([trustedCertData isEqualToData:certData]) { + _pinnedCertFound = YES; + break; + } + } + } + } + + if (!_pinnedCertFound) { + dispatch_async(_workQueue, ^{ + NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : @"Invalid server cert" }; + [weakSelf _failWithError:[NSError errorWithDomain:@"org.lolrus.SocketRocket" code:23556 userInfo:userInfo]]; + }); + return; + } else if (aStream == _outputStream) { + dispatch_async(_workQueue, ^{ + [self didConnect]; + }); + } + } + } + + dispatch_async(_workQueue, ^{ + [weakSelf safeHandleEvent:eventCode stream:aStream]; + }); +} + +- (void)safeHandleEvent:(NSStreamEvent)eventCode stream:(NSStream *)aStream +{ + switch (eventCode) { + case NSStreamEventOpenCompleted: { + SRFastLog(@"NSStreamEventOpenCompleted %@", aStream); + if (self.readyState >= SR_CLOSING) { + return; + } + assert(_readBuffer); + + // didConnect fires after certificate verification if we're using pinned certificates. + BOOL usingPinnedCerts = [[_urlRequest SR_SSLPinnedCertificates] count] > 0; + if ((!_secure || !usingPinnedCerts) && self.readyState == SR_CONNECTING && aStream == _inputStream) { + [self didConnect]; + } + [self _pumpWriting]; + [self _pumpScanner]; + break; + } + + case NSStreamEventErrorOccurred: { + SRFastLog(@"NSStreamEventErrorOccurred %@ %@", aStream, [[aStream streamError] copy]); + /// TODO specify error better! + [self _failWithError:aStream.streamError]; + _readBufferOffset = 0; + [_readBuffer setLength:0]; + break; + + } + + case NSStreamEventEndEncountered: { + [self _pumpScanner]; + SRFastLog(@"NSStreamEventEndEncountered %@", aStream); + if (aStream.streamError) { + [self _failWithError:aStream.streamError]; + } else { + dispatch_async(_workQueue, ^{ + if (self.readyState != SR_CLOSED) { + self.readyState = SR_CLOSED; + [self _scheduleCleanup]; + } + + if (!_sentClose && !_failed) { + _sentClose = YES; + // If we get closed in this state it's probably not clean because we should be sending this when we send messages + [self _performDelegateBlock:^{ + if ([self.delegate respondsToSelector:@selector(webSocket:didCloseWithCode:reason:wasClean:)]) { + [self.delegate webSocket:self didCloseWithCode:SRStatusCodeGoingAway reason:@"Stream end encountered" wasClean:NO]; + } + }]; + } + }); + } + + break; + } + + case NSStreamEventHasBytesAvailable: { + SRFastLog(@"NSStreamEventHasBytesAvailable %@", aStream); + const int bufferSize = 2048; + uint8_t buffer[bufferSize]; + + while (_inputStream.hasBytesAvailable) { + NSInteger bytes_read = [_inputStream read:buffer maxLength:bufferSize]; + + if (bytes_read > 0) { + [_readBuffer appendBytes:buffer length:bytes_read]; + } else if (bytes_read < 0) { + [self _failWithError:_inputStream.streamError]; + } + + if (bytes_read != bufferSize) { + break; + } + }; + [self _pumpScanner]; + break; + } + + case NSStreamEventHasSpaceAvailable: { + SRFastLog(@"NSStreamEventHasSpaceAvailable %@", aStream); + [self _pumpWriting]; + break; + } + + default: + SRFastLog(@"(default) %@", aStream); + break; + } +} + +@end + + +@implementation SRIOConsumer + +@synthesize bytesNeeded = _bytesNeeded; +@synthesize consumer = _scanner; +@synthesize handler = _handler; +@synthesize readToCurrentFrame = _readToCurrentFrame; +@synthesize unmaskBytes = _unmaskBytes; + +- (void)setupWithScanner:(stream_scanner)scanner handler:(data_callback)handler bytesNeeded:(size_t)bytesNeeded readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes; +{ + _scanner = [scanner copy]; + _handler = [handler copy]; + _bytesNeeded = bytesNeeded; + _readToCurrentFrame = readToCurrentFrame; + _unmaskBytes = unmaskBytes; + assert(_scanner || _bytesNeeded); +} + + +@end + + +@implementation SRIOConsumerPool { + NSUInteger _poolSize; + NSMutableArray *_bufferedConsumers; +} + +- (id)initWithBufferCapacity:(NSUInteger)poolSize; +{ + self = [super init]; + if (self) { + _poolSize = poolSize; + _bufferedConsumers = [[NSMutableArray alloc] initWithCapacity:poolSize]; + } + return self; +} + +- (id)init +{ + return [self initWithBufferCapacity:8]; +} + +- (SRIOConsumer *)consumerWithScanner:(stream_scanner)scanner handler:(data_callback)handler bytesNeeded:(size_t)bytesNeeded readToCurrentFrame:(BOOL)readToCurrentFrame unmaskBytes:(BOOL)unmaskBytes; +{ + SRIOConsumer *consumer = nil; + if (_bufferedConsumers.count) { + consumer = [_bufferedConsumers lastObject]; + [_bufferedConsumers removeLastObject]; + } else { + consumer = [[SRIOConsumer alloc] init]; + } + + [consumer setupWithScanner:scanner handler:handler bytesNeeded:bytesNeeded readToCurrentFrame:readToCurrentFrame unmaskBytes:unmaskBytes]; + + return consumer; +} + +- (void)returnConsumer:(SRIOConsumer *)consumer; +{ + if (_bufferedConsumers.count < _poolSize) { + [_bufferedConsumers addObject:consumer]; + } +} + +@end + + +@implementation NSURLRequest (SRCertificateAdditions) + +- (NSArray *)SR_SSLPinnedCertificates; +{ + return [NSURLProtocol propertyForKey:@"SR_SSLPinnedCertificates" inRequest:self]; +} + +@end + +@implementation NSMutableURLRequest (SRCertificateAdditions) + +- (NSArray *)SR_SSLPinnedCertificates; +{ + return [NSURLProtocol propertyForKey:@"SR_SSLPinnedCertificates" inRequest:self]; +} + +- (void)setSR_SSLPinnedCertificates:(NSArray *)SR_SSLPinnedCertificates; +{ + [NSURLProtocol setProperty:SR_SSLPinnedCertificates forKey:@"SR_SSLPinnedCertificates" inRequest:self]; +} + +@end + +@implementation NSURL (SRWebSocket) + +- (NSString *)SR_origin; +{ + NSString *scheme = [self.scheme lowercaseString]; + + if ([scheme isEqualToString:@"wss"]) { + scheme = @"https"; + } else if ([scheme isEqualToString:@"ws"]) { + scheme = @"http"; + } + + BOOL portIsDefault = !self.port || + ([scheme isEqualToString:@"http"] && self.port.integerValue == 80) || + ([scheme isEqualToString:@"https"] && self.port.integerValue == 443); + + if (!portIsDefault) { + return [NSString stringWithFormat:@"%@://%@:%@", scheme, self.host, self.port]; + } else { + return [NSString stringWithFormat:@"%@://%@", scheme, self.host]; + } +} + +@end + +//#define SR_ENABLE_LOG + +static inline void SRFastLog(NSString *format, ...) { +#ifdef SR_ENABLE_LOG + __block va_list arg_list; + va_start (arg_list, format); + + NSString *formattedString = [[NSString alloc] initWithFormat:format arguments:arg_list]; + + va_end(arg_list); + + NSLog(@"[SR] %@", formattedString); +#endif +} + + +#ifdef HAS_ICU + +static inline int32_t validate_dispatch_data_partial_string(NSData *data) { + if ([data length] > INT32_MAX) { + // INT32_MAX is the limit so long as this Framework is using 32 bit ints everywhere. + return -1; + } + + int32_t size = (int32_t)[data length]; + + const void * contents = [data bytes]; + const uint8_t *str = (const uint8_t *)contents; + + UChar32 codepoint = 1; + int32_t offset = 0; + int32_t lastOffset = 0; + while(offset < size && codepoint > 0) { + lastOffset = offset; + U8_NEXT(str, offset, size, codepoint); + } + + if (codepoint == -1) { + // Check to see if the last byte is valid or whether it was just continuing + if (!U8_IS_LEAD(str[lastOffset]) || U8_COUNT_TRAIL_BYTES(str[lastOffset]) + lastOffset < (int32_t)size) { + + size = -1; + } else { + uint8_t leadByte = str[lastOffset]; + U8_MASK_LEAD_BYTE(leadByte, U8_COUNT_TRAIL_BYTES(leadByte)); + + for (int i = lastOffset + 1; i < offset; i++) { + if (U8_IS_SINGLE(str[i]) || U8_IS_LEAD(str[i]) || !U8_IS_TRAIL(str[i])) { + size = -1; + } + } + + if (size != -1) { + size = lastOffset; + } + } + } + + if (size != -1 && ![[NSString alloc] initWithBytesNoCopy:(char *)[data bytes] length:size encoding:NSUTF8StringEncoding freeWhenDone:NO]) { + size = -1; + } + + return size; +} + +#else + +// This is a hack, and probably not optimal +static inline int32_t validate_dispatch_data_partial_string(NSData *data) { + static const int maxCodepointSize = 3; + + for (int i = 0; i < maxCodepointSize; i++) { + NSString *str = [[NSString alloc] initWithBytesNoCopy:(char *)data.bytes length:data.length - i encoding:NSUTF8StringEncoding freeWhenDone:NO]; + if (str) { + return (int32_t)data.length - i; + } + } + + return -1; +} + +#endif + +static _SRRunLoopThread *networkThread = nil; +static NSRunLoop *networkRunLoop = nil; + +@implementation NSRunLoop (SRWebSocket) + ++ (NSRunLoop *)SR_networkRunLoop { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + networkThread = [[_SRRunLoopThread alloc] init]; + networkThread.name = @"com.squareup.SocketRocket.NetworkThread"; + [networkThread start]; + networkRunLoop = networkThread.runLoop; + }); + + return networkRunLoop; +} + +@end + + +@implementation _SRRunLoopThread { + dispatch_group_t _waitGroup; +} + +@synthesize runLoop = _runLoop; + +- (void)dealloc +{ + sr_dispatch_release(_waitGroup); +} + +- (id)init +{ + self = [super init]; + if (self) { + _waitGroup = dispatch_group_create(); + dispatch_group_enter(_waitGroup); + } + return self; +} + +- (void)main; +{ + @autoreleasepool { + _runLoop = [NSRunLoop currentRunLoop]; + dispatch_group_leave(_waitGroup); + + // Add an empty run loop source to prevent runloop from spinning. + CFRunLoopSourceContext sourceCtx = { + .version = 0, + .info = NULL, + .retain = NULL, + .release = NULL, + .copyDescription = NULL, + .equal = NULL, + .hash = NULL, + .schedule = NULL, + .cancel = NULL, + .perform = NULL + }; + CFRunLoopSourceRef source = CFRunLoopSourceCreate(NULL, 0, &sourceCtx); + CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode); + CFRelease(source); + + while ([_runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) { + + } + assert(NO); + } +} + +- (NSRunLoop *)runLoop; +{ + dispatch_group_wait(_waitGroup, DISPATCH_TIME_FOREVER); + return _runLoop; +} + +@end diff --git a/Pods/SocketRocket/SocketRocket/SocketRocket.h b/Pods/SocketRocket/SocketRocket/SocketRocket.h new file mode 100644 index 0000000..2e986ae --- /dev/null +++ b/Pods/SocketRocket/SocketRocket/SocketRocket.h @@ -0,0 +1,17 @@ +// +// Copyright 2012 Square Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#import diff --git a/Pods/TTTAttributedLabel/LICENSE b/Pods/TTTAttributedLabel/LICENSE new file mode 100644 index 0000000..11028ca --- /dev/null +++ b/Pods/TTTAttributedLabel/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011 Mattt Thompson (http://mattt.me/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Pods/TTTAttributedLabel/README.md b/Pods/TTTAttributedLabel/README.md new file mode 100644 index 0000000..cbc81b4 --- /dev/null +++ b/Pods/TTTAttributedLabel/README.md @@ -0,0 +1,159 @@ +# TTTAttributedLabel + +[![Circle CI](https://circleci.com/gh/TTTAttributedLabel/TTTAttributedLabel.svg?style=svg)](https://circleci.com/gh/TTTAttributedLabel/TTTAttributedLabel) [![Documentation](https://img.shields.io/cocoapods/v/TTTAttributedLabel.svg?style=flat)](http://cocoadocs.org/docsets/TTTAttributedLabel/) [![codecov.io](https://codecov.io/github/TTTAttributedLabel/TTTAttributedLabel/coverage.svg?branch=master)](http://codecov.io/github/TTTAttributedLabel/TTTAttributedLabel?branch=master) [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) + +**A drop-in replacement for `UILabel` that supports attributes, data detectors, links, and more** + +`TTTAttributedLabel` is a drop-in replacement for `UILabel` providing a simple way to performantly render [attributed strings](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/Reference/Reference.html). As a bonus, it also supports link embedding, both automatically with `NSTextCheckingTypes` and manually by specifying a range for a URL, address, phone number, event, or transit information. + +> Already using this library? Please comment on [this issue](https://github.com/TTTAttributedLabel/TTTAttributedLabel/issues/586) to let us know which versions of iOS your app supports. + +Even though `UILabel` received support for `NSAttributedString` in iOS 6, `TTTAttributedLabel` has several unique features: + +- Compatibility with iOS >= 4.3 +- Automatic data detection +- Manual link embedding +- Label style inheritance for attributed strings +- Custom styling for links within the label +- Long-press gestures in addition to tap gestures for links + +It also includes advanced paragraph style properties: + +- `attributedTruncationToken` +- `firstLineIndent` +- `highlightedShadowRadius` +- `highlightedShadowOffset` +- `highlightedShadowColor` +- `lineHeightMultiple` +- `lineSpacing` +- `minimumLineHeight` +- `maximumLineHeight` +- `shadowRadius` +- `textInsets` +- `verticalAlignment` + +### Accessibility + +As of version 1.10.0, `TTTAttributedLabel` supports VoiceOver through the `UIAccessibilityElement` protocol. Each link can be individually selected, with an `accessibilityLabel` equal to its string value, and a corresponding `accessibilityValue` for URL, phone number, and date links. Developers who wish to change this behavior or provide custom values should create a subclass and override `accessibilityElements`. + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/tttattributedlabel). (Tag `tttattributedlabel`) +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/tttattributedlabel). +- If you **found a bug**, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + +## Installation + +[CocoaPods](https://cocoapods.org/) is the recommended method of installing `TTTAttributedLabel`. Simply add the following line to your `Podfile`: + +```ruby +# Podfile + +pod 'TTTAttributedLabel' +``` + +## Usage + +`TTTAttributedLabel` can display both plain and attributed text: just pass an `NSString` or `NSAttributedString` to the `setText:` setter. Never assign to the `attributedText` property. + +```objc +// NSAttributedString + +TTTAttributedLabel *attributedLabel = [[TTTAttributedLabel alloc] initWithFrame:CGRectZero]; + +NSAttributedString *attString = [[NSAttributedString alloc] initWithString:@"Tom Bombadil" + attributes:@{ + (id)kCTForegroundColorAttributeName : (id)[UIColor redColor].CGColor, + NSFontAttributeName : [UIFont boldSystemFontOfSize:16], + NSKernAttributeName : [NSNull null], + (id)kTTTBackgroundFillColorAttributeName : (id)[UIColor greenColor].CGColor +}]; + +// The attributed string is directly set, without inheriting any other text +// properties of the label. +attributedLabel.text = attString; +``` + +```objc +// NSString + +TTTAttributedLabel *label = [[TTTAttributedLabel alloc] initWithFrame:CGRectZero]; +label.font = [UIFont systemFontOfSize:14]; +label.textColor = [UIColor darkGrayColor]; +label.lineBreakMode = NSLineBreakByWordWrapping; +label.numberOfLines = 0; + +// If you're using a simple `NSString` for your text, +// assign to the `text` property last so it can inherit other label properties. +NSString *text = @"Lorem ipsum dolor sit amet"; +[label setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) { + NSRange boldRange = [[mutableAttributedString string] rangeOfString:@"ipsum dolor" options:NSCaseInsensitiveSearch]; + NSRange strikeRange = [[mutableAttributedString string] rangeOfString:@"sit amet" options:NSCaseInsensitiveSearch]; + + // Core Text APIs use C functions without a direct bridge to UIFont. See Apple's "Core Text Programming Guide" to learn how to configure string attributes. + UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:14]; + CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL); + if (font) { + [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font range:boldRange]; + [mutableAttributedString addAttribute:kTTTStrikeOutAttributeName value:@YES range:strikeRange]; + CFRelease(font); + } + + return mutableAttributedString; +}]; +``` + +First, we create and configure the label, the same way you would instantiate `UILabel`. Any text properties that are set on the label are inherited as the base attributes when using the `-setText:afterInheritingLabelAttributesAndConfiguringWithBlock:` method. In this example, the substring "ipsum dolar", would appear in bold, such that the label would read "Lorem **ipsum dolar** sit amet", in size 14 Helvetica, with a dark gray color. + +## `IBDesignable` + +`TTTAttributedLabel` includes `IBInspectable` and `IB_DESIGNABLE` annotations to enable configuring the label inside Interface Builder. However, if you see these warnings when building... + +``` +IB Designables: Failed to update auto layout status: Failed to load designables from path (null) +IB Designables: Failed to render instance of TTTAttributedLabel: Failed to load designables from path (null) +``` + +...then you are likely using `TTTAttributedLabel` as a static library, which does not support IB annotations. Some workarounds include: + +- Install `TTTAttributedLabel` as a dynamic framework using CocoaPods with `use_frameworks!` in your `Podfile`, or with Carthage +- Install `TTTAttributedLabel` by dragging its source files to your project + +### Links and Data Detection + +In addition to supporting rich text, `TTTAttributedLabel` can automatically detect links for dates, addresses, URLs, phone numbers, transit information, and allows you to embed your own links. + +``` objective-c +label.enabledTextCheckingTypes = NSTextCheckingTypeLink; // Automatically detect links when the label text is subsequently changed +label.delegate = self; // Delegate methods are called when the user taps on a link (see `TTTAttributedLabelDelegate` protocol) + +label.text = @"Fork me on GitHub! (https://github.com/mattt/TTTAttributedLabel/)"; // Repository URL will be automatically detected and linked + +NSRange range = [label.text rangeOfString:@"me"]; +[label addLinkToURL:[NSURL URLWithString:@"http://github.com/mattt/"] withRange:range]; // Embedding a custom link in a substring +``` + +## Demo + +```bash +pod try TTTAttributedLabel +``` + +...or clone this repo and build and run/test the `Espressos` project in Xcode to see `TTTAttributedLabel` in action. If you don't have [CocoaPods](http://cocoapods.org) installed, grab it with `[sudo] gem install cocoapods`. + +```bash +cd Example +pod install +open Espressos.xcworkspace +``` + +## Requirements + +- iOS 8+ / tvOS 9+ +- Xcode 6+ + +## License + +`TTTAttributedLabel` is available under the MIT license. See the LICENSE file for more info. diff --git a/Pods/TTTAttributedLabel/TTTAttributedLabel/TTTAttributedLabel.h b/Pods/TTTAttributedLabel/TTTAttributedLabel/TTTAttributedLabel.h new file mode 100644 index 0000000..80ad4d6 --- /dev/null +++ b/Pods/TTTAttributedLabel/TTTAttributedLabel/TTTAttributedLabel.h @@ -0,0 +1,681 @@ +// TTTAttributedLabel.h +// +// Copyright (c) 2011 Mattt Thompson (http://mattt.me) +// +// 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 +#import + +//! Project version number for TTTAttributedLabel. +FOUNDATION_EXPORT double TTTAttributedLabelVersionNumber; + +//! Project version string for TTTAttributedLabel. +FOUNDATION_EXPORT const unsigned char TTTAttributedLabelVersionString[]; + +@class TTTAttributedLabelLink; + +/** + Vertical alignment for text in a label whose bounds are larger than its text bounds + */ +typedef NS_ENUM(NSInteger, TTTAttributedLabelVerticalAlignment) { + TTTAttributedLabelVerticalAlignmentCenter = 0, + TTTAttributedLabelVerticalAlignmentTop = 1, + TTTAttributedLabelVerticalAlignmentBottom = 2, +}; + +/** + Determines whether the text to which this attribute applies has a strikeout drawn through itself. + */ +extern NSString * const kTTTStrikeOutAttributeName; + +/** + The background fill color. Value must be a `CGColorRef`. Default value is `nil` (no fill). + */ +extern NSString * const kTTTBackgroundFillColorAttributeName; + +/** + The padding for the background fill. Value must be a `UIEdgeInsets`. Default value is `UIEdgeInsetsZero` (no padding). + */ +extern NSString * const kTTTBackgroundFillPaddingAttributeName; + +/** + The background stroke color. Value must be a `CGColorRef`. Default value is `nil` (no stroke). + */ +extern NSString * const kTTTBackgroundStrokeColorAttributeName; + +/** + The background stroke line width. Value must be an `NSNumber`. Default value is `1.0f`. + */ +extern NSString * const kTTTBackgroundLineWidthAttributeName; + +/** + The background corner radius. Value must be an `NSNumber`. Default value is `5.0f`. + */ +extern NSString * const kTTTBackgroundCornerRadiusAttributeName; + +@protocol TTTAttributedLabelDelegate; + +// Override UILabel @property to accept both NSString and NSAttributedString +@protocol TTTAttributedLabel +@property (nonatomic, copy) IBInspectable id text; +@end + +IB_DESIGNABLE + +/** + `TTTAttributedLabel` is a drop-in replacement for `UILabel` that supports `NSAttributedString`, as well as automatically-detected and manually-added links to URLs, addresses, phone numbers, and dates. + + ## Differences Between `TTTAttributedLabel` and `UILabel` + + For the most part, `TTTAttributedLabel` behaves just like `UILabel`. The following are notable exceptions, in which `TTTAttributedLabel` may act differently: + + - `text` - This property now takes an `id` type argument, which can either be a kind of `NSString` or `NSAttributedString` (mutable or immutable in both cases) + - `attributedText` - Do not set this property directly. Instead, pass an `NSAttributedString` to `text`. + - `lineBreakMode` - This property displays only the first line when the value is `UILineBreakModeHeadTruncation`, `UILineBreakModeTailTruncation`, or `UILineBreakModeMiddleTruncation` + - `adjustsFontsizeToFitWidth` - Supported in iOS 5 and greater, this property is effective for any value of `numberOfLines` greater than zero. In iOS 4, setting `numberOfLines` to a value greater than 1 with `adjustsFontSizeToFitWidth` set to `YES` may cause `sizeToFit` to execute indefinitely. + - `baselineAdjustment` - This property has no affect. + - `textAlignment` - This property does not support justified alignment. + - `NSTextAttachment` - This string attribute is not supported. + + Any properties affecting text or paragraph styling, such as `firstLineIndent` will only apply when text is set with an `NSString`. If the text is set with an `NSAttributedString`, these properties will not apply. + + ### NSCoding + + `TTTAttributedLabel`, like `UILabel`, conforms to `NSCoding`. However, if the build target is set to less than iOS 6.0, `linkAttributes` and `activeLinkAttributes` will not be encoded or decoded. This is due to an runtime exception thrown when attempting to copy non-object CoreText values in dictionaries. + + @warning Any properties changed on the label after setting the text will not be reflected until a subsequent call to `setText:` or `setText:afterInheritingLabelAttributesAndConfiguringWithBlock:`. This is to say, order of operations matters in this case. For example, if the label text color is originally black when the text is set, changing the text color to red will have no effect on the display of the label until the text is set once again. + + @bug Setting `attributedText` directly is not recommended, as it may cause a crash when attempting to access any links previously set. Instead, call `setText:`, passing an `NSAttributedString`. + */ +@interface TTTAttributedLabel : UILabel + +/** + * The designated initializers are @c initWithFrame: and @c initWithCoder:. + * init will not properly initialize many required properties and other configuration. + */ +- (instancetype) init NS_UNAVAILABLE; + +///----------------------------- +/// @name Accessing the Delegate +///----------------------------- + +/** + The receiver's delegate. + + @discussion A `TTTAttributedLabel` delegate responds to messages sent by tapping on links in the label. You can use the delegate to respond to links referencing a URL, address, phone number, date, or date with a specified time zone and duration. + */ +@property (nonatomic, unsafe_unretained) IBOutlet id delegate; + +///-------------------------------------------- +/// @name Detecting, Accessing, & Styling Links +///-------------------------------------------- + +/** + A bitmask of `NSTextCheckingType` which are used to automatically detect links in the label text. + + @warning You must specify `enabledTextCheckingTypes` before setting the `text`, with either `setText:` or `setText:afterInheritingLabelAttributesAndConfiguringWithBlock:`. + */ +@property (nonatomic, assign) NSTextCheckingTypes enabledTextCheckingTypes; + +/** + An array of `NSTextCheckingResult` objects for links detected or manually added to the label text. + */ +@property (readonly, nonatomic, strong) NSArray *links; + +/** + A dictionary containing the default `NSAttributedString` attributes to be applied to links detected or manually added to the label text. The default link style is blue and underlined. + + @warning You must specify `linkAttributes` before setting autodecting or manually-adding links for these attributes to be applied. + */ +@property (nonatomic, strong) NSDictionary *linkAttributes; + +/** + A dictionary containing the default `NSAttributedString` attributes to be applied to links when they are in the active state. If `nil` or an empty `NSDictionary`, active links will not be styled. The default active link style is red and underlined. + */ +@property (nonatomic, strong) NSDictionary *activeLinkAttributes; + +/** + A dictionary containing the default `NSAttributedString` attributes to be applied to links when they are in the inactive state, which is triggered by a change in `tintColor` in iOS 7 and later. If `nil` or an empty `NSDictionary`, inactive links will not be styled. The default inactive link style is gray and unadorned. + */ +@property (nonatomic, strong) NSDictionary *inactiveLinkAttributes; + +/** + The edge inset for the background of a link. The default value is `{0, -1, 0, -1}`. + */ +@property (nonatomic, assign) UIEdgeInsets linkBackgroundEdgeInset; + +/** + Indicates if links will be detected within an extended area around the touch + to emulate the link detection behaviour of UIWebView. + Default value is NO. Enabling this may adversely impact performance. + */ +@property (nonatomic, assign) BOOL extendsLinkTouchArea; + +///--------------------------------------- +/// @name Acccessing Text Style Attributes +///--------------------------------------- + +/** + The shadow blur radius for the label. A value of 0 indicates no blur, while larger values produce correspondingly larger blurring. This value must not be negative. The default value is 0. + */ +@property (nonatomic, assign) IBInspectable CGFloat shadowRadius; + +/** + The shadow blur radius for the label when the label's `highlighted` property is `YES`. A value of 0 indicates no blur, while larger values produce correspondingly larger blurring. This value must not be negative. The default value is 0. + */ +@property (nonatomic, assign) IBInspectable CGFloat highlightedShadowRadius; +/** + The shadow offset for the label when the label's `highlighted` property is `YES`. A size of {0, 0} indicates no offset, with positive values extending down and to the right. The default size is {0, 0}. + */ +@property (nonatomic, assign) IBInspectable CGSize highlightedShadowOffset; +/** + The shadow color for the label when the label's `highlighted` property is `YES`. The default value is `nil` (no shadow color). + */ +@property (nonatomic, strong) IBInspectable UIColor *highlightedShadowColor; + +/** + The amount to kern the next character. Default is standard kerning. If this attribute is set to 0.0, no kerning is done at all. + */ +@property (nonatomic, assign) IBInspectable CGFloat kern; + +///-------------------------------------------- +/// @name Acccessing Paragraph Style Attributes +///-------------------------------------------- + +/** + The distance, in points, from the leading margin of a frame to the beginning of the + paragraph's first line. This value is always nonnegative, and is 0.0 by default. + This applies to the full text, rather than any specific paragraph metrics. + */ +@property (nonatomic, assign) IBInspectable CGFloat firstLineIndent; + +/** + The space in points added between lines within the paragraph. This value is always nonnegative and is 0.0 by default. + */ +@property (nonatomic, assign) IBInspectable CGFloat lineSpacing; + +/** + The minimum line height within the paragraph. If the value is 0.0, the minimum line height is set to the line height of the `font`. 0.0 by default. + */ +@property (nonatomic, assign) IBInspectable CGFloat minimumLineHeight; + +/** + The maximum line height within the paragraph. If the value is 0.0, the maximum line height is set to the line height of the `font`. 0.0 by default. + */ +@property (nonatomic, assign) IBInspectable CGFloat maximumLineHeight; + +/** + The line height multiple. This value is 1.0 by default. + */ +@property (nonatomic, assign) IBInspectable CGFloat lineHeightMultiple; + +/** + The distance, in points, from the margin to the text container. This value is `UIEdgeInsetsZero` by default. + sizeThatFits: will have its returned size increased by these margins. + drawTextInRect: will inset all drawn text by these margins. + */ +@property (nonatomic, assign) IBInspectable UIEdgeInsets textInsets; + +/** + The vertical text alignment for the label, for when the frame size is greater than the text rect size. The vertical alignment is `TTTAttributedLabelVerticalAlignmentCenter` by default. + */ +@property (nonatomic, assign) TTTAttributedLabelVerticalAlignment verticalAlignment; + +///-------------------------------------------- +/// @name Accessing Truncation Token Appearance +///-------------------------------------------- + +/** + The attributed string to apply to the truncation token at the end of a truncated line. Overrides `truncationTokenStringAttributes` and `truncationTokenString`. If unspecified, attributes will fallback to `truncationTokenStringAttributes` and `truncationTokenString`. + */ +@property (nonatomic, strong) IBInspectable NSAttributedString *attributedTruncationToken; + +///-------------------------- +/// @name Long press gestures +///-------------------------- + +/** + * The long-press gesture recognizer used internally by the label. + */ +@property (nonatomic, strong, readonly) UILongPressGestureRecognizer *longPressGestureRecognizer; + +///-------------------------------------------- +/// @name Calculating Size of Attributed String +///-------------------------------------------- + +/** + Calculate and return the size that best fits an attributed string, given the specified constraints on size and number of lines. + + @param attributedString The attributed string. + @param size The maximum dimensions used to calculate size. + @param numberOfLines The maximum number of lines in the text to draw, if the constraining size cannot accomodate the full attributed string. + + @return The size that fits the attributed string within the specified constraints. + */ ++ (CGSize)sizeThatFitsAttributedString:(NSAttributedString *)attributedString + withConstraints:(CGSize)size + limitedToNumberOfLines:(NSUInteger)numberOfLines; + +///---------------------------------- +/// @name Setting the Text Attributes +///---------------------------------- + +/** + Sets the text displayed by the label. + + @param text An `NSString` or `NSAttributedString` object to be displayed by the label. If the specified text is an `NSString`, the label will display the text like a `UILabel`, inheriting the text styles of the label. If the specified text is an `NSAttributedString`, the label text styles will be overridden by the styles specified in the attributed string. + + @discussion This method overrides `UILabel -setText:` to accept both `NSString` and `NSAttributedString` objects. This string is `nil` by default. + */ +- (void)setText:(id)text; + +/** + Sets the text displayed by the label, after configuring an attributed string containing the text attributes inherited from the label in a block. + + @param text An `NSString` or `NSAttributedString` object to be displayed by the label. + @param block A block object that returns an `NSMutableAttributedString` object and takes a single argument, which is an `NSMutableAttributedString` object with the text from the first parameter, and the text attributes inherited from the label text styles. For example, if you specified the `font` of the label to be `[UIFont boldSystemFontOfSize:14]` and `textColor` to be `[UIColor redColor]`, the `NSAttributedString` argument of the block would be contain the `NSAttributedString` attribute equivalents of those properties. In this block, you can set further attributes on particular ranges. + + @discussion This string is `nil` by default. + */ +- (void)setText:(id)text +afterInheritingLabelAttributesAndConfiguringWithBlock:(NSMutableAttributedString *(^)(NSMutableAttributedString *mutableAttributedString))block; + +///------------------------------------ +/// @name Accessing the Text Attributes +///------------------------------------ + +/** + A copy of the label's current attributedText. This returns `nil` if an attributed string has never been set on the label. + + @warning Do not set this property directly. Instead, set @c text to an @c NSAttributedString. + */ +@property (readwrite, nonatomic, copy) NSAttributedString *attributedText; + +///------------------- +/// @name Adding Links +///------------------- + +/** + Adds a link. You can customize an individual link's appearance and accessibility value by creating your own @c TTTAttributedLabelLink and passing it to this method. The other methods for adding links will use the label's default attributes. + + @warning Modifying the link's attribute dictionaries must be done before calling this method. + + @param link A @c TTTAttributedLabelLink object. + */ +- (void)addLink:(TTTAttributedLabelLink *)link; + +/** + Adds a link to an @c NSTextCheckingResult. + + @param result An @c NSTextCheckingResult representing the link's location and type. + + @return The newly added link object. + */ +- (TTTAttributedLabelLink *)addLinkWithTextCheckingResult:(NSTextCheckingResult *)result; + +/** + Adds a link to an @c NSTextCheckingResult. + + @param result An @c NSTextCheckingResult representing the link's location and type. + @param attributes The attributes to be added to the text in the range of the specified link. If set, the label's @c activeAttributes and @c inactiveAttributes will be applied to the link. If `nil`, no attributes are added to the link. + + @return The newly added link object. + */ +- (TTTAttributedLabelLink *)addLinkWithTextCheckingResult:(NSTextCheckingResult *)result + attributes:(NSDictionary *)attributes; + +/** + Adds a link to a URL for a specified range in the label text. + + @param url The url to be linked to + @param range The range in the label text of the link. The range must not exceed the bounds of the receiver. + + @return The newly added link object. + */ +- (TTTAttributedLabelLink *)addLinkToURL:(NSURL *)url + withRange:(NSRange)range; + +/** + Adds a link to an address for a specified range in the label text. + + @param addressComponents A dictionary of address components for the address to be linked to + @param range The range in the label text of the link. The range must not exceed the bounds of the receiver. + + @discussion The address component dictionary keys are described in `NSTextCheckingResult`'s "Keys for Address Components." + + @return The newly added link object. + */ +- (TTTAttributedLabelLink *)addLinkToAddress:(NSDictionary *)addressComponents + withRange:(NSRange)range; + +/** + Adds a link to a phone number for a specified range in the label text. + + @param phoneNumber The phone number to be linked to. + @param range The range in the label text of the link. The range must not exceed the bounds of the receiver. + + @return The newly added link object. + */ +- (TTTAttributedLabelLink *)addLinkToPhoneNumber:(NSString *)phoneNumber + withRange:(NSRange)range; + +/** + Adds a link to a date for a specified range in the label text. + + @param date The date to be linked to. + @param range The range in the label text of the link. The range must not exceed the bounds of the receiver. + + @return The newly added link object. + */ +- (TTTAttributedLabelLink *)addLinkToDate:(NSDate *)date + withRange:(NSRange)range; + +/** + Adds a link to a date with a particular time zone and duration for a specified range in the label text. + + @param date The date to be linked to. + @param timeZone The time zone of the specified date. + @param duration The duration, in seconds from the specified date. + @param range The range in the label text of the link. The range must not exceed the bounds of the receiver. + + @return The newly added link object. + */ +- (TTTAttributedLabelLink *)addLinkToDate:(NSDate *)date + timeZone:(NSTimeZone *)timeZone + duration:(NSTimeInterval)duration + withRange:(NSRange)range; + +/** + Adds a link to transit information for a specified range in the label text. + + @param components A dictionary containing the transit components. The currently supported keys are `NSTextCheckingAirlineKey` and `NSTextCheckingFlightKey`. + @param range The range in the label text of the link. The range must not exceed the bounds of the receiver. + + @return The newly added link object. + */ +- (TTTAttributedLabelLink *)addLinkToTransitInformation:(NSDictionary *)components + withRange:(NSRange)range; + +/** + Returns whether an @c NSTextCheckingResult is found at the give point. + + @discussion This can be used together with @c UITapGestureRecognizer to tap interactions with overlapping views. + + @param point The point inside the label. + */ +- (BOOL)containslinkAtPoint:(CGPoint)point; + +/** + Returns the @c TTTAttributedLabelLink at the give point if it exists. + + @discussion This can be used together with @c UIViewControllerPreviewingDelegate to peek into links. + + @param point The point inside the label. + */ +- (TTTAttributedLabelLink *)linkAtPoint:(CGPoint)point; + +@end + +/** + The `TTTAttributedLabelDelegate` protocol defines the messages sent to an attributed label delegate when links are tapped. All of the methods of this protocol are optional. + */ +@protocol TTTAttributedLabelDelegate + +///----------------------------------- +/// @name Responding to Link Selection +///----------------------------------- +@optional + +/** + Tells the delegate that the user did select a link to a URL. + + @param label The label whose link was selected. + @param url The URL for the selected link. + */ +- (void)attributedLabel:(TTTAttributedLabel *)label + didSelectLinkWithURL:(NSURL *)url; + +/** + Tells the delegate that the user did select a link to an address. + + @param label The label whose link was selected. + @param addressComponents The components of the address for the selected link. + */ +- (void)attributedLabel:(TTTAttributedLabel *)label +didSelectLinkWithAddress:(NSDictionary *)addressComponents; + +/** + Tells the delegate that the user did select a link to a phone number. + + @param label The label whose link was selected. + @param phoneNumber The phone number for the selected link. + */ +- (void)attributedLabel:(TTTAttributedLabel *)label +didSelectLinkWithPhoneNumber:(NSString *)phoneNumber; + +/** + Tells the delegate that the user did select a link to a date. + + @param label The label whose link was selected. + @param date The datefor the selected link. + */ +- (void)attributedLabel:(TTTAttributedLabel *)label + didSelectLinkWithDate:(NSDate *)date; + +/** + Tells the delegate that the user did select a link to a date with a time zone and duration. + + @param label The label whose link was selected. + @param date The date for the selected link. + @param timeZone The time zone of the date for the selected link. + @param duration The duration, in seconds from the date for the selected link. + */ +- (void)attributedLabel:(TTTAttributedLabel *)label + didSelectLinkWithDate:(NSDate *)date + timeZone:(NSTimeZone *)timeZone + duration:(NSTimeInterval)duration; + +/** + Tells the delegate that the user did select a link to transit information + + @param label The label whose link was selected. + @param components A dictionary containing the transit components. The currently supported keys are `NSTextCheckingAirlineKey` and `NSTextCheckingFlightKey`. + */ +- (void)attributedLabel:(TTTAttributedLabel *)label +didSelectLinkWithTransitInformation:(NSDictionary *)components; + +/** + Tells the delegate that the user did select a link to a text checking result. + + @discussion This method is called if no other delegate method was called, which can occur by either now implementing the method in `TTTAttributedLabelDelegate` corresponding to a particular link, or the link was added by passing an instance of a custom `NSTextCheckingResult` subclass into `-addLinkWithTextCheckingResult:`. + + @param label The label whose link was selected. + @param result The custom text checking result. + */ +- (void)attributedLabel:(TTTAttributedLabel *)label +didSelectLinkWithTextCheckingResult:(NSTextCheckingResult *)result; + +///--------------------------------- +/// @name Responding to Long Presses +///--------------------------------- + +/** + * Long-press delegate methods include the CGPoint tapped within the label's coordinate space. + * This may be useful on iPad to present a popover from a specific origin point. + */ + +/** + Tells the delegate that the user long-pressed a link to a URL. + + @param label The label whose link was long pressed. + @param url The URL for the link. + @param point the point pressed, in the label's coordinate space + */ +- (void)attributedLabel:(TTTAttributedLabel *)label +didLongPressLinkWithURL:(NSURL *)url + atPoint:(CGPoint)point; + +/** + Tells the delegate that the user long-pressed a link to an address. + + @param label The label whose link was long pressed. + @param addressComponents The components of the address for the link. + @param point the point pressed, in the label's coordinate space + */ +- (void)attributedLabel:(TTTAttributedLabel *)label +didLongPressLinkWithAddress:(NSDictionary *)addressComponents + atPoint:(CGPoint)point; + +/** + Tells the delegate that the user long-pressed a link to a phone number. + + @param label The label whose link was long pressed. + @param phoneNumber The phone number for the link. + @param point the point pressed, in the label's coordinate space + */ +- (void)attributedLabel:(TTTAttributedLabel *)label +didLongPressLinkWithPhoneNumber:(NSString *)phoneNumber + atPoint:(CGPoint)point; + + +/** + Tells the delegate that the user long-pressed a link to a date. + + @param label The label whose link was long pressed. + @param date The date for the selected link. + @param point the point pressed, in the label's coordinate space + */ +- (void)attributedLabel:(TTTAttributedLabel *)label +didLongPressLinkWithDate:(NSDate *)date + atPoint:(CGPoint)point; + + +/** + Tells the delegate that the user long-pressed a link to a date with a time zone and duration. + + @param label The label whose link was long pressed. + @param date The date for the link. + @param timeZone The time zone of the date for the link. + @param duration The duration, in seconds from the date for the link. + @param point the point pressed, in the label's coordinate space + */ +- (void)attributedLabel:(TTTAttributedLabel *)label +didLongPressLinkWithDate:(NSDate *)date + timeZone:(NSTimeZone *)timeZone + duration:(NSTimeInterval)duration + atPoint:(CGPoint)point; + + +/** + Tells the delegate that the user long-pressed a link to transit information. + + @param label The label whose link was long pressed. + @param components A dictionary containing the transit components. The currently supported keys are `NSTextCheckingAirlineKey` and `NSTextCheckingFlightKey`. + @param point the point pressed, in the label's coordinate space + */ +- (void)attributedLabel:(TTTAttributedLabel *)label +didLongPressLinkWithTransitInformation:(NSDictionary *)components + atPoint:(CGPoint)point; + +/** + Tells the delegate that the user long-pressed a link to a text checking result. + + @discussion Similar to `-attributedLabel:didSelectLinkWithTextCheckingResult:`, this method is called if a link is long pressed and the delegate does not implement the method corresponding to this type of link. + + @param label The label whose link was long pressed. + @param result The custom text checking result. + @param point the point pressed, in the label's coordinate space + */ +- (void)attributedLabel:(TTTAttributedLabel *)label +didLongPressLinkWithTextCheckingResult:(NSTextCheckingResult *)result + atPoint:(CGPoint)point; + +@end + +@interface TTTAttributedLabelLink : NSObject + +typedef void (^TTTAttributedLabelLinkBlock) (TTTAttributedLabel *, TTTAttributedLabelLink *); + +/** + An `NSTextCheckingResult` representing the link's location and type. + */ +@property (readonly, nonatomic, strong) NSTextCheckingResult *result; + +/** + A dictionary containing the @c NSAttributedString attributes to be applied to the link. + */ +@property (readonly, nonatomic, copy) NSDictionary *attributes; + +/** + A dictionary containing the @c NSAttributedString attributes to be applied to the link when it is in the active state. + */ +@property (readonly, nonatomic, copy) NSDictionary *activeAttributes; + +/** + A dictionary containing the @c NSAttributedString attributes to be applied to the link when it is in the inactive state, which is triggered by a change in `tintColor` in iOS 7 and later. + */ +@property (readonly, nonatomic, copy) NSDictionary *inactiveAttributes; + +/** + Additional information about a link for VoiceOver users. Has default values if the link's @c result is @c NSTextCheckingTypeLink, @c NSTextCheckingTypePhoneNumber, or @c NSTextCheckingTypeDate. + */ +@property (nonatomic, copy) NSString *accessibilityValue; + +/** + A block called when this link is tapped. + If non-nil, tapping on this link will call this block instead of the + @c TTTAttributedLabelDelegate tap methods, which will not be called for this link. + */ +@property (nonatomic, copy) TTTAttributedLabelLinkBlock linkTapBlock; + +/** + A block called when this link is long-pressed. + If non-nil, long pressing on this link will call this block instead of the + @c TTTAttributedLabelDelegate long press methods, which will not be called for this link. + */ +@property (nonatomic, copy) TTTAttributedLabelLinkBlock linkLongPressBlock; + +/** + Initializes a link using the attribute dictionaries specified. + + @param attributes The @c attributes property for the link. + @param activeAttributes The @c activeAttributes property for the link. + @param inactiveAttributes The @c inactiveAttributes property for the link. + @param result An @c NSTextCheckingResult representing the link's location and type. + + @return The initialized link object. + */ +- (instancetype)initWithAttributes:(NSDictionary *)attributes + activeAttributes:(NSDictionary *)activeAttributes + inactiveAttributes:(NSDictionary *)inactiveAttributes + textCheckingResult:(NSTextCheckingResult *)result; + +/** + Initializes a link using the attribute dictionaries set on a specified label. + + @param label The attributed label from which to inherit attribute dictionaries. + @param result An @c NSTextCheckingResult representing the link's location and type. + + @return The initialized link object. + */ +- (instancetype)initWithAttributesFromLabel:(TTTAttributedLabel*)label + textCheckingResult:(NSTextCheckingResult *)result; + +@end diff --git a/Pods/TTTAttributedLabel/TTTAttributedLabel/TTTAttributedLabel.m b/Pods/TTTAttributedLabel/TTTAttributedLabel/TTTAttributedLabel.m new file mode 100644 index 0000000..48f6328 --- /dev/null +++ b/Pods/TTTAttributedLabel/TTTAttributedLabel/TTTAttributedLabel.m @@ -0,0 +1,1898 @@ +// TTTAttributedLabel.m +// +// Copyright (c) 2011 Mattt Thompson (http://mattt.me) +// +// 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 "TTTAttributedLabel.h" + +#import +#import +#import + +#define kTTTLineBreakWordWrapTextWidthScalingFactor (M_PI / M_E) + +static CGFloat const TTTFLOAT_MAX = 100000; + +NSString * const kTTTStrikeOutAttributeName = @"TTTStrikeOutAttribute"; +NSString * const kTTTBackgroundFillColorAttributeName = @"TTTBackgroundFillColor"; +NSString * const kTTTBackgroundFillPaddingAttributeName = @"TTTBackgroundFillPadding"; +NSString * const kTTTBackgroundStrokeColorAttributeName = @"TTTBackgroundStrokeColor"; +NSString * const kTTTBackgroundLineWidthAttributeName = @"TTTBackgroundLineWidth"; +NSString * const kTTTBackgroundCornerRadiusAttributeName = @"TTTBackgroundCornerRadius"; + +const NSTextAlignment TTTTextAlignmentLeft = NSTextAlignmentLeft; +const NSTextAlignment TTTTextAlignmentCenter = NSTextAlignmentCenter; +const NSTextAlignment TTTTextAlignmentRight = NSTextAlignmentRight; +const NSTextAlignment TTTTextAlignmentJustified = NSTextAlignmentJustified; +const NSTextAlignment TTTTextAlignmentNatural = NSTextAlignmentNatural; + +const NSLineBreakMode TTTLineBreakByWordWrapping = NSLineBreakByWordWrapping; +const NSLineBreakMode TTTLineBreakByCharWrapping = NSLineBreakByCharWrapping; +const NSLineBreakMode TTTLineBreakByClipping = NSLineBreakByClipping; +const NSLineBreakMode TTTLineBreakByTruncatingHead = NSLineBreakByTruncatingHead; +const NSLineBreakMode TTTLineBreakByTruncatingMiddle = NSLineBreakByTruncatingMiddle; +const NSLineBreakMode TTTLineBreakByTruncatingTail = NSLineBreakByTruncatingTail; + +typedef NSTextAlignment TTTTextAlignment; +typedef NSLineBreakMode TTTLineBreakMode; + + +static inline CTTextAlignment CTTextAlignmentFromTTTTextAlignment(TTTTextAlignment alignment) { + switch (alignment) { +#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000 + case NSTextAlignmentLeft: return kCTTextAlignmentLeft; + case NSTextAlignmentCenter: return kCTTextAlignmentCenter; + case NSTextAlignmentRight: return kCTTextAlignmentRight; + default: return kCTTextAlignmentNatural; +#else + case NSTextAlignmentLeft: return kCTLeftTextAlignment; + case NSTextAlignmentCenter: return kCTCenterTextAlignment; + case NSTextAlignmentRight: return kCTRightTextAlignment; + default: return kCTNaturalTextAlignment; +#endif + } +} + +static inline CTLineBreakMode CTLineBreakModeFromTTTLineBreakMode(TTTLineBreakMode lineBreakMode) { + switch (lineBreakMode) { + case NSLineBreakByWordWrapping: return kCTLineBreakByWordWrapping; + case NSLineBreakByCharWrapping: return kCTLineBreakByCharWrapping; + case NSLineBreakByClipping: return kCTLineBreakByClipping; + case NSLineBreakByTruncatingHead: return kCTLineBreakByTruncatingHead; + case NSLineBreakByTruncatingTail: return kCTLineBreakByTruncatingTail; + case NSLineBreakByTruncatingMiddle: return kCTLineBreakByTruncatingMiddle; + default: return 0; + } +} + +static inline CGFLOAT_TYPE CGFloat_ceil(CGFLOAT_TYPE cgfloat) { +#if CGFLOAT_IS_DOUBLE + return ceil(cgfloat); +#else + return ceilf(cgfloat); +#endif +} + +static inline CGFLOAT_TYPE CGFloat_floor(CGFLOAT_TYPE cgfloat) { +#if CGFLOAT_IS_DOUBLE + return floor(cgfloat); +#else + return floorf(cgfloat); +#endif +} + +static inline CGFLOAT_TYPE CGFloat_round(CGFLOAT_TYPE cgfloat) { +#if CGFLOAT_IS_DOUBLE + return round(cgfloat); +#else + return roundf(cgfloat); +#endif +} + +static inline CGFLOAT_TYPE CGFloat_sqrt(CGFLOAT_TYPE cgfloat) { +#if CGFLOAT_IS_DOUBLE + return sqrt(cgfloat); +#else + return sqrtf(cgfloat); +#endif +} + +static inline CGFloat TTTFlushFactorForTextAlignment(NSTextAlignment textAlignment) { + switch (textAlignment) { + case TTTTextAlignmentCenter: + return 0.5f; + case TTTTextAlignmentRight: + return 1.0f; + case TTTTextAlignmentLeft: + default: + return 0.0f; + } +} + +static inline NSDictionary * NSAttributedStringAttributesFromLabel(TTTAttributedLabel *label) { + NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionary]; + + if ([NSMutableParagraphStyle class]) { + [mutableAttributes setObject:label.font forKey:(NSString *)kCTFontAttributeName]; + [mutableAttributes setObject:label.textColor forKey:(NSString *)kCTForegroundColorAttributeName]; + [mutableAttributes setObject:@(label.kern) forKey:(NSString *)kCTKernAttributeName]; + + NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; + paragraphStyle.alignment = label.textAlignment; + paragraphStyle.lineSpacing = label.lineSpacing; + paragraphStyle.minimumLineHeight = label.minimumLineHeight > 0 ? label.minimumLineHeight : label.font.lineHeight * label.lineHeightMultiple; + paragraphStyle.maximumLineHeight = label.maximumLineHeight > 0 ? label.maximumLineHeight : label.font.lineHeight * label.lineHeightMultiple; + paragraphStyle.lineHeightMultiple = label.lineHeightMultiple; + paragraphStyle.firstLineHeadIndent = label.firstLineIndent; + + if (label.numberOfLines == 1) { + paragraphStyle.lineBreakMode = label.lineBreakMode; + } else { + paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping; + } + + [mutableAttributes setObject:paragraphStyle forKey:(NSString *)kCTParagraphStyleAttributeName]; + } else { + CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)label.font.fontName, label.font.pointSize, NULL); + [mutableAttributes setObject:(__bridge id)font forKey:(NSString *)kCTFontAttributeName]; + CFRelease(font); + + [mutableAttributes setObject:(id)[label.textColor CGColor] forKey:(NSString *)kCTForegroundColorAttributeName]; + [mutableAttributes setObject:@(label.kern) forKey:(NSString *)kCTKernAttributeName]; + + CTTextAlignment alignment = CTTextAlignmentFromTTTTextAlignment(label.textAlignment); + CGFloat lineSpacing = label.lineSpacing; + CGFloat minimumLineHeight = label.minimumLineHeight * label.lineHeightMultiple; + CGFloat maximumLineHeight = label.maximumLineHeight * label.lineHeightMultiple; + CGFloat lineSpacingAdjustment = CGFloat_ceil(label.font.lineHeight - label.font.ascender + label.font.descender); + CGFloat lineHeightMultiple = label.lineHeightMultiple; + CGFloat firstLineIndent = label.firstLineIndent; + + CTLineBreakMode lineBreakMode = kCTLineBreakByWordWrapping; + if (label.numberOfLines == 1) { + lineBreakMode = CTLineBreakModeFromTTTLineBreakMode(label.lineBreakMode); + } + + CTParagraphStyleSetting paragraphStyles[12] = { + {.spec = kCTParagraphStyleSpecifierAlignment, .valueSize = sizeof(CTTextAlignment), .value = (const void *)&alignment}, + {.spec = kCTParagraphStyleSpecifierLineBreakMode, .valueSize = sizeof(CTLineBreakMode), .value = (const void *)&lineBreakMode}, + {.spec = kCTParagraphStyleSpecifierLineSpacing, .valueSize = sizeof(CGFloat), .value = (const void *)&lineSpacing}, + {.spec = kCTParagraphStyleSpecifierMinimumLineSpacing, .valueSize = sizeof(CGFloat), .value = (const void *)&minimumLineHeight}, + {.spec = kCTParagraphStyleSpecifierMaximumLineSpacing, .valueSize = sizeof(CGFloat), .value = (const void *)&maximumLineHeight}, + {.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment, .valueSize = sizeof (CGFloat), .value = (const void *)&lineSpacingAdjustment}, + {.spec = kCTParagraphStyleSpecifierLineHeightMultiple, .valueSize = sizeof(CGFloat), .value = (const void *)&lineHeightMultiple}, + {.spec = kCTParagraphStyleSpecifierFirstLineHeadIndent, .valueSize = sizeof(CGFloat), .value = (const void *)&firstLineIndent}, + }; + + CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(paragraphStyles, 12); + + [mutableAttributes setObject:(__bridge id)paragraphStyle forKey:(NSString *)kCTParagraphStyleAttributeName]; + + CFRelease(paragraphStyle); + } + + return [NSDictionary dictionaryWithDictionary:mutableAttributes]; +} + +static inline CGColorRef CGColorRefFromColor(id color); +static inline NSDictionary * convertNSAttributedStringAttributesToCTAttributes(NSDictionary *attributes); + +static inline NSAttributedString * NSAttributedStringByScalingFontSize(NSAttributedString *attributedString, CGFloat scale) { + NSMutableAttributedString *mutableAttributedString = [attributedString mutableCopy]; + [mutableAttributedString enumerateAttribute:(NSString *)kCTFontAttributeName inRange:NSMakeRange(0, [mutableAttributedString length]) options:0 usingBlock:^(id value, NSRange range, BOOL * __unused stop) { + UIFont *font = (UIFont *)value; + if (font) { + NSString *fontName; + CGFloat pointSize; + + if ([font isKindOfClass:[UIFont class]]) { + fontName = font.fontName; + pointSize = font.pointSize; + } else { + fontName = (NSString *)CFBridgingRelease(CTFontCopyName((__bridge CTFontRef)font, kCTFontPostScriptNameKey)); + pointSize = CTFontGetSize((__bridge CTFontRef)font); + } + + [mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName range:range]; + CTFontRef fontRef = CTFontCreateWithName((__bridge CFStringRef)fontName, CGFloat_floor(pointSize * scale), NULL); + [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)fontRef range:range]; + CFRelease(fontRef); + } + }]; + + return mutableAttributedString; +} + +static inline NSAttributedString * NSAttributedStringBySettingColorFromContext(NSAttributedString *attributedString, UIColor *color) { + if (!color) { + return attributedString; + } + + NSMutableAttributedString *mutableAttributedString = [attributedString mutableCopy]; + [mutableAttributedString enumerateAttribute:(NSString *)kCTForegroundColorFromContextAttributeName inRange:NSMakeRange(0, [mutableAttributedString length]) options:0 usingBlock:^(id value, NSRange range, __unused BOOL *stop) { + BOOL usesColorFromContext = (BOOL)value; + if (usesColorFromContext) { + [mutableAttributedString setAttributes:[NSDictionary dictionaryWithObject:color forKey:(NSString *)kCTForegroundColorAttributeName] range:range]; + [mutableAttributedString removeAttribute:(NSString *)kCTForegroundColorFromContextAttributeName range:range]; + } + }]; + + return mutableAttributedString; +} + +static inline CGSize CTFramesetterSuggestFrameSizeForAttributedStringWithConstraints(CTFramesetterRef framesetter, NSAttributedString *attributedString, CGSize size, NSUInteger numberOfLines) { + CFRange rangeToSize = CFRangeMake(0, (CFIndex)[attributedString length]); + CGSize constraints = CGSizeMake(size.width, TTTFLOAT_MAX); + + if (numberOfLines == 1) { + // If there is one line, the size that fits is the full width of the line + constraints = CGSizeMake(TTTFLOAT_MAX, TTTFLOAT_MAX); + } else if (numberOfLines > 0) { + // If the line count of the label more than 1, limit the range to size to the number of lines that have been set + CGMutablePathRef path = CGPathCreateMutable(); + CGPathAddRect(path, NULL, CGRectMake(0.0f, 0.0f, constraints.width, TTTFLOAT_MAX)); + CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL); + CFArrayRef lines = CTFrameGetLines(frame); + + if (CFArrayGetCount(lines) > 0) { + NSInteger lastVisibleLineIndex = MIN((CFIndex)numberOfLines, CFArrayGetCount(lines)) - 1; + CTLineRef lastVisibleLine = CFArrayGetValueAtIndex(lines, lastVisibleLineIndex); + + CFRange rangeToLayout = CTLineGetStringRange(lastVisibleLine); + rangeToSize = CFRangeMake(0, rangeToLayout.location + rangeToLayout.length); + } + + CFRelease(frame); + CGPathRelease(path); + } + + CGSize suggestedSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, rangeToSize, NULL, constraints, NULL); + + return CGSizeMake(CGFloat_ceil(suggestedSize.width), CGFloat_ceil(suggestedSize.height)); +} + +@interface TTTAccessibilityElement : UIAccessibilityElement +@property (nonatomic, weak) UIView *superview; +@property (nonatomic, assign) CGRect boundingRect; +@end + +@implementation TTTAccessibilityElement + +- (CGRect)accessibilityFrame { + return UIAccessibilityConvertFrameToScreenCoordinates(self.boundingRect, self.superview); +} + +@end + +@interface TTTAttributedLabel () +@property (readwrite, nonatomic, copy) NSAttributedString *inactiveAttributedText; +@property (readwrite, nonatomic, copy) NSAttributedString *renderedAttributedText; +@property (readwrite, atomic, strong) NSDataDetector *dataDetector; +@property (readwrite, nonatomic, strong) NSArray *linkModels; +@property (readwrite, nonatomic, strong) TTTAttributedLabelLink *activeLink; +@property (readwrite, nonatomic, strong) NSArray *accessibilityElements; + +- (void) longPressGestureDidFire:(UILongPressGestureRecognizer *)sender; +@end + +@implementation TTTAttributedLabel { +@private + BOOL _needsFramesetter; + CTFramesetterRef _framesetter; + CTFramesetterRef _highlightFramesetter; +} + +@dynamic text; +@synthesize attributedText = _attributedText; + +#ifndef kCFCoreFoundationVersionNumber_iOS_7_0 +#define kCFCoreFoundationVersionNumber_iOS_7_0 847.2 +#endif + ++ (void)load { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iOS_7_0) { + Class class = [self class]; + Class superclass = class_getSuperclass(class); + + NSArray *strings = @[ + NSStringFromSelector(@selector(isAccessibilityElement)), + NSStringFromSelector(@selector(accessibilityElementCount)), + NSStringFromSelector(@selector(accessibilityElementAtIndex:)), + NSStringFromSelector(@selector(indexOfAccessibilityElement:)), + ]; + + for (NSString *string in strings) { + SEL selector = NSSelectorFromString(string); + IMP superImplementation = class_getMethodImplementation(superclass, selector); + Method method = class_getInstanceMethod(class, selector); + const char *types = method_getTypeEncoding(method); + class_replaceMethod(class, selector, superImplementation, types); + } + } + }); +} + +- (instancetype)initWithFrame:(CGRect)frame { + self = [super initWithFrame:frame]; + if (!self) { + return nil; + } + + [self commonInit]; + + return self; +} + +- (void)commonInit { + self.userInteractionEnabled = YES; +#if !TARGET_OS_TV + self.multipleTouchEnabled = NO; +#endif + + self.textInsets = UIEdgeInsetsZero; + self.lineHeightMultiple = 1.0f; + + self.linkModels = [NSArray array]; + + self.linkBackgroundEdgeInset = UIEdgeInsetsMake(0.0f, -1.0f, 0.0f, -1.0f); + + NSMutableDictionary *mutableLinkAttributes = [NSMutableDictionary dictionary]; + [mutableLinkAttributes setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCTUnderlineStyleAttributeName]; + + NSMutableDictionary *mutableActiveLinkAttributes = [NSMutableDictionary dictionary]; + [mutableActiveLinkAttributes setObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCTUnderlineStyleAttributeName]; + + NSMutableDictionary *mutableInactiveLinkAttributes = [NSMutableDictionary dictionary]; + [mutableInactiveLinkAttributes setObject:[NSNumber numberWithBool:NO] forKey:(NSString *)kCTUnderlineStyleAttributeName]; + + if ([NSMutableParagraphStyle class]) { + [mutableLinkAttributes setObject:[UIColor blueColor] forKey:(NSString *)kCTForegroundColorAttributeName]; + [mutableActiveLinkAttributes setObject:[UIColor redColor] forKey:(NSString *)kCTForegroundColorAttributeName]; + [mutableInactiveLinkAttributes setObject:[UIColor grayColor] forKey:(NSString *)kCTForegroundColorAttributeName]; + } else { + [mutableLinkAttributes setObject:(__bridge id)[[UIColor blueColor] CGColor] forKey:(NSString *)kCTForegroundColorAttributeName]; + [mutableActiveLinkAttributes setObject:(__bridge id)[[UIColor redColor] CGColor] forKey:(NSString *)kCTForegroundColorAttributeName]; + [mutableInactiveLinkAttributes setObject:(__bridge id)[[UIColor grayColor] CGColor] forKey:(NSString *)kCTForegroundColorAttributeName]; + } + + self.linkAttributes = [NSDictionary dictionaryWithDictionary:mutableLinkAttributes]; + self.activeLinkAttributes = [NSDictionary dictionaryWithDictionary:mutableActiveLinkAttributes]; + self.inactiveLinkAttributes = [NSDictionary dictionaryWithDictionary:mutableInactiveLinkAttributes]; + _extendsLinkTouchArea = NO; + _longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self + action:@selector(longPressGestureDidFire:)]; + self.longPressGestureRecognizer.delegate = self; + [self addGestureRecognizer:self.longPressGestureRecognizer]; +} + +- (void)dealloc { + if (_framesetter) { + CFRelease(_framesetter); + } + + if (_highlightFramesetter) { + CFRelease(_highlightFramesetter); + } + + if (_longPressGestureRecognizer) { + [self removeGestureRecognizer:_longPressGestureRecognizer]; + } +} + +#pragma mark - + ++ (CGSize)sizeThatFitsAttributedString:(NSAttributedString *)attributedString + withConstraints:(CGSize)size + limitedToNumberOfLines:(NSUInteger)numberOfLines +{ + if (!attributedString || attributedString.length == 0) { + return CGSizeZero; + } + + CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attributedString); + + CGSize calculatedSize = CTFramesetterSuggestFrameSizeForAttributedStringWithConstraints(framesetter, attributedString, size, numberOfLines); + + CFRelease(framesetter); + + return calculatedSize; +} + +#pragma mark - + +- (void)setAttributedText:(NSAttributedString *)text { + if ([text isEqualToAttributedString:_attributedText]) { + return; + } + + _attributedText = [text copy]; + + [self setNeedsFramesetter]; + [self setNeedsDisplay]; + + if ([self respondsToSelector:@selector(invalidateIntrinsicContentSize)]) { + [self invalidateIntrinsicContentSize]; + } + + [super setText:[self.attributedText string]]; +} + +- (NSAttributedString *)renderedAttributedText { + if (!_renderedAttributedText) { + self.renderedAttributedText = NSAttributedStringBySettingColorFromContext(self.attributedText, self.textColor); + } + + return _renderedAttributedText; +} + +- (NSArray *) links { + return [_linkModels valueForKey:@"result"]; +} + +- (void)setLinkModels:(NSArray *)linkModels { + _linkModels = linkModels; + + self.accessibilityElements = nil; +} + +- (void)setNeedsFramesetter { + // Reset the rendered attributed text so it has a chance to regenerate + self.renderedAttributedText = nil; + + _needsFramesetter = YES; +} + +- (CTFramesetterRef)framesetter { + if (_needsFramesetter) { + @synchronized(self) { + CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)self.renderedAttributedText); + [self setFramesetter:framesetter]; + [self setHighlightFramesetter:nil]; + _needsFramesetter = NO; + + if (framesetter) { + CFRelease(framesetter); + } + } + } + + return _framesetter; +} + +- (void)setFramesetter:(CTFramesetterRef)framesetter { + if (framesetter) { + CFRetain(framesetter); + } + + if (_framesetter) { + CFRelease(_framesetter); + } + + _framesetter = framesetter; +} + +- (CTFramesetterRef)highlightFramesetter { + return _highlightFramesetter; +} + +- (void)setHighlightFramesetter:(CTFramesetterRef)highlightFramesetter { + if (highlightFramesetter) { + CFRetain(highlightFramesetter); + } + + if (_highlightFramesetter) { + CFRelease(_highlightFramesetter); + } + + _highlightFramesetter = highlightFramesetter; +} + +#pragma mark - + +- (void)setEnabledTextCheckingTypes:(NSTextCheckingTypes)enabledTextCheckingTypes { + if (self.enabledTextCheckingTypes == enabledTextCheckingTypes) { + return; + } + + _enabledTextCheckingTypes = enabledTextCheckingTypes; + + // one detector instance per type (combination), fast reuse e.g. in cells + static NSMutableDictionary *dataDetectorsByType = nil; + + if (!dataDetectorsByType) { + dataDetectorsByType = [NSMutableDictionary dictionary]; + } + + if (enabledTextCheckingTypes) { + if (![dataDetectorsByType objectForKey:@(enabledTextCheckingTypes)]) { + NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:enabledTextCheckingTypes + error:nil]; + if (detector) { + [dataDetectorsByType setObject:detector forKey:@(enabledTextCheckingTypes)]; + } + } + self.dataDetector = [dataDetectorsByType objectForKey:@(enabledTextCheckingTypes)]; + } else { + self.dataDetector = nil; + } +} + +- (void)addLink:(TTTAttributedLabelLink *)link { + [self addLinks:@[link]]; +} + +- (void)addLinks:(NSArray *)links { + NSMutableArray *mutableLinkModels = [NSMutableArray arrayWithArray:self.linkModels]; + + NSMutableAttributedString *mutableAttributedString = [self.attributedText mutableCopy]; + + for (TTTAttributedLabelLink *link in links) { + if (link.attributes) { + [mutableAttributedString addAttributes:link.attributes range:link.result.range]; + } + } + + self.attributedText = mutableAttributedString; + [self setNeedsDisplay]; + + [mutableLinkModels addObjectsFromArray:links]; + + self.linkModels = [NSArray arrayWithArray:mutableLinkModels]; +} + +- (TTTAttributedLabelLink *)addLinkWithTextCheckingResult:(NSTextCheckingResult *)result + attributes:(NSDictionary *)attributes +{ + return [self addLinksWithTextCheckingResults:@[result] attributes:attributes].firstObject; +} + +- (NSArray *)addLinksWithTextCheckingResults:(NSArray *)results + attributes:(NSDictionary *)attributes +{ + NSMutableArray *links = [NSMutableArray array]; + + for (NSTextCheckingResult *result in results) { + NSDictionary *activeAttributes = attributes ? self.activeLinkAttributes : nil; + NSDictionary *inactiveAttributes = attributes ? self.inactiveLinkAttributes : nil; + + TTTAttributedLabelLink *link = [[TTTAttributedLabelLink alloc] initWithAttributes:attributes + activeAttributes:activeAttributes + inactiveAttributes:inactiveAttributes + textCheckingResult:result]; + + [links addObject:link]; + } + + [self addLinks:links]; + + return links; +} + +- (TTTAttributedLabelLink *)addLinkWithTextCheckingResult:(NSTextCheckingResult *)result { + return [self addLinkWithTextCheckingResult:result attributes:self.linkAttributes]; +} + +- (TTTAttributedLabelLink *)addLinkToURL:(NSURL *)url + withRange:(NSRange)range +{ + return [self addLinkWithTextCheckingResult:[NSTextCheckingResult linkCheckingResultWithRange:range URL:url]]; +} + +- (TTTAttributedLabelLink *)addLinkToAddress:(NSDictionary *)addressComponents + withRange:(NSRange)range +{ + return [self addLinkWithTextCheckingResult:[NSTextCheckingResult addressCheckingResultWithRange:range components:addressComponents]]; +} + +- (TTTAttributedLabelLink *)addLinkToPhoneNumber:(NSString *)phoneNumber + withRange:(NSRange)range +{ + return [self addLinkWithTextCheckingResult:[NSTextCheckingResult phoneNumberCheckingResultWithRange:range phoneNumber:phoneNumber]]; +} + +- (TTTAttributedLabelLink *)addLinkToDate:(NSDate *)date + withRange:(NSRange)range +{ + return [self addLinkWithTextCheckingResult:[NSTextCheckingResult dateCheckingResultWithRange:range date:date]]; +} + +- (TTTAttributedLabelLink *)addLinkToDate:(NSDate *)date + timeZone:(NSTimeZone *)timeZone + duration:(NSTimeInterval)duration + withRange:(NSRange)range +{ + return [self addLinkWithTextCheckingResult:[NSTextCheckingResult dateCheckingResultWithRange:range date:date timeZone:timeZone duration:duration]]; +} + +- (TTTAttributedLabelLink *)addLinkToTransitInformation:(NSDictionary *)components + withRange:(NSRange)range +{ + return [self addLinkWithTextCheckingResult:[NSTextCheckingResult transitInformationCheckingResultWithRange:range components:components]]; +} + +#pragma mark - + +- (BOOL)containslinkAtPoint:(CGPoint)point { + return [self linkAtPoint:point] != nil; +} + +- (TTTAttributedLabelLink *)linkAtPoint:(CGPoint)point { + + // Stop quickly if none of the points to be tested are in the bounds. + if (!CGRectContainsPoint(CGRectInset(self.bounds, -15.f, -15.f), point) || self.links.count == 0) { + return nil; + } + + TTTAttributedLabelLink *result = [self linkAtCharacterIndex:[self characterIndexAtPoint:point]]; + + if (!result && self.extendsLinkTouchArea) { + result = [self linkAtRadius:2.5f aroundPoint:point] + ?: [self linkAtRadius:5.f aroundPoint:point] + ?: [self linkAtRadius:7.5f aroundPoint:point] + ?: [self linkAtRadius:12.5f aroundPoint:point] + ?: [self linkAtRadius:15.f aroundPoint:point]; + } + + return result; +} + +- (TTTAttributedLabelLink *)linkAtRadius:(const CGFloat)radius aroundPoint:(CGPoint)point { + const CGFloat diagonal = CGFloat_sqrt(2 * radius * radius); + const CGPoint deltas[] = { + CGPointMake(0, -radius), CGPointMake(0, radius), // Above and below + CGPointMake(-radius, 0), CGPointMake(radius, 0), // Beside + CGPointMake(-diagonal, -diagonal), CGPointMake(-diagonal, diagonal), + CGPointMake(diagonal, diagonal), CGPointMake(diagonal, -diagonal) // Diagonal + }; + const size_t count = sizeof(deltas) / sizeof(CGPoint); + + TTTAttributedLabelLink *link = nil; + + for (NSInteger i = 0; i < count && link.result == nil; i ++) { + CGPoint currentPoint = CGPointMake(point.x + deltas[i].x, point.y + deltas[i].y); + link = [self linkAtCharacterIndex:[self characterIndexAtPoint:currentPoint]]; + } + + return link; +} + +- (TTTAttributedLabelLink *)linkAtCharacterIndex:(CFIndex)idx { + // Do not enumerate if the index is outside of the bounds of the text. + if (!NSLocationInRange((NSUInteger)idx, NSMakeRange(0, self.attributedText.length))) { + return nil; + } + + NSEnumerator *enumerator = [self.linkModels reverseObjectEnumerator]; + TTTAttributedLabelLink *link = nil; + while ((link = [enumerator nextObject])) { + if (NSLocationInRange((NSUInteger)idx, link.result.range)) { + return link; + } + } + + return nil; +} + +- (CFIndex)characterIndexAtPoint:(CGPoint)p { + if (!CGRectContainsPoint(self.bounds, p)) { + return NSNotFound; + } + + CGRect textRect = [self textRectForBounds:self.bounds limitedToNumberOfLines:self.numberOfLines]; + if (!CGRectContainsPoint(textRect, p)) { + return NSNotFound; + } + + // Offset tap coordinates by textRect origin to make them relative to the origin of frame + p = CGPointMake(p.x - textRect.origin.x, p.y - textRect.origin.y); + // Convert tap coordinates (start at top left) to CT coordinates (start at bottom left) + p = CGPointMake(p.x, textRect.size.height - p.y); + + CGMutablePathRef path = CGPathCreateMutable(); + CGPathAddRect(path, NULL, textRect); + CTFrameRef frame = CTFramesetterCreateFrame([self framesetter], CFRangeMake(0, (CFIndex)[self.attributedText length]), path, NULL); + if (frame == NULL) { + CGPathRelease(path); + return NSNotFound; + } + + CFArrayRef lines = CTFrameGetLines(frame); + NSInteger numberOfLines = self.numberOfLines > 0 ? MIN(self.numberOfLines, CFArrayGetCount(lines)) : CFArrayGetCount(lines); + if (numberOfLines == 0) { + CFRelease(frame); + CGPathRelease(path); + return NSNotFound; + } + + CFIndex idx = NSNotFound; + + CGPoint lineOrigins[numberOfLines]; + CTFrameGetLineOrigins(frame, CFRangeMake(0, numberOfLines), lineOrigins); + + for (CFIndex lineIndex = 0; lineIndex < numberOfLines; lineIndex++) { + CGPoint lineOrigin = lineOrigins[lineIndex]; + CTLineRef line = CFArrayGetValueAtIndex(lines, lineIndex); + + // Get bounding information of line + CGFloat ascent = 0.0f, descent = 0.0f, leading = 0.0f; + CGFloat width = (CGFloat)CTLineGetTypographicBounds(line, &ascent, &descent, &leading); + CGFloat yMin = (CGFloat)floor(lineOrigin.y - descent); + CGFloat yMax = (CGFloat)ceil(lineOrigin.y + ascent); + + // Apply penOffset using flushFactor for horizontal alignment to set lineOrigin since this is the horizontal offset from drawFramesetter + CGFloat flushFactor = TTTFlushFactorForTextAlignment(self.textAlignment); + CGFloat penOffset = (CGFloat)CTLineGetPenOffsetForFlush(line, flushFactor, textRect.size.width); + lineOrigin.x = penOffset; + + // Check if we've already passed the line + if (p.y > yMax) { + break; + } + // Check if the point is within this line vertically + if (p.y >= yMin) { + // Check if the point is within this line horizontally + if (p.x >= lineOrigin.x && p.x <= lineOrigin.x + width) { + // Convert CT coordinates to line-relative coordinates + CGPoint relativePoint = CGPointMake(p.x - lineOrigin.x, p.y - lineOrigin.y); + idx = CTLineGetStringIndexForPosition(line, relativePoint); + break; + } + } + } + + CFRelease(frame); + CGPathRelease(path); + + return idx; +} + +- (CGRect)boundingRectForCharacterRange:(NSRange)range { + NSMutableAttributedString *mutableAttributedString = [self.attributedText mutableCopy]; + + NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:mutableAttributedString]; + + NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init]; + [textStorage addLayoutManager:layoutManager]; + + NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:self.bounds.size]; + [layoutManager addTextContainer:textContainer]; + + NSRange glyphRange; + [layoutManager characterRangeForGlyphRange:range actualGlyphRange:&glyphRange]; + + return [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer]; +} + +- (void)drawFramesetter:(CTFramesetterRef)framesetter + attributedString:(NSAttributedString *)attributedString + textRange:(CFRange)textRange + inRect:(CGRect)rect + context:(CGContextRef)c +{ + CGMutablePathRef path = CGPathCreateMutable(); + CGPathAddRect(path, NULL, rect); + CTFrameRef frame = CTFramesetterCreateFrame(framesetter, textRange, path, NULL); + + [self drawBackground:frame inRect:rect context:c]; + + CFArrayRef lines = CTFrameGetLines(frame); + NSInteger numberOfLines = self.numberOfLines > 0 ? MIN(self.numberOfLines, CFArrayGetCount(lines)) : CFArrayGetCount(lines); + BOOL truncateLastLine = (self.lineBreakMode == TTTLineBreakByTruncatingHead || self.lineBreakMode == TTTLineBreakByTruncatingMiddle || self.lineBreakMode == TTTLineBreakByTruncatingTail); + + CGPoint lineOrigins[numberOfLines]; + CTFrameGetLineOrigins(frame, CFRangeMake(0, numberOfLines), lineOrigins); + + for (CFIndex lineIndex = 0; lineIndex < numberOfLines; lineIndex++) { + CGPoint lineOrigin = lineOrigins[lineIndex]; + CGContextSetTextPosition(c, lineOrigin.x, lineOrigin.y); + CTLineRef line = CFArrayGetValueAtIndex(lines, lineIndex); + + CGFloat descent = 0.0f; + CTLineGetTypographicBounds((CTLineRef)line, NULL, &descent, NULL); + + // Adjust pen offset for flush depending on text alignment + CGFloat flushFactor = TTTFlushFactorForTextAlignment(self.textAlignment); + + if (lineIndex == numberOfLines - 1 && truncateLastLine) { + // Check if the range of text in the last line reaches the end of the full attributed string + CFRange lastLineRange = CTLineGetStringRange(line); + + if (!(lastLineRange.length == 0 && lastLineRange.location == 0) && lastLineRange.location + lastLineRange.length < textRange.location + textRange.length) { + // Get correct truncationType and attribute position + CTLineTruncationType truncationType; + CFIndex truncationAttributePosition = lastLineRange.location; + TTTLineBreakMode lineBreakMode = self.lineBreakMode; + + // Multiple lines, only use UILineBreakModeTailTruncation + if (numberOfLines != 1) { + lineBreakMode = TTTLineBreakByTruncatingTail; + } + + switch (lineBreakMode) { + case TTTLineBreakByTruncatingHead: + truncationType = kCTLineTruncationStart; + break; + case TTTLineBreakByTruncatingMiddle: + truncationType = kCTLineTruncationMiddle; + truncationAttributePosition += (lastLineRange.length / 2); + break; + case TTTLineBreakByTruncatingTail: + default: + truncationType = kCTLineTruncationEnd; + truncationAttributePosition += (lastLineRange.length - 1); + break; + } + + NSAttributedString *attributedTruncationString = self.attributedTruncationToken; + if (!attributedTruncationString) { + NSString *truncationTokenString = @"\u2026"; // Unicode Character 'HORIZONTAL ELLIPSIS' (U+2026) + + NSDictionary *truncationTokenStringAttributes = truncationTokenStringAttributes = [attributedString attributesAtIndex:(NSUInteger)truncationAttributePosition effectiveRange:NULL]; + + attributedTruncationString = [[NSAttributedString alloc] initWithString:truncationTokenString attributes:truncationTokenStringAttributes]; + } + CTLineRef truncationToken = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)attributedTruncationString); + + // Append truncationToken to the string + // because if string isn't too long, CT won't add the truncationToken on its own. + // There is no chance of a double truncationToken because CT only adds the + // token if it removes characters (and the one we add will go first) + NSMutableAttributedString *truncationString = [[NSMutableAttributedString alloc] initWithAttributedString: + [attributedString attributedSubstringFromRange: + NSMakeRange((NSUInteger)lastLineRange.location, + (NSUInteger)lastLineRange.length)]]; + if (lastLineRange.length > 0) { + // Remove any newline at the end (we don't want newline space between the text and the truncation token). There can only be one, because the second would be on the next line. + unichar lastCharacter = [[truncationString string] characterAtIndex:(NSUInteger)(lastLineRange.length - 1)]; + if ([[NSCharacterSet newlineCharacterSet] characterIsMember:lastCharacter]) { + [truncationString deleteCharactersInRange:NSMakeRange((NSUInteger)(lastLineRange.length - 1), 1)]; + } + } + [truncationString appendAttributedString:attributedTruncationString]; + CTLineRef truncationLine = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)truncationString); + + // Truncate the line in case it is too long. + CTLineRef truncatedLine = CTLineCreateTruncatedLine(truncationLine, rect.size.width, truncationType, truncationToken); + if (!truncatedLine) { + // If the line is not as wide as the truncationToken, truncatedLine is NULL + truncatedLine = CFRetain(truncationToken); + } + + CGFloat penOffset = (CGFloat)CTLineGetPenOffsetForFlush(truncatedLine, flushFactor, rect.size.width); + CGContextSetTextPosition(c, penOffset, lineOrigin.y - descent - self.font.descender); + + CTLineDraw(truncatedLine, c); + + NSRange linkRange; + if ([attributedTruncationString attribute:NSLinkAttributeName atIndex:0 effectiveRange:&linkRange]) { + NSRange tokenRange = [truncationString.string rangeOfString:attributedTruncationString.string]; + NSRange tokenLinkRange = NSMakeRange((NSUInteger)(lastLineRange.location+lastLineRange.length)-tokenRange.length, (NSUInteger)tokenRange.length); + + [self addLinkToURL:[attributedTruncationString attribute:NSLinkAttributeName atIndex:0 effectiveRange:&linkRange] withRange:tokenLinkRange]; + } + + CFRelease(truncatedLine); + CFRelease(truncationLine); + CFRelease(truncationToken); + } else { + CGFloat penOffset = (CGFloat)CTLineGetPenOffsetForFlush(line, flushFactor, rect.size.width); + CGContextSetTextPosition(c, penOffset, lineOrigin.y - descent - self.font.descender); + CTLineDraw(line, c); + } + } else { + CGFloat penOffset = (CGFloat)CTLineGetPenOffsetForFlush(line, flushFactor, rect.size.width); + CGContextSetTextPosition(c, penOffset, lineOrigin.y - descent - self.font.descender); + CTLineDraw(line, c); + } + } + + [self drawStrike:frame inRect:rect context:c]; + + CFRelease(frame); + CGPathRelease(path); +} + +- (void)drawBackground:(CTFrameRef)frame + inRect:(CGRect)rect + context:(CGContextRef)c +{ + NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame); + CGPoint origins[[lines count]]; + CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), origins); + + CFIndex lineIndex = 0; + for (id line in lines) { + CGFloat ascent = 0.0f, descent = 0.0f, leading = 0.0f; + CGFloat width = (CGFloat)CTLineGetTypographicBounds((__bridge CTLineRef)line, &ascent, &descent, &leading) ; + + for (id glyphRun in (__bridge NSArray *)CTLineGetGlyphRuns((__bridge CTLineRef)line)) { + NSDictionary *attributes = (__bridge NSDictionary *)CTRunGetAttributes((__bridge CTRunRef) glyphRun); + CGColorRef strokeColor = CGColorRefFromColor([attributes objectForKey:kTTTBackgroundStrokeColorAttributeName]); + CGColorRef fillColor = CGColorRefFromColor([attributes objectForKey:kTTTBackgroundFillColorAttributeName]); + UIEdgeInsets fillPadding = [[attributes objectForKey:kTTTBackgroundFillPaddingAttributeName] UIEdgeInsetsValue]; + CGFloat cornerRadius = [[attributes objectForKey:kTTTBackgroundCornerRadiusAttributeName] floatValue]; + CGFloat lineWidth = [[attributes objectForKey:kTTTBackgroundLineWidthAttributeName] floatValue]; + + if (strokeColor || fillColor) { + CGRect runBounds = CGRectZero; + CGFloat runAscent = 0.0f; + CGFloat runDescent = 0.0f; + + runBounds.size.width = (CGFloat)CTRunGetTypographicBounds((__bridge CTRunRef)glyphRun, CFRangeMake(0, 0), &runAscent, &runDescent, NULL) + fillPadding.left + fillPadding.right; + runBounds.size.height = runAscent + runDescent + fillPadding.top + fillPadding.bottom; + + CGFloat xOffset = 0.0f; + CFRange glyphRange = CTRunGetStringRange((__bridge CTRunRef)glyphRun); + switch (CTRunGetStatus((__bridge CTRunRef)glyphRun)) { + case kCTRunStatusRightToLeft: + xOffset = CTLineGetOffsetForStringIndex((__bridge CTLineRef)line, glyphRange.location + glyphRange.length, NULL); + break; + default: + xOffset = CTLineGetOffsetForStringIndex((__bridge CTLineRef)line, glyphRange.location, NULL); + break; + } + + runBounds.origin.x = origins[lineIndex].x + rect.origin.x + xOffset - fillPadding.left - rect.origin.x; + runBounds.origin.y = origins[lineIndex].y + rect.origin.y - fillPadding.bottom - rect.origin.y; + runBounds.origin.y -= runDescent; + + // Don't draw higlightedLinkBackground too far to the right + if (CGRectGetWidth(runBounds) > width) { + runBounds.size.width = width; + } + + CGPathRef path = [[UIBezierPath bezierPathWithRoundedRect:CGRectInset(UIEdgeInsetsInsetRect(runBounds, self.linkBackgroundEdgeInset), lineWidth, lineWidth) cornerRadius:cornerRadius] CGPath]; + + CGContextSetLineJoin(c, kCGLineJoinRound); + + if (fillColor) { + CGContextSetFillColorWithColor(c, fillColor); + CGContextAddPath(c, path); + CGContextFillPath(c); + } + + if (strokeColor) { + CGContextSetStrokeColorWithColor(c, strokeColor); + CGContextAddPath(c, path); + CGContextStrokePath(c); + } + } + } + + lineIndex++; + } +} + +- (void)drawStrike:(CTFrameRef)frame + inRect:(__unused CGRect)rect + context:(CGContextRef)c +{ + NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame); + CGPoint origins[[lines count]]; + CTFrameGetLineOrigins(frame, CFRangeMake(0, 0), origins); + + CFIndex lineIndex = 0; + for (id line in lines) { + CGFloat ascent = 0.0f, descent = 0.0f, leading = 0.0f; + CGFloat width = (CGFloat)CTLineGetTypographicBounds((__bridge CTLineRef)line, &ascent, &descent, &leading) ; + + for (id glyphRun in (__bridge NSArray *)CTLineGetGlyphRuns((__bridge CTLineRef)line)) { + NSDictionary *attributes = (__bridge NSDictionary *)CTRunGetAttributes((__bridge CTRunRef) glyphRun); + BOOL strikeOut = [[attributes objectForKey:kTTTStrikeOutAttributeName] boolValue]; + NSInteger superscriptStyle = [[attributes objectForKey:(id)kCTSuperscriptAttributeName] integerValue]; + + if (strikeOut) { + CGRect runBounds = CGRectZero; + CGFloat runAscent = 0.0f; + CGFloat runDescent = 0.0f; + + runBounds.size.width = (CGFloat)CTRunGetTypographicBounds((__bridge CTRunRef)glyphRun, CFRangeMake(0, 0), &runAscent, &runDescent, NULL); + runBounds.size.height = runAscent + runDescent; + + CGFloat xOffset = 0.0f; + CFRange glyphRange = CTRunGetStringRange((__bridge CTRunRef)glyphRun); + switch (CTRunGetStatus((__bridge CTRunRef)glyphRun)) { + case kCTRunStatusRightToLeft: + xOffset = CTLineGetOffsetForStringIndex((__bridge CTLineRef)line, glyphRange.location + glyphRange.length, NULL); + break; + default: + xOffset = CTLineGetOffsetForStringIndex((__bridge CTLineRef)line, glyphRange.location, NULL); + break; + } + runBounds.origin.x = origins[lineIndex].x + xOffset; + runBounds.origin.y = origins[lineIndex].y; + runBounds.origin.y -= runDescent; + + // Don't draw strikeout too far to the right + if (CGRectGetWidth(runBounds) > width) { + runBounds.size.width = width; + } + + switch (superscriptStyle) { + case 1: + runBounds.origin.y -= runAscent * 0.47f; + break; + case -1: + runBounds.origin.y += runAscent * 0.25f; + break; + default: + break; + } + + // Use text color, or default to black + id color = [attributes objectForKey:(id)kCTForegroundColorAttributeName]; + if (color) { + CGContextSetStrokeColorWithColor(c, CGColorRefFromColor(color)); + } else { + CGContextSetGrayStrokeColor(c, 0.0f, 1.0); + } + + CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)self.font.fontName, self.font.pointSize, NULL); + CGContextSetLineWidth(c, CTFontGetUnderlineThickness(font)); + CFRelease(font); + + CGFloat y = CGFloat_round(runBounds.origin.y + runBounds.size.height / 2.0f); + CGContextMoveToPoint(c, runBounds.origin.x, y); + CGContextAddLineToPoint(c, runBounds.origin.x + runBounds.size.width, y); + + CGContextStrokePath(c); + } + } + + lineIndex++; + } +} + +#pragma mark - TTTAttributedLabel + +- (void)setText:(id)text { + NSParameterAssert(!text || [text isKindOfClass:[NSAttributedString class]] || [text isKindOfClass:[NSString class]]); + + if ([text isKindOfClass:[NSString class]]) { + [self setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:nil]; + return; + } + + self.attributedText = text; + self.activeLink = nil; + + self.linkModels = [NSArray array]; + if (text && self.attributedText && self.enabledTextCheckingTypes) { + __weak __typeof(self)weakSelf = self; + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + __strong __typeof(weakSelf)strongSelf = weakSelf; + + NSDataDetector *dataDetector = strongSelf.dataDetector; + if (dataDetector && [dataDetector respondsToSelector:@selector(matchesInString:options:range:)]) { + NSArray *results = [dataDetector matchesInString:[(NSAttributedString *)text string] options:0 range:NSMakeRange(0, [(NSAttributedString *)text length])]; + if ([results count] > 0) { + dispatch_async(dispatch_get_main_queue(), ^{ + if ([[strongSelf.attributedText string] isEqualToString:[(NSAttributedString *)text string]]) { + [strongSelf addLinksWithTextCheckingResults:results attributes:strongSelf.linkAttributes]; + } + }); + } + } + }); + } + + [self.attributedText enumerateAttribute:NSLinkAttributeName inRange:NSMakeRange(0, self.attributedText.length) options:0 usingBlock:^(id value, __unused NSRange range, __unused BOOL *stop) { + if (value) { + NSURL *URL = [value isKindOfClass:[NSString class]] ? [NSURL URLWithString:value] : value; + [self addLinkToURL:URL withRange:range]; + } + }]; +} + +- (void)setText:(id)text +afterInheritingLabelAttributesAndConfiguringWithBlock:(NSMutableAttributedString * (^)(NSMutableAttributedString *mutableAttributedString))block +{ + NSMutableAttributedString *mutableAttributedString = nil; + if ([text isKindOfClass:[NSString class]]) { + mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:text attributes:NSAttributedStringAttributesFromLabel(self)]; + } else { + mutableAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:text]; + [mutableAttributedString addAttributes:NSAttributedStringAttributesFromLabel(self) range:NSMakeRange(0, [mutableAttributedString length])]; + } + + if (block) { + mutableAttributedString = block(mutableAttributedString); + } + + [self setText:mutableAttributedString]; +} + +- (void)setActiveLink:(TTTAttributedLabelLink *)activeLink { + _activeLink = activeLink; + + NSDictionary *activeAttributes = activeLink.activeAttributes ?: self.activeLinkAttributes; + + if (_activeLink && activeAttributes.count > 0) { + if (!self.inactiveAttributedText) { + self.inactiveAttributedText = [self.attributedText copy]; + } + + NSMutableAttributedString *mutableAttributedString = [self.inactiveAttributedText mutableCopy]; + if (self.activeLink.result.range.length > 0 && NSLocationInRange(NSMaxRange(self.activeLink.result.range) - 1, NSMakeRange(0, [self.inactiveAttributedText length]))) { + [mutableAttributedString addAttributes:activeAttributes range:self.activeLink.result.range]; + } + + self.attributedText = mutableAttributedString; + [self setNeedsDisplay]; + + [CATransaction flush]; + } else if (self.inactiveAttributedText) { + self.attributedText = self.inactiveAttributedText; + self.inactiveAttributedText = nil; + + [self setNeedsDisplay]; + } +} + +- (void)setLinkAttributes:(NSDictionary *)linkAttributes { + _linkAttributes = convertNSAttributedStringAttributesToCTAttributes(linkAttributes); +} + +- (void)setActiveLinkAttributes:(NSDictionary *)activeLinkAttributes { + _activeLinkAttributes = convertNSAttributedStringAttributesToCTAttributes(activeLinkAttributes); +} + +- (void)setInactiveLinkAttributes:(NSDictionary *)inactiveLinkAttributes { + _inactiveLinkAttributes = convertNSAttributedStringAttributesToCTAttributes(inactiveLinkAttributes); +} + +#pragma mark - UILabel + +- (void)setHighlighted:(BOOL)highlighted { + [super setHighlighted:highlighted]; + [self setNeedsDisplay]; +} + +// Fixes crash when loading from a UIStoryboard +- (UIColor *)textColor { + UIColor *color = [super textColor]; + if (!color) { + color = [UIColor blackColor]; + } + + return color; +} + +- (void)setTextColor:(UIColor *)textColor { + UIColor *oldTextColor = self.textColor; + [super setTextColor:textColor]; + + // Redraw to allow any ColorFromContext attributes a chance to update + if (textColor != oldTextColor) { + [self setNeedsFramesetter]; + [self setNeedsDisplay]; + } +} + +- (CGRect)textRectForBounds:(CGRect)bounds + limitedToNumberOfLines:(NSInteger)numberOfLines +{ + bounds = UIEdgeInsetsInsetRect(bounds, self.textInsets); + if (!self.attributedText) { + return [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines]; + } + + CGRect textRect = bounds; + + // Calculate height with a minimum of double the font pointSize, to ensure that CTFramesetterSuggestFrameSizeWithConstraints doesn't return CGSizeZero, as it would if textRect height is insufficient. + textRect.size.height = MAX(self.font.lineHeight * MAX(2, numberOfLines), bounds.size.height); + + // Adjust the text to be in the center vertically, if the text size is smaller than bounds + CGSize textSize = CTFramesetterSuggestFrameSizeWithConstraints([self framesetter], CFRangeMake(0, (CFIndex)[self.attributedText length]), NULL, textRect.size, NULL); + textSize = CGSizeMake(CGFloat_ceil(textSize.width), CGFloat_ceil(textSize.height)); // Fix for iOS 4, CTFramesetterSuggestFrameSizeWithConstraints sometimes returns fractional sizes + + if (textSize.height < bounds.size.height) { + CGFloat yOffset = 0.0f; + switch (self.verticalAlignment) { + case TTTAttributedLabelVerticalAlignmentCenter: + yOffset = CGFloat_floor((bounds.size.height - textSize.height) / 2.0f); + break; + case TTTAttributedLabelVerticalAlignmentBottom: + yOffset = bounds.size.height - textSize.height; + break; + case TTTAttributedLabelVerticalAlignmentTop: + default: + break; + } + + textRect.origin.y += yOffset; + } + + return textRect; +} + +- (void)drawTextInRect:(CGRect)rect { + CGRect insetRect = UIEdgeInsetsInsetRect(rect, self.textInsets); + if (!self.attributedText) { + [super drawTextInRect:insetRect]; + return; + } + + NSAttributedString *originalAttributedText = nil; + + // Adjust the font size to fit width, if necessarry + if (self.adjustsFontSizeToFitWidth && self.numberOfLines > 0) { + // Framesetter could still be working with a resized version of the text; + // need to reset so we start from the original font size. + // See #393. + [self setNeedsFramesetter]; + [self setNeedsDisplay]; + + if ([self respondsToSelector:@selector(invalidateIntrinsicContentSize)]) { + [self invalidateIntrinsicContentSize]; + } + + // Use infinite width to find the max width, which will be compared to availableWidth if needed. + CGSize maxSize = (self.numberOfLines > 1) ? CGSizeMake(TTTFLOAT_MAX, TTTFLOAT_MAX) : CGSizeZero; + + CGFloat textWidth = [self sizeThatFits:maxSize].width; + CGFloat availableWidth = self.frame.size.width * self.numberOfLines; + if (self.numberOfLines > 1 && self.lineBreakMode == TTTLineBreakByWordWrapping) { + textWidth *= kTTTLineBreakWordWrapTextWidthScalingFactor; + } + + if (textWidth > availableWidth && textWidth > 0.0f) { + originalAttributedText = [self.attributedText copy]; + + CGFloat scaleFactor = availableWidth / textWidth; + if ([self respondsToSelector:@selector(minimumScaleFactor)] && self.minimumScaleFactor > scaleFactor) { + scaleFactor = self.minimumScaleFactor; + } + + self.attributedText = NSAttributedStringByScalingFontSize(self.attributedText, scaleFactor); + } + } + + CGContextRef c = UIGraphicsGetCurrentContext(); + CGContextSaveGState(c); + { + CGContextSetTextMatrix(c, CGAffineTransformIdentity); + + // Inverts the CTM to match iOS coordinates (otherwise text draws upside-down; Mac OS's system is different) + CGContextTranslateCTM(c, 0.0f, insetRect.size.height); + CGContextScaleCTM(c, 1.0f, -1.0f); + + CFRange textRange = CFRangeMake(0, (CFIndex)[self.attributedText length]); + + // First, get the text rect (which takes vertical centering into account) + CGRect textRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines]; + + // CoreText draws its text aligned to the bottom, so we move the CTM here to take our vertical offsets into account + CGContextTranslateCTM(c, insetRect.origin.x, insetRect.size.height - textRect.origin.y - textRect.size.height); + + // Second, trace the shadow before the actual text, if we have one + if (self.shadowColor && !self.highlighted) { + CGContextSetShadowWithColor(c, self.shadowOffset, self.shadowRadius, [self.shadowColor CGColor]); + } else if (self.highlightedShadowColor) { + CGContextSetShadowWithColor(c, self.highlightedShadowOffset, self.highlightedShadowRadius, [self.highlightedShadowColor CGColor]); + } + + // Finally, draw the text or highlighted text itself (on top of the shadow, if there is one) + if (self.highlightedTextColor && self.highlighted) { + NSMutableAttributedString *highlightAttributedString = [self.renderedAttributedText mutableCopy]; + [highlightAttributedString addAttribute:(__bridge NSString *)kCTForegroundColorAttributeName value:(id)[self.highlightedTextColor CGColor] range:NSMakeRange(0, highlightAttributedString.length)]; + + if (![self highlightFramesetter]) { + CTFramesetterRef highlightFramesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)highlightAttributedString); + [self setHighlightFramesetter:highlightFramesetter]; + CFRelease(highlightFramesetter); + } + + [self drawFramesetter:[self highlightFramesetter] attributedString:highlightAttributedString textRange:textRange inRect:textRect context:c]; + } else { + [self drawFramesetter:[self framesetter] attributedString:self.renderedAttributedText textRange:textRange inRect:textRect context:c]; + } + + // If we adjusted the font size, set it back to its original size + if (originalAttributedText) { + // Use ivar directly to avoid clearing out framesetter and renderedAttributedText + _attributedText = originalAttributedText; + } + } + CGContextRestoreGState(c); +} + +#pragma mark - UIAccessibilityElement + +- (BOOL)isAccessibilityElement { + return NO; +} + +- (NSInteger)accessibilityElementCount { + return (NSInteger)[[self accessibilityElements] count]; +} + +- (id)accessibilityElementAtIndex:(NSInteger)index { + return [[self accessibilityElements] objectAtIndex:(NSUInteger)index]; +} + +- (NSInteger)indexOfAccessibilityElement:(id)element { + return (NSInteger)[[self accessibilityElements] indexOfObject:element]; +} + +- (NSArray *)accessibilityElements { + if (!_accessibilityElements) { + @synchronized(self) { + NSMutableArray *mutableAccessibilityItems = [NSMutableArray array]; + + for (TTTAttributedLabelLink *link in self.linkModels) { + + if (link.result.range.location == NSNotFound) { + continue; + } + + NSString *sourceText = [self.text isKindOfClass:[NSString class]] ? self.text : [(NSAttributedString *)self.text string]; + + NSString *accessibilityLabel = [sourceText substringWithRange:link.result.range]; + NSString *accessibilityValue = link.accessibilityValue; + + if (accessibilityLabel) { + TTTAccessibilityElement *linkElement = [[TTTAccessibilityElement alloc] initWithAccessibilityContainer:self]; + linkElement.accessibilityTraits = UIAccessibilityTraitLink; + linkElement.boundingRect = [self boundingRectForCharacterRange:link.result.range]; + linkElement.superview = self; + linkElement.accessibilityLabel = accessibilityLabel; + + if (![accessibilityLabel isEqualToString:accessibilityValue]) { + linkElement.accessibilityValue = accessibilityValue; + } + + [mutableAccessibilityItems addObject:linkElement]; + } + } + + TTTAccessibilityElement *baseElement = [[TTTAccessibilityElement alloc] initWithAccessibilityContainer:self]; + baseElement.accessibilityLabel = [super accessibilityLabel]; + baseElement.accessibilityHint = [super accessibilityHint]; + baseElement.accessibilityValue = [super accessibilityValue]; + baseElement.boundingRect = self.bounds; + baseElement.superview = self; + baseElement.accessibilityTraits = [super accessibilityTraits]; + + [mutableAccessibilityItems addObject:baseElement]; + + self.accessibilityElements = [NSArray arrayWithArray:mutableAccessibilityItems]; + } + } + + return _accessibilityElements; +} + +#pragma mark - UIView + +- (CGSize)sizeThatFits:(CGSize)size { + if (!self.attributedText) { + return [super sizeThatFits:size]; + } else { + NSMutableAttributedString *fullString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText]; + + if (self.attributedTruncationToken) { + [fullString appendAttributedString:self.attributedTruncationToken]; + } + + NSAttributedString *string = [[NSAttributedString alloc] initWithAttributedString:fullString]; + + CGSize labelSize = CTFramesetterSuggestFrameSizeForAttributedStringWithConstraints([self framesetter], string, size, (NSUInteger)self.numberOfLines); + labelSize.width += self.textInsets.left + self.textInsets.right; + labelSize.height += self.textInsets.top + self.textInsets.bottom; + + return labelSize; + } +} + +- (CGSize)intrinsicContentSize { + // There's an implicit width from the original UILabel implementation + return [self sizeThatFits:[super intrinsicContentSize]]; +} + +- (void)tintColorDidChange { + if (!self.inactiveLinkAttributes || [self.inactiveLinkAttributes count] == 0) { + return; + } + + BOOL isInactive = (self.tintAdjustmentMode == UIViewTintAdjustmentModeDimmed); + + NSMutableAttributedString *mutableAttributedString = [self.attributedText mutableCopy]; + for (TTTAttributedLabelLink *link in self.linkModels) { + NSDictionary *attributesToRemove = isInactive ? link.attributes : link.inactiveAttributes; + NSDictionary *attributesToAdd = isInactive ? link.inactiveAttributes : link.attributes; + + [attributesToRemove enumerateKeysAndObjectsUsingBlock:^(NSString *name, __unused id value, __unused BOOL *stop) { + if (NSMaxRange(link.result.range) <= mutableAttributedString.length) { + [mutableAttributedString removeAttribute:name range:link.result.range]; + } + }]; + + if (attributesToAdd) { + if (NSMaxRange(link.result.range) <= mutableAttributedString.length) { + [mutableAttributedString addAttributes:attributesToAdd range:link.result.range]; + } + } + } + + self.attributedText = mutableAttributedString; + + [self setNeedsDisplay]; +} + +- (UIView *)hitTest:(CGPoint)point + withEvent:(UIEvent *)event +{ + if (![self linkAtPoint:point] || !self.userInteractionEnabled || self.hidden || self.alpha < 0.01) { + return [super hitTest:point withEvent:event]; + } + + return self; +} + +#pragma mark - UIResponder + +- (BOOL)canBecomeFirstResponder { + return YES; +} + +- (BOOL)canPerformAction:(SEL)action + withSender:(__unused id)sender +{ +#if !TARGET_OS_TV + return (action == @selector(copy:)); +#else + return NO; +#endif +} + +- (void)touchesBegan:(NSSet *)touches + withEvent:(UIEvent *)event +{ + UITouch *touch = [touches anyObject]; + + self.activeLink = [self linkAtPoint:[touch locationInView:self]]; + + if (!self.activeLink) { + [super touchesBegan:touches withEvent:event]; + } +} + +- (void)touchesMoved:(NSSet *)touches + withEvent:(UIEvent *)event +{ + if (self.activeLink) { + UITouch *touch = [touches anyObject]; + + if (self.activeLink != [self linkAtPoint:[touch locationInView:self]]) { + self.activeLink = nil; + } + } else { + [super touchesMoved:touches withEvent:event]; + } +} + +- (void)touchesEnded:(NSSet *)touches + withEvent:(UIEvent *)event +{ + if (self.activeLink) { + if (self.activeLink.linkTapBlock) { + self.activeLink.linkTapBlock(self, self.activeLink); + self.activeLink = nil; + return; + } + + NSTextCheckingResult *result = self.activeLink.result; + self.activeLink = nil; + + switch (result.resultType) { + case NSTextCheckingTypeLink: + if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithURL:)]) { + [self.delegate attributedLabel:self didSelectLinkWithURL:result.URL]; + return; + } + break; + case NSTextCheckingTypeAddress: + if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithAddress:)]) { + [self.delegate attributedLabel:self didSelectLinkWithAddress:result.addressComponents]; + return; + } + break; + case NSTextCheckingTypePhoneNumber: + if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithPhoneNumber:)]) { + [self.delegate attributedLabel:self didSelectLinkWithPhoneNumber:result.phoneNumber]; + return; + } + break; + case NSTextCheckingTypeDate: + if (result.timeZone && [self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithDate:timeZone:duration:)]) { + [self.delegate attributedLabel:self didSelectLinkWithDate:result.date timeZone:result.timeZone duration:result.duration]; + return; + } else if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithDate:)]) { + [self.delegate attributedLabel:self didSelectLinkWithDate:result.date]; + return; + } + break; + case NSTextCheckingTypeTransitInformation: + if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithTransitInformation:)]) { + [self.delegate attributedLabel:self didSelectLinkWithTransitInformation:result.components]; + return; + } + default: + break; + } + + // Fallback to `attributedLabel:didSelectLinkWithTextCheckingResult:` if no other delegate method matched. + if ([self.delegate respondsToSelector:@selector(attributedLabel:didSelectLinkWithTextCheckingResult:)]) { + [self.delegate attributedLabel:self didSelectLinkWithTextCheckingResult:result]; + } + } else { + [super touchesEnded:touches withEvent:event]; + } +} + +- (void)touchesCancelled:(NSSet *)touches + withEvent:(UIEvent *)event +{ + if (self.activeLink) { + self.activeLink = nil; + } else { + [super touchesCancelled:touches withEvent:event]; + } +} + +#pragma mark - UIGestureRecognizerDelegate + +- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { + return [self containslinkAtPoint:[touch locationInView:self]]; +} + +#pragma mark - UILongPressGestureRecognizer + +- (void)longPressGestureDidFire:(UILongPressGestureRecognizer *)sender { + switch (sender.state) { + case UIGestureRecognizerStateBegan: { + CGPoint touchPoint = [sender locationInView:self]; + TTTAttributedLabelLink *link = [self linkAtPoint:touchPoint]; + + if (link) { + if (link.linkLongPressBlock) { + link.linkLongPressBlock(self, link); + return; + } + + NSTextCheckingResult *result = link.result; + + if (!result) { + return; + } + + switch (result.resultType) { + case NSTextCheckingTypeLink: + if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithURL:atPoint:)]) { + [self.delegate attributedLabel:self didLongPressLinkWithURL:result.URL atPoint:touchPoint]; + return; + } + break; + case NSTextCheckingTypeAddress: + if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithAddress:atPoint:)]) { + [self.delegate attributedLabel:self didLongPressLinkWithAddress:result.addressComponents atPoint:touchPoint]; + return; + } + break; + case NSTextCheckingTypePhoneNumber: + if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithPhoneNumber:atPoint:)]) { + [self.delegate attributedLabel:self didLongPressLinkWithPhoneNumber:result.phoneNumber atPoint:touchPoint]; + return; + } + break; + case NSTextCheckingTypeDate: + if (result.timeZone && [self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithDate:timeZone:duration:atPoint:)]) { + [self.delegate attributedLabel:self didLongPressLinkWithDate:result.date timeZone:result.timeZone duration:result.duration atPoint:touchPoint]; + return; + } else if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithDate:atPoint:)]) { + [self.delegate attributedLabel:self didLongPressLinkWithDate:result.date atPoint:touchPoint]; + return; + } + break; + case NSTextCheckingTypeTransitInformation: + if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithTransitInformation:atPoint:)]) { + [self.delegate attributedLabel:self didLongPressLinkWithTransitInformation:result.components atPoint:touchPoint]; + return; + } + default: + break; + } + + // Fallback to `attributedLabel:didLongPressLinkWithTextCheckingResult:atPoint:` if no other delegate method matched. + if ([self.delegate respondsToSelector:@selector(attributedLabel:didLongPressLinkWithTextCheckingResult:atPoint:)]) { + [self.delegate attributedLabel:self didLongPressLinkWithTextCheckingResult:result atPoint:touchPoint]; + } + } + break; + } + default: + break; + } +} + +#if !TARGET_OS_TV +#pragma mark - UIResponderStandardEditActions + +- (void)copy:(__unused id)sender { + [[UIPasteboard generalPasteboard] setString:self.text]; +} +#endif + +#pragma mark - NSCoding + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.enabledTextCheckingTypes) forKey:NSStringFromSelector(@selector(enabledTextCheckingTypes))]; + + [coder encodeObject:self.linkModels forKey:NSStringFromSelector(@selector(linkModels))]; + if ([NSMutableParagraphStyle class]) { + [coder encodeObject:self.linkAttributes forKey:NSStringFromSelector(@selector(linkAttributes))]; + [coder encodeObject:self.activeLinkAttributes forKey:NSStringFromSelector(@selector(activeLinkAttributes))]; + [coder encodeObject:self.inactiveLinkAttributes forKey:NSStringFromSelector(@selector(inactiveLinkAttributes))]; + } + [coder encodeObject:@(self.shadowRadius) forKey:NSStringFromSelector(@selector(shadowRadius))]; + [coder encodeObject:@(self.highlightedShadowRadius) forKey:NSStringFromSelector(@selector(highlightedShadowRadius))]; + [coder encodeCGSize:self.highlightedShadowOffset forKey:NSStringFromSelector(@selector(highlightedShadowOffset))]; + [coder encodeObject:self.highlightedShadowColor forKey:NSStringFromSelector(@selector(highlightedShadowColor))]; + [coder encodeObject:@(self.kern) forKey:NSStringFromSelector(@selector(kern))]; + [coder encodeObject:@(self.firstLineIndent) forKey:NSStringFromSelector(@selector(firstLineIndent))]; + [coder encodeObject:@(self.lineSpacing) forKey:NSStringFromSelector(@selector(lineSpacing))]; + [coder encodeObject:@(self.lineHeightMultiple) forKey:NSStringFromSelector(@selector(lineHeightMultiple))]; + [coder encodeUIEdgeInsets:self.textInsets forKey:NSStringFromSelector(@selector(textInsets))]; + [coder encodeInteger:self.verticalAlignment forKey:NSStringFromSelector(@selector(verticalAlignment))]; + + [coder encodeObject:self.attributedTruncationToken forKey:NSStringFromSelector(@selector(attributedTruncationToken))]; + + [coder encodeObject:NSStringFromUIEdgeInsets(self.linkBackgroundEdgeInset) forKey:NSStringFromSelector(@selector(linkBackgroundEdgeInset))]; + [coder encodeObject:self.attributedText forKey:NSStringFromSelector(@selector(attributedText))]; + [coder encodeObject:self.text forKey:NSStringFromSelector(@selector(text))]; +} + +- (id)initWithCoder:(NSCoder *)coder { + self = [super initWithCoder:coder]; + if (!self) { + return nil; + } + + [self commonInit]; + + if ([coder containsValueForKey:NSStringFromSelector(@selector(enabledTextCheckingTypes))]) { + self.enabledTextCheckingTypes = [[coder decodeObjectForKey:NSStringFromSelector(@selector(enabledTextCheckingTypes))] unsignedLongLongValue]; + } + + if ([NSMutableParagraphStyle class]) { + if ([coder containsValueForKey:NSStringFromSelector(@selector(linkAttributes))]) { + self.linkAttributes = [coder decodeObjectForKey:NSStringFromSelector(@selector(linkAttributes))]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(activeLinkAttributes))]) { + self.activeLinkAttributes = [coder decodeObjectForKey:NSStringFromSelector(@selector(activeLinkAttributes))]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(inactiveLinkAttributes))]) { + self.inactiveLinkAttributes = [coder decodeObjectForKey:NSStringFromSelector(@selector(inactiveLinkAttributes))]; + } + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(links))]) { + NSArray *oldLinks = [coder decodeObjectForKey:NSStringFromSelector(@selector(links))]; + [self addLinksWithTextCheckingResults:oldLinks attributes:nil]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(linkModels))]) { + self.linkModels = [coder decodeObjectForKey:NSStringFromSelector(@selector(linkModels))]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(shadowRadius))]) { + self.shadowRadius = [[coder decodeObjectForKey:NSStringFromSelector(@selector(shadowRadius))] floatValue]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(highlightedShadowRadius))]) { + self.highlightedShadowRadius = [[coder decodeObjectForKey:NSStringFromSelector(@selector(highlightedShadowRadius))] floatValue]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(highlightedShadowOffset))]) { + self.highlightedShadowOffset = [coder decodeCGSizeForKey:NSStringFromSelector(@selector(highlightedShadowOffset))]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(highlightedShadowColor))]) { + self.highlightedShadowColor = [coder decodeObjectForKey:NSStringFromSelector(@selector(highlightedShadowColor))]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(kern))]) { + self.kern = [[coder decodeObjectForKey:NSStringFromSelector(@selector(kern))] floatValue]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(firstLineIndent))]) { + self.firstLineIndent = [[coder decodeObjectForKey:NSStringFromSelector(@selector(firstLineIndent))] floatValue]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(lineSpacing))]) { + self.lineSpacing = [[coder decodeObjectForKey:NSStringFromSelector(@selector(lineSpacing))] floatValue]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(minimumLineHeight))]) { + self.minimumLineHeight = [[coder decodeObjectForKey:NSStringFromSelector(@selector(minimumLineHeight))] floatValue]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(maximumLineHeight))]) { + self.maximumLineHeight = [[coder decodeObjectForKey:NSStringFromSelector(@selector(maximumLineHeight))] floatValue]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(lineHeightMultiple))]) { + self.lineHeightMultiple = [[coder decodeObjectForKey:NSStringFromSelector(@selector(lineHeightMultiple))] floatValue]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(textInsets))]) { + self.textInsets = [coder decodeUIEdgeInsetsForKey:NSStringFromSelector(@selector(textInsets))]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(verticalAlignment))]) { + self.verticalAlignment = [coder decodeIntegerForKey:NSStringFromSelector(@selector(verticalAlignment))]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(attributedTruncationToken))]) { + self.attributedTruncationToken = [coder decodeObjectForKey:NSStringFromSelector(@selector(attributedTruncationToken))]; + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(linkBackgroundEdgeInset))]) { + self.linkBackgroundEdgeInset = UIEdgeInsetsFromString([coder decodeObjectForKey:NSStringFromSelector(@selector(linkBackgroundEdgeInset))]); + } + + if ([coder containsValueForKey:NSStringFromSelector(@selector(attributedText))]) { + self.attributedText = [coder decodeObjectForKey:NSStringFromSelector(@selector(attributedText))]; + } else { + self.text = super.text; + } + + return self; +} + +@end + +#pragma mark - TTTAttributedLabelLink + +@implementation TTTAttributedLabelLink + +- (instancetype)initWithAttributes:(NSDictionary *)attributes + activeAttributes:(NSDictionary *)activeAttributes + inactiveAttributes:(NSDictionary *)inactiveAttributes + textCheckingResult:(NSTextCheckingResult *)result { + + if ((self = [super init])) { + _result = result; + _attributes = [attributes copy]; + _activeAttributes = [activeAttributes copy]; + _inactiveAttributes = [inactiveAttributes copy]; + } + + return self; +} + +- (instancetype)initWithAttributesFromLabel:(TTTAttributedLabel*)label + textCheckingResult:(NSTextCheckingResult *)result { + + return [self initWithAttributes:label.linkAttributes + activeAttributes:label.activeLinkAttributes + inactiveAttributes:label.inactiveLinkAttributes + textCheckingResult:result]; +} + +#pragma mark - Accessibility + +- (NSString *) accessibilityValue { + if ([_accessibilityValue length] == 0) { + switch (self.result.resultType) { + case NSTextCheckingTypeLink: + _accessibilityValue = self.result.URL.absoluteString; + break; + case NSTextCheckingTypePhoneNumber: + _accessibilityValue = self.result.phoneNumber; + break; + case NSTextCheckingTypeDate: + _accessibilityValue = [NSDateFormatter localizedStringFromDate:self.result.date + dateStyle:NSDateFormatterLongStyle + timeStyle:NSDateFormatterLongStyle]; + break; + default: + break; + } + } + + return _accessibilityValue; +} + +#pragma mark - NSCoding + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:self.result forKey:NSStringFromSelector(@selector(result))]; + [aCoder encodeObject:self.attributes forKey:NSStringFromSelector(@selector(attributes))]; + [aCoder encodeObject:self.activeAttributes forKey:NSStringFromSelector(@selector(activeAttributes))]; + [aCoder encodeObject:self.inactiveAttributes forKey:NSStringFromSelector(@selector(inactiveAttributes))]; + [aCoder encodeObject:self.accessibilityValue forKey:NSStringFromSelector(@selector(accessibilityValue))]; +} + +- (id)initWithCoder:(NSCoder *)aDecoder { + if ((self = [super init])) { + _result = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(result))]; + _attributes = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(attributes))]; + _activeAttributes = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(activeAttributes))]; + _inactiveAttributes = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(inactiveAttributes))]; + self.accessibilityValue = [aDecoder decodeObjectForKey:NSStringFromSelector(@selector(accessibilityValue))]; + } + + return self; +} + +@end + +#pragma mark - + +static inline CGColorRef CGColorRefFromColor(id color) { + return [color isKindOfClass:[UIColor class]] ? [color CGColor] : (__bridge CGColorRef)color; +} + +static inline CTFontRef CTFontRefFromUIFont(UIFont * font) { + CTFontRef ctfont = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, NULL); + return CFAutorelease(ctfont); +} + +static inline NSDictionary * convertNSAttributedStringAttributesToCTAttributes(NSDictionary *attributes) { + if (!attributes) return nil; + + NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionary]; + + NSDictionary *NSToCTAttributeNamesMap = @{ + NSFontAttributeName: (NSString *)kCTFontAttributeName, + NSBackgroundColorAttributeName: (NSString *)kTTTBackgroundFillColorAttributeName, + NSForegroundColorAttributeName: (NSString *)kCTForegroundColorAttributeName, + NSUnderlineColorAttributeName: (NSString *)kCTUnderlineColorAttributeName, + NSUnderlineStyleAttributeName: (NSString *)kCTUnderlineStyleAttributeName, + NSStrokeWidthAttributeName: (NSString *)kCTStrokeWidthAttributeName, + NSStrokeColorAttributeName: (NSString *)kCTStrokeWidthAttributeName, + NSKernAttributeName: (NSString *)kCTKernAttributeName, + NSLigatureAttributeName: (NSString *)kCTLigatureAttributeName + }; + + [attributes enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) { + key = [NSToCTAttributeNamesMap objectForKey:key] ? : key; + + if (![NSMutableParagraphStyle class]) { + if ([value isKindOfClass:[UIFont class]]) { + value = (__bridge id)CTFontRefFromUIFont(value); + } else if ([value isKindOfClass:[UIColor class]]) { + value = (__bridge id)((UIColor *)value).CGColor; + } + } + + [mutableAttributes setObject:value forKey:key]; + }]; + + return [NSDictionary dictionaryWithDictionary:mutableAttributes]; +} diff --git a/Pods/Target Support Files/AFNetworking/AFNetworking-dummy.m b/Pods/Target Support Files/AFNetworking/AFNetworking-dummy.m new file mode 100644 index 0000000..6a29cf8 --- /dev/null +++ b/Pods/Target Support Files/AFNetworking/AFNetworking-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_AFNetworking : NSObject +@end +@implementation PodsDummy_AFNetworking +@end diff --git a/Pods/Target Support Files/AFNetworking/AFNetworking-prefix.pch b/Pods/Target Support Files/AFNetworking/AFNetworking-prefix.pch new file mode 100644 index 0000000..e72247a --- /dev/null +++ b/Pods/Target Support Files/AFNetworking/AFNetworking-prefix.pch @@ -0,0 +1,23 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#ifndef TARGET_OS_IOS + #define TARGET_OS_IOS TARGET_OS_IPHONE +#endif + +#ifndef TARGET_OS_WATCH + #define TARGET_OS_WATCH 0 +#endif + +#ifndef TARGET_OS_TV + #define TARGET_OS_TV 0 +#endif diff --git a/Pods/Target Support Files/AFNetworking/AFNetworking-umbrella.h b/Pods/Target Support Files/AFNetworking/AFNetworking-umbrella.h new file mode 100644 index 0000000..67520b6 --- /dev/null +++ b/Pods/Target Support Files/AFNetworking/AFNetworking-umbrella.h @@ -0,0 +1,35 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "AFNetworking.h" +#import "AFHTTPSessionManager.h" +#import "AFURLSessionManager.h" +#import "AFCompatibilityMacros.h" +#import "AFNetworkReachabilityManager.h" +#import "AFSecurityPolicy.h" +#import "AFURLRequestSerialization.h" +#import "AFURLResponseSerialization.h" +#import "AFAutoPurgingImageCache.h" +#import "AFImageDownloader.h" +#import "AFNetworkActivityIndicatorManager.h" +#import "UIActivityIndicatorView+AFNetworking.h" +#import "UIButton+AFNetworking.h" +#import "UIImage+AFNetworking.h" +#import "UIImageView+AFNetworking.h" +#import "UIKit+AFNetworking.h" +#import "UIProgressView+AFNetworking.h" +#import "UIRefreshControl+AFNetworking.h" +#import "UIWebView+AFNetworking.h" + +FOUNDATION_EXPORT double AFNetworkingVersionNumber; +FOUNDATION_EXPORT const unsigned char AFNetworkingVersionString[]; + diff --git a/Pods/Target Support Files/AFNetworking/AFNetworking.modulemap b/Pods/Target Support Files/AFNetworking/AFNetworking.modulemap new file mode 100644 index 0000000..5892cd3 --- /dev/null +++ b/Pods/Target Support Files/AFNetworking/AFNetworking.modulemap @@ -0,0 +1,6 @@ +framework module AFNetworking { + umbrella header "AFNetworking-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/AFNetworking/AFNetworking.xcconfig b/Pods/Target Support Files/AFNetworking/AFNetworking.xcconfig new file mode 100644 index 0000000..5a114d8 --- /dev/null +++ b/Pods/Target Support Files/AFNetworking/AFNetworking.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = -framework "CoreGraphics" -framework "MobileCoreServices" -framework "Security" -framework "SystemConfiguration" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/AFNetworking +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/AFNetworking/Info.plist b/Pods/Target Support Files/AFNetworking/Info.plist new file mode 100644 index 0000000..42c9fae --- /dev/null +++ b/Pods/Target Support Files/AFNetworking/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 3.2.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/FMDB/FMDB-dummy.m b/Pods/Target Support Files/FMDB/FMDB-dummy.m new file mode 100644 index 0000000..20ea8f1 --- /dev/null +++ b/Pods/Target Support Files/FMDB/FMDB-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_FMDB : NSObject +@end +@implementation PodsDummy_FMDB +@end diff --git a/Pods/Target Support Files/FMDB/FMDB-prefix.pch b/Pods/Target Support Files/FMDB/FMDB-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/FMDB/FMDB-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/FMDB/FMDB-umbrella.h b/Pods/Target Support Files/FMDB/FMDB-umbrella.h new file mode 100644 index 0000000..2ad4707 --- /dev/null +++ b/Pods/Target Support Files/FMDB/FMDB-umbrella.h @@ -0,0 +1,22 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "FMDatabase.h" +#import "FMDatabaseAdditions.h" +#import "FMDatabasePool.h" +#import "FMDatabaseQueue.h" +#import "FMDB.h" +#import "FMResultSet.h" + +FOUNDATION_EXPORT double FMDBVersionNumber; +FOUNDATION_EXPORT const unsigned char FMDBVersionString[]; + diff --git a/Pods/Target Support Files/FMDB/FMDB.modulemap b/Pods/Target Support Files/FMDB/FMDB.modulemap new file mode 100644 index 0000000..c1747d5 --- /dev/null +++ b/Pods/Target Support Files/FMDB/FMDB.modulemap @@ -0,0 +1,6 @@ +framework module FMDB { + umbrella header "FMDB-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/FMDB/FMDB.xcconfig b/Pods/Target Support Files/FMDB/FMDB.xcconfig new file mode 100644 index 0000000..cd25d0b --- /dev/null +++ b/Pods/Target Support Files/FMDB/FMDB.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/FMDB +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = -l"sqlite3" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/FMDB +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/FMDB/Info.plist b/Pods/Target Support Files/FMDB/Info.plist new file mode 100644 index 0000000..b66e8c6 --- /dev/null +++ b/Pods/Target Support Files/FMDB/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 2.7.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/IQKeyboardManager/IQKeyboardManager-dummy.m b/Pods/Target Support Files/IQKeyboardManager/IQKeyboardManager-dummy.m new file mode 100644 index 0000000..1d8d5d2 --- /dev/null +++ b/Pods/Target Support Files/IQKeyboardManager/IQKeyboardManager-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_IQKeyboardManager : NSObject +@end +@implementation PodsDummy_IQKeyboardManager +@end diff --git a/Pods/Target Support Files/IQKeyboardManager/IQKeyboardManager-prefix.pch b/Pods/Target Support Files/IQKeyboardManager/IQKeyboardManager-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/IQKeyboardManager/IQKeyboardManager-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/IQKeyboardManager/IQKeyboardManager-umbrella.h b/Pods/Target Support Files/IQKeyboardManager/IQKeyboardManager-umbrella.h new file mode 100644 index 0000000..437943d --- /dev/null +++ b/Pods/Target Support Files/IQKeyboardManager/IQKeyboardManager-umbrella.h @@ -0,0 +1,29 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "IQKeyboardManager.h" +#import "IQKeyboardReturnKeyHandler.h" +#import "IQUIScrollView+Additions.h" +#import "IQUITextFieldView+Additions.h" +#import "IQUIView+Hierarchy.h" +#import "IQUIViewController+Additions.h" +#import "IQKeyboardManagerConstants.h" +#import "IQTextView.h" +#import "IQBarButtonItem.h" +#import "IQPreviousNextView.h" +#import "IQTitleBarButtonItem.h" +#import "IQToolbar.h" +#import "IQUIView+IQKeyboardToolbar.h" + +FOUNDATION_EXPORT double IQKeyboardManagerVersionNumber; +FOUNDATION_EXPORT const unsigned char IQKeyboardManagerVersionString[]; + diff --git a/Pods/Target Support Files/IQKeyboardManager/IQKeyboardManager.modulemap b/Pods/Target Support Files/IQKeyboardManager/IQKeyboardManager.modulemap new file mode 100644 index 0000000..027250d --- /dev/null +++ b/Pods/Target Support Files/IQKeyboardManager/IQKeyboardManager.modulemap @@ -0,0 +1,6 @@ +framework module IQKeyboardManager { + umbrella header "IQKeyboardManager-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/IQKeyboardManager/IQKeyboardManager.xcconfig b/Pods/Target Support Files/IQKeyboardManager/IQKeyboardManager.xcconfig new file mode 100644 index 0000000..f07614b --- /dev/null +++ b/Pods/Target Support Files/IQKeyboardManager/IQKeyboardManager.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/IQKeyboardManager +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = -framework "CoreGraphics" -framework "Foundation" -framework "QuartzCore" -framework "UIKit" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/IQKeyboardManager +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/IQKeyboardManager/Info.plist b/Pods/Target Support Files/IQKeyboardManager/Info.plist new file mode 100644 index 0000000..40211fa --- /dev/null +++ b/Pods/Target Support Files/IQKeyboardManager/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 6.1.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/JSONModel/Info.plist b/Pods/Target Support Files/JSONModel/Info.plist new file mode 100644 index 0000000..fcedd03 --- /dev/null +++ b/Pods/Target Support Files/JSONModel/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.7.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/JSONModel/JSONModel-dummy.m b/Pods/Target Support Files/JSONModel/JSONModel-dummy.m new file mode 100644 index 0000000..a968b12 --- /dev/null +++ b/Pods/Target Support Files/JSONModel/JSONModel-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_JSONModel : NSObject +@end +@implementation PodsDummy_JSONModel +@end diff --git a/Pods/Target Support Files/JSONModel/JSONModel-prefix.pch b/Pods/Target Support Files/JSONModel/JSONModel-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/JSONModel/JSONModel-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/JSONModel/JSONModel-umbrella.h b/Pods/Target Support Files/JSONModel/JSONModel-umbrella.h new file mode 100644 index 0000000..a6ea263 --- /dev/null +++ b/Pods/Target Support Files/JSONModel/JSONModel-umbrella.h @@ -0,0 +1,25 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "JSONModel.h" +#import "JSONModelClassProperty.h" +#import "JSONModelError.h" +#import "JSONModelLib.h" +#import "JSONAPI.h" +#import "JSONHTTPClient.h" +#import "JSONModel+networking.h" +#import "JSONKeyMapper.h" +#import "JSONValueTransformer.h" + +FOUNDATION_EXPORT double JSONModelVersionNumber; +FOUNDATION_EXPORT const unsigned char JSONModelVersionString[]; + diff --git a/Pods/Target Support Files/JSONModel/JSONModel.modulemap b/Pods/Target Support Files/JSONModel/JSONModel.modulemap new file mode 100644 index 0000000..ab6c3cb --- /dev/null +++ b/Pods/Target Support Files/JSONModel/JSONModel.modulemap @@ -0,0 +1,6 @@ +framework module JSONModel { + umbrella header "JSONModel-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/JSONModel/JSONModel.xcconfig b/Pods/Target Support Files/JSONModel/JSONModel.xcconfig new file mode 100644 index 0000000..b7c138f --- /dev/null +++ b/Pods/Target Support Files/JSONModel/JSONModel.xcconfig @@ -0,0 +1,8 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/JSONModel +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/JSONModel +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/LKDBHelper/Info.plist b/Pods/Target Support Files/LKDBHelper/Info.plist new file mode 100644 index 0000000..a482d50 --- /dev/null +++ b/Pods/Target Support Files/LKDBHelper/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 2.5.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/LKDBHelper/LKDBHelper-dummy.m b/Pods/Target Support Files/LKDBHelper/LKDBHelper-dummy.m new file mode 100644 index 0000000..89e4b0c --- /dev/null +++ b/Pods/Target Support Files/LKDBHelper/LKDBHelper-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_LKDBHelper : NSObject +@end +@implementation PodsDummy_LKDBHelper +@end diff --git a/Pods/Target Support Files/LKDBHelper/LKDBHelper-prefix.pch b/Pods/Target Support Files/LKDBHelper/LKDBHelper-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/LKDBHelper/LKDBHelper-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/LKDBHelper/LKDBHelper-umbrella.h b/Pods/Target Support Files/LKDBHelper/LKDBHelper-umbrella.h new file mode 100644 index 0000000..069f7b1 --- /dev/null +++ b/Pods/Target Support Files/LKDBHelper/LKDBHelper-umbrella.h @@ -0,0 +1,21 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "LKDB+Mapping.h" +#import "LKDBHelper.h" +#import "LKDBUtils.h" +#import "NSObject+LKDBHelper.h" +#import "NSObject+LKModel.h" + +FOUNDATION_EXPORT double LKDBHelperVersionNumber; +FOUNDATION_EXPORT const unsigned char LKDBHelperVersionString[]; + diff --git a/Pods/Target Support Files/LKDBHelper/LKDBHelper.modulemap b/Pods/Target Support Files/LKDBHelper/LKDBHelper.modulemap new file mode 100644 index 0000000..1d324db --- /dev/null +++ b/Pods/Target Support Files/LKDBHelper/LKDBHelper.modulemap @@ -0,0 +1,6 @@ +framework module LKDBHelper { + umbrella header "LKDBHelper-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/LKDBHelper/LKDBHelper.xcconfig b/Pods/Target Support Files/LKDBHelper/LKDBHelper.xcconfig new file mode 100644 index 0000000..69909e5 --- /dev/null +++ b/Pods/Target Support Files/LKDBHelper/LKDBHelper.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/LKDBHelper +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/FMDB" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/LKDBHelper +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/MBProgressHUD/Info.plist b/Pods/Target Support Files/MBProgressHUD/Info.plist new file mode 100644 index 0000000..68ac6e2 --- /dev/null +++ b/Pods/Target Support Files/MBProgressHUD/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.9.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/MBProgressHUD/MBProgressHUD-dummy.m b/Pods/Target Support Files/MBProgressHUD/MBProgressHUD-dummy.m new file mode 100644 index 0000000..67a74df --- /dev/null +++ b/Pods/Target Support Files/MBProgressHUD/MBProgressHUD-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_MBProgressHUD : NSObject +@end +@implementation PodsDummy_MBProgressHUD +@end diff --git a/Pods/Target Support Files/MBProgressHUD/MBProgressHUD-prefix.pch b/Pods/Target Support Files/MBProgressHUD/MBProgressHUD-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/MBProgressHUD/MBProgressHUD-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/MBProgressHUD/MBProgressHUD-umbrella.h b/Pods/Target Support Files/MBProgressHUD/MBProgressHUD-umbrella.h new file mode 100644 index 0000000..8522a01 --- /dev/null +++ b/Pods/Target Support Files/MBProgressHUD/MBProgressHUD-umbrella.h @@ -0,0 +1,17 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "MBProgressHUD.h" + +FOUNDATION_EXPORT double MBProgressHUDVersionNumber; +FOUNDATION_EXPORT const unsigned char MBProgressHUDVersionString[]; + diff --git a/Pods/Target Support Files/MBProgressHUD/MBProgressHUD.modulemap b/Pods/Target Support Files/MBProgressHUD/MBProgressHUD.modulemap new file mode 100644 index 0000000..dbb3f94 --- /dev/null +++ b/Pods/Target Support Files/MBProgressHUD/MBProgressHUD.modulemap @@ -0,0 +1,6 @@ +framework module MBProgressHUD { + umbrella header "MBProgressHUD-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/MBProgressHUD/MBProgressHUD.xcconfig b/Pods/Target Support Files/MBProgressHUD/MBProgressHUD.xcconfig new file mode 100644 index 0000000..36d19b8 --- /dev/null +++ b/Pods/Target Support Files/MBProgressHUD/MBProgressHUD.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/MBProgressHUD +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = -framework "CoreGraphics" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/MBProgressHUD +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/MJRefresh/Info.plist b/Pods/Target Support Files/MJRefresh/Info.plist new file mode 100644 index 0000000..fe40e00 --- /dev/null +++ b/Pods/Target Support Files/MJRefresh/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 3.1.15 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/MJRefresh/MJRefresh-dummy.m b/Pods/Target Support Files/MJRefresh/MJRefresh-dummy.m new file mode 100644 index 0000000..d43259d --- /dev/null +++ b/Pods/Target Support Files/MJRefresh/MJRefresh-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_MJRefresh : NSObject +@end +@implementation PodsDummy_MJRefresh +@end diff --git a/Pods/Target Support Files/MJRefresh/MJRefresh-prefix.pch b/Pods/Target Support Files/MJRefresh/MJRefresh-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/MJRefresh/MJRefresh-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/MJRefresh/MJRefresh-umbrella.h b/Pods/Target Support Files/MJRefresh/MJRefresh-umbrella.h new file mode 100644 index 0000000..509dcc9 --- /dev/null +++ b/Pods/Target Support Files/MJRefresh/MJRefresh-umbrella.h @@ -0,0 +1,36 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "MJRefreshAutoFooter.h" +#import "MJRefreshBackFooter.h" +#import "MJRefreshComponent.h" +#import "MJRefreshFooter.h" +#import "MJRefreshHeader.h" +#import "MJRefreshAutoGifFooter.h" +#import "MJRefreshAutoNormalFooter.h" +#import "MJRefreshAutoStateFooter.h" +#import "MJRefreshBackGifFooter.h" +#import "MJRefreshBackNormalFooter.h" +#import "MJRefreshBackStateFooter.h" +#import "MJRefreshGifHeader.h" +#import "MJRefreshNormalHeader.h" +#import "MJRefreshStateHeader.h" +#import "MJRefresh.h" +#import "MJRefreshConst.h" +#import "NSBundle+MJRefresh.h" +#import "UIScrollView+MJExtension.h" +#import "UIScrollView+MJRefresh.h" +#import "UIView+MJExtension.h" + +FOUNDATION_EXPORT double MJRefreshVersionNumber; +FOUNDATION_EXPORT const unsigned char MJRefreshVersionString[]; + diff --git a/Pods/Target Support Files/MJRefresh/MJRefresh.modulemap b/Pods/Target Support Files/MJRefresh/MJRefresh.modulemap new file mode 100644 index 0000000..ec3d85e --- /dev/null +++ b/Pods/Target Support Files/MJRefresh/MJRefresh.modulemap @@ -0,0 +1,6 @@ +framework module MJRefresh { + umbrella header "MJRefresh-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/MJRefresh/MJRefresh.xcconfig b/Pods/Target Support Files/MJRefresh/MJRefresh.xcconfig new file mode 100644 index 0000000..21fdc14 --- /dev/null +++ b/Pods/Target Support Files/MJRefresh/MJRefresh.xcconfig @@ -0,0 +1,8 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/MJRefresh +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/MJRefresh +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/Masonry/Info.plist b/Pods/Target Support Files/Masonry/Info.plist new file mode 100644 index 0000000..b35ab35 --- /dev/null +++ b/Pods/Target Support Files/Masonry/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Masonry/Masonry-dummy.m b/Pods/Target Support Files/Masonry/Masonry-dummy.m new file mode 100644 index 0000000..04001b1 --- /dev/null +++ b/Pods/Target Support Files/Masonry/Masonry-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Masonry : NSObject +@end +@implementation PodsDummy_Masonry +@end diff --git a/Pods/Target Support Files/Masonry/Masonry-prefix.pch b/Pods/Target Support Files/Masonry/Masonry-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/Masonry/Masonry-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/Masonry/Masonry-umbrella.h b/Pods/Target Support Files/Masonry/Masonry-umbrella.h new file mode 100644 index 0000000..3fe9c4c --- /dev/null +++ b/Pods/Target Support Files/Masonry/Masonry-umbrella.h @@ -0,0 +1,31 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "MASCompositeConstraint.h" +#import "MASConstraint+Private.h" +#import "MASConstraint.h" +#import "MASConstraintMaker.h" +#import "MASLayoutConstraint.h" +#import "Masonry.h" +#import "MASUtilities.h" +#import "MASViewAttribute.h" +#import "MASViewConstraint.h" +#import "NSArray+MASAdditions.h" +#import "NSArray+MASShorthandAdditions.h" +#import "NSLayoutConstraint+MASDebugAdditions.h" +#import "View+MASAdditions.h" +#import "View+MASShorthandAdditions.h" +#import "ViewController+MASAdditions.h" + +FOUNDATION_EXPORT double MasonryVersionNumber; +FOUNDATION_EXPORT const unsigned char MasonryVersionString[]; + diff --git a/Pods/Target Support Files/Masonry/Masonry.modulemap b/Pods/Target Support Files/Masonry/Masonry.modulemap new file mode 100644 index 0000000..06ec492 --- /dev/null +++ b/Pods/Target Support Files/Masonry/Masonry.modulemap @@ -0,0 +1,6 @@ +framework module Masonry { + umbrella header "Masonry-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Masonry/Masonry.xcconfig b/Pods/Target Support Files/Masonry/Masonry.xcconfig new file mode 100644 index 0000000..a7b2cee --- /dev/null +++ b/Pods/Target Support Files/Masonry/Masonry.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Masonry +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = -framework "Foundation" -framework "UIKit" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Masonry +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/NJKWebViewProgress/Info.plist b/Pods/Target Support Files/NJKWebViewProgress/Info.plist new file mode 100644 index 0000000..421cf1d --- /dev/null +++ b/Pods/Target Support Files/NJKWebViewProgress/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.2.3 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/NJKWebViewProgress/NJKWebViewProgress-dummy.m b/Pods/Target Support Files/NJKWebViewProgress/NJKWebViewProgress-dummy.m new file mode 100644 index 0000000..d81e97c --- /dev/null +++ b/Pods/Target Support Files/NJKWebViewProgress/NJKWebViewProgress-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_NJKWebViewProgress : NSObject +@end +@implementation PodsDummy_NJKWebViewProgress +@end diff --git a/Pods/Target Support Files/NJKWebViewProgress/NJKWebViewProgress-prefix.pch b/Pods/Target Support Files/NJKWebViewProgress/NJKWebViewProgress-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/NJKWebViewProgress/NJKWebViewProgress-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/NJKWebViewProgress/NJKWebViewProgress-umbrella.h b/Pods/Target Support Files/NJKWebViewProgress/NJKWebViewProgress-umbrella.h new file mode 100644 index 0000000..c603fc8 --- /dev/null +++ b/Pods/Target Support Files/NJKWebViewProgress/NJKWebViewProgress-umbrella.h @@ -0,0 +1,18 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "NJKWebViewProgress.h" +#import "NJKWebViewProgressView.h" + +FOUNDATION_EXPORT double NJKWebViewProgressVersionNumber; +FOUNDATION_EXPORT const unsigned char NJKWebViewProgressVersionString[]; + diff --git a/Pods/Target Support Files/NJKWebViewProgress/NJKWebViewProgress.modulemap b/Pods/Target Support Files/NJKWebViewProgress/NJKWebViewProgress.modulemap new file mode 100644 index 0000000..fd5ad48 --- /dev/null +++ b/Pods/Target Support Files/NJKWebViewProgress/NJKWebViewProgress.modulemap @@ -0,0 +1,6 @@ +framework module NJKWebViewProgress { + umbrella header "NJKWebViewProgress-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/NJKWebViewProgress/NJKWebViewProgress.xcconfig b/Pods/Target Support Files/NJKWebViewProgress/NJKWebViewProgress.xcconfig new file mode 100644 index 0000000..e76879e --- /dev/null +++ b/Pods/Target Support Files/NJKWebViewProgress/NJKWebViewProgress.xcconfig @@ -0,0 +1,8 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/NJKWebViewProgress +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/NJKWebViewProgress +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/Pods-GIGA/Info.plist b/Pods/Target Support Files/Pods-GIGA/Info.plist new file mode 100644 index 0000000..2243fe6 --- /dev/null +++ b/Pods/Target Support Files/Pods-GIGA/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-acknowledgements.markdown b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-acknowledgements.markdown new file mode 100644 index 0000000..0d2d219 --- /dev/null +++ b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-acknowledgements.markdown @@ -0,0 +1,369 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## AFNetworking + +Copyright (c) 2011-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. + + +## FMDB + +If you are using FMDB in your project, I'd love to hear about it. Let Gus know +by sending an email to gus@flyingmeat.com. + +And if you happen to come across either Gus Mueller or Rob Ryan in a bar, you +might consider purchasing a drink of their choosing if FMDB has been useful to +you. + +Finally, and shortly, this is the MIT License. + +Copyright (c) 2008-2014 Flying Meat Inc. + +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. + +## IQKeyboardManager + +MIT License + +Copyright (c) 2013-2017 Iftekhar Qurashi + +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. + + +## JCore + +Copyright jpush.cn + +## JPush + +Copyright jiguang.cn + +## JSONModel + +Copyright (c) 2012-2016 Marin Todorov and JSONModel contributors + +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. + + +## LKDBHelper + +Copyright (c) 2012 Jianghuai Li (https://github.com/li6185377) + +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. + +## MBProgressHUD + +Copyright (c) 2009-2015 Matej Bukovinski + +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. + +## MJRefresh + +Copyright (c) 2013-2015 MJRefresh (https://github.com/CoderMJLee/MJRefresh) + +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. + + +## Masonry + +Copyright (c) 2011-2012 Masonry Team - https://github.com/Masonry + +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. + +## NJKWebViewProgress + +The MIT License (MIT) + +Copyright (c) 2013 Satoshi Asano + +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. + +## SDWebImage + +Copyright (c) 2009-2017 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. + + + +## SocketRocket + + + Copyright 2012 Square Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + +## TTTAttributedLabel + +Copyright (c) 2011 Mattt Thompson (http://mattt.me/) + +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. + + +## Toast + +Copyright (c) 2011-2017 Charles Scalesse. + +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. + + +## UITableView+FDTemplateLayoutCell + +The MIT License (MIT) + +Copyright (c) 2015 + +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. + + + +## WechatOpenSDK + +Copyright 2018 tencent.com. All rights reserved. + + +## YTKKeyValueStore + +Copyright (c) 2012-2014 YTKKeyValueStore https://github.com/yuantiku + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Generated by CocoaPods - https://cocoapods.org diff --git a/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-acknowledgements.plist b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-acknowledgements.plist new file mode 100644 index 0000000..0a65ae8 --- /dev/null +++ b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-acknowledgements.plist @@ -0,0 +1,503 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2011-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. + + License + MIT + Title + AFNetworking + Type + PSGroupSpecifier + + + FooterText + If you are using FMDB in your project, I'd love to hear about it. Let Gus know +by sending an email to gus@flyingmeat.com. + +And if you happen to come across either Gus Mueller or Rob Ryan in a bar, you +might consider purchasing a drink of their choosing if FMDB has been useful to +you. + +Finally, and shortly, this is the MIT License. + +Copyright (c) 2008-2014 Flying Meat Inc. + +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 + FMDB + Type + PSGroupSpecifier + + + FooterText + MIT License + +Copyright (c) 2013-2017 Iftekhar Qurashi + +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 + IQKeyboardManager + Type + PSGroupSpecifier + + + FooterText + Copyright jpush.cn + License + Copyright + Title + JCore + Type + PSGroupSpecifier + + + FooterText + Copyright jiguang.cn + License + Copyright + Title + JPush + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2012-2016 Marin Todorov and JSONModel contributors + +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 + JSONModel + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2012 Jianghuai Li (https://github.com/li6185377) + +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 + LKDBHelper + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2009-2015 Matej Bukovinski + +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 + MBProgressHUD + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2013-2015 MJRefresh (https://github.com/CoderMJLee/MJRefresh) + +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 + MJRefresh + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2011-2012 Masonry Team - https://github.com/Masonry + +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 + Masonry + Type + PSGroupSpecifier + + + FooterText + The MIT License (MIT) + +Copyright (c) 2013 Satoshi Asano + +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 + NJKWebViewProgress + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2009-2017 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 + + Copyright 2012 Square Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + + License + Apache License, Version 2.0 + Title + SocketRocket + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2011 Mattt Thompson (http://mattt.me/) + +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 + TTTAttributedLabel + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2011-2017 Charles Scalesse. + +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 + Toast + Type + PSGroupSpecifier + + + FooterText + The MIT License (MIT) + +Copyright (c) 2015 + +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 + UITableView+FDTemplateLayoutCell + Type + PSGroupSpecifier + + + FooterText + Copyright 2018 tencent.com. All rights reserved. + + License + Copyright + Title + WechatOpenSDK + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2012-2014 YTKKeyValueStore https://github.com/yuantiku + +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 + YTKKeyValueStore + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-dummy.m b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-dummy.m new file mode 100644 index 0000000..ab71386 --- /dev/null +++ b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_GIGA : NSObject +@end +@implementation PodsDummy_Pods_GIGA +@end diff --git a/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-frameworks.sh b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-frameworks.sh new file mode 100755 index 0000000..ab9240e --- /dev/null +++ b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-frameworks.sh @@ -0,0 +1,181 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then + # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy + # frameworks to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" + +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + +# This protects against multiple targets copying the same framework dependency at the same time. The solution +# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html +RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") + +# Copies and strips a vendored framework +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + # Use filter instead of exclude so missing patterns don't throw errors. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} + +# Copies and strips a vendored dSYM +install_dsym() { + local source="$1" + if [ -r "$source" ]; then + # Copy the dSYM into a the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .framework.dSYM "$source")" + binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then + strip_invalid_archs "$binary" + fi + + if [[ $STRIP_BINARY_RETVAL == 1 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" + fi + fi +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identitiy + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" + + if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + code_sign_cmd="$code_sign_cmd &" + fi + echo "$code_sign_cmd" + eval "$code_sign_cmd" + fi +} + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + # Get architectures for current target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + STRIP_BINARY_RETVAL=0 + return + fi + stripped="" + for arch in $binary_archs; do + if ! [[ "${ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" || exit 1 + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi + STRIP_BINARY_RETVAL=1 +} + + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework" + install_framework "${BUILT_PRODUCTS_DIR}/FMDB/FMDB.framework" + install_framework "${BUILT_PRODUCTS_DIR}/IQKeyboardManager/IQKeyboardManager.framework" + install_framework "${BUILT_PRODUCTS_DIR}/JSONModel/JSONModel.framework" + install_framework "${BUILT_PRODUCTS_DIR}/LKDBHelper/LKDBHelper.framework" + install_framework "${BUILT_PRODUCTS_DIR}/MBProgressHUD/MBProgressHUD.framework" + install_framework "${BUILT_PRODUCTS_DIR}/MJRefresh/MJRefresh.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework" + install_framework "${BUILT_PRODUCTS_DIR}/NJKWebViewProgress/NJKWebViewProgress.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SocketRocket/SocketRocket.framework" + install_framework "${BUILT_PRODUCTS_DIR}/TTTAttributedLabel/TTTAttributedLabel.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Toast/Toast.framework" + install_framework "${BUILT_PRODUCTS_DIR}/UITableView+FDTemplateLayoutCell/UITableView_FDTemplateLayoutCell.framework" + install_framework "${BUILT_PRODUCTS_DIR}/YTKKeyValueStore/YTKKeyValueStore.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/AFNetworking/AFNetworking.framework" + install_framework "${BUILT_PRODUCTS_DIR}/FMDB/FMDB.framework" + install_framework "${BUILT_PRODUCTS_DIR}/IQKeyboardManager/IQKeyboardManager.framework" + install_framework "${BUILT_PRODUCTS_DIR}/JSONModel/JSONModel.framework" + install_framework "${BUILT_PRODUCTS_DIR}/LKDBHelper/LKDBHelper.framework" + install_framework "${BUILT_PRODUCTS_DIR}/MBProgressHUD/MBProgressHUD.framework" + install_framework "${BUILT_PRODUCTS_DIR}/MJRefresh/MJRefresh.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Masonry/Masonry.framework" + install_framework "${BUILT_PRODUCTS_DIR}/NJKWebViewProgress/NJKWebViewProgress.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SDWebImage/SDWebImage.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SocketRocket/SocketRocket.framework" + install_framework "${BUILT_PRODUCTS_DIR}/TTTAttributedLabel/TTTAttributedLabel.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Toast/Toast.framework" + install_framework "${BUILT_PRODUCTS_DIR}/UITableView+FDTemplateLayoutCell/UITableView_FDTemplateLayoutCell.framework" + install_framework "${BUILT_PRODUCTS_DIR}/YTKKeyValueStore/YTKKeyValueStore.framework" +fi +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-resources.sh b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-resources.sh new file mode 100755 index 0000000..fe3f9c7 --- /dev/null +++ b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-resources.sh @@ -0,0 +1,118 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +if [ -z ${UNLOCALIZED_RESOURCES_FOLDER_PATH+x} ]; then + # If UNLOCALIZED_RESOURCES_FOLDER_PATH is not set, then there's nowhere for us to copy + # resources to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +# This protects against multiple targets copying the same framework dependency at the same time. The solution +# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html +RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") + +case "${TARGETED_DEVICE_FAMILY:-}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + 3) + TARGET_DEVICE_ARGS="--target-device tv" + ;; + 4) + TARGET_DEVICE_ARGS="--target-device watch" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; +esac + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" || true + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" || true + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" || true + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" || true + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" || true + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" || true + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "${XCASSET_FILES:-}" ] +then + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "${PODS_ROOT}*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + if [ -z ${ASSETCATALOG_COMPILER_APPICON_NAME+x} ]; then + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + else + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" --app-icon "${ASSETCATALOG_COMPILER_APPICON_NAME}" --output-partial-info-plist "${TARGET_BUILD_DIR}/assetcatalog_generated_info.plist" + fi +fi diff --git a/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-umbrella.h b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-umbrella.h new file mode 100644 index 0000000..2236770 --- /dev/null +++ b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_GIGAVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_GIGAVersionString[]; + diff --git a/Pods/Target Support Files/Pods-GIGA/Pods-GIGA.debug.xcconfig b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA.debug.xcconfig new file mode 100644 index 0000000..7486bb7 --- /dev/null +++ b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA.debug.xcconfig @@ -0,0 +1,11 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking" "${PODS_CONFIGURATION_BUILD_DIR}/FMDB" "${PODS_CONFIGURATION_BUILD_DIR}/IQKeyboardManager" "${PODS_CONFIGURATION_BUILD_DIR}/JSONModel" "${PODS_CONFIGURATION_BUILD_DIR}/LKDBHelper" "${PODS_CONFIGURATION_BUILD_DIR}/MBProgressHUD" "${PODS_CONFIGURATION_BUILD_DIR}/MJRefresh" "${PODS_CONFIGURATION_BUILD_DIR}/Masonry" "${PODS_CONFIGURATION_BUILD_DIR}/NJKWebViewProgress" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage" "${PODS_CONFIGURATION_BUILD_DIR}/SocketRocket" "${PODS_CONFIGURATION_BUILD_DIR}/TTTAttributedLabel" "${PODS_CONFIGURATION_BUILD_DIR}/Toast" "${PODS_CONFIGURATION_BUILD_DIR}/UITableView+FDTemplateLayoutCell" "${PODS_CONFIGURATION_BUILD_DIR}/YTKKeyValueStore" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/JPush" "${PODS_ROOT}/Headers/Public/WechatOpenSDK" +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +LIBRARY_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/JCore" "${PODS_ROOT}/JPush" "${PODS_ROOT}/WechatOpenSDK/WechatSDK1.8.2" +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking/AFNetworking.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FMDB/FMDB.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/IQKeyboardManager/IQKeyboardManager.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/JSONModel/JSONModel.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/LKDBHelper/LKDBHelper.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/MBProgressHUD/MBProgressHUD.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/MJRefresh/MJRefresh.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Masonry/Masonry.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/NJKWebViewProgress/NJKWebViewProgress.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage/SDWebImage.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/SocketRocket/SocketRocket.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/TTTAttributedLabel/TTTAttributedLabel.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Toast/Toast.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/UITableView+FDTemplateLayoutCell/UITableView_FDTemplateLayoutCell.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/YTKKeyValueStore/YTKKeyValueStore.framework/Headers" -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/JPush" -isystem "${PODS_ROOT}/Headers/Public/WechatOpenSDK" +OTHER_LDFLAGS = $(inherited) -ObjC -l"WeChatSDK" -l"c++" -l"jcore-ios-1.2.2" -l"jpush-ios-3.1.0" -l"resolv" -l"sqlite3.0" -l"z" -framework "AFNetworking" -framework "CFNetwork" -framework "CoreFoundation" -framework "CoreGraphics" -framework "CoreTelephony" -framework "FMDB" -framework "Foundation" -framework "IQKeyboardManager" -framework "JSONModel" -framework "LKDBHelper" -framework "MBProgressHUD" -framework "MJRefresh" -framework "Masonry" -framework "NJKWebViewProgress" -framework "SDWebImage" -framework "Security" -framework "SocketRocket" -framework "SystemConfiguration" -framework "TTTAttributedLabel" -framework "Toast" -framework "UIKit" -framework "UITableView_FDTemplateLayoutCell" -framework "YTKKeyValueStore" -weak_framework "UserNotifications" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods diff --git a/Pods/Target Support Files/Pods-GIGA/Pods-GIGA.modulemap b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA.modulemap new file mode 100644 index 0000000..16c5bf0 --- /dev/null +++ b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA.modulemap @@ -0,0 +1,6 @@ +framework module Pods_GIGA { + umbrella header "Pods-GIGA-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Pods-GIGA/Pods-GIGA.release.xcconfig b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA.release.xcconfig new file mode 100644 index 0000000..7486bb7 --- /dev/null +++ b/Pods/Target Support Files/Pods-GIGA/Pods-GIGA.release.xcconfig @@ -0,0 +1,11 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking" "${PODS_CONFIGURATION_BUILD_DIR}/FMDB" "${PODS_CONFIGURATION_BUILD_DIR}/IQKeyboardManager" "${PODS_CONFIGURATION_BUILD_DIR}/JSONModel" "${PODS_CONFIGURATION_BUILD_DIR}/LKDBHelper" "${PODS_CONFIGURATION_BUILD_DIR}/MBProgressHUD" "${PODS_CONFIGURATION_BUILD_DIR}/MJRefresh" "${PODS_CONFIGURATION_BUILD_DIR}/Masonry" "${PODS_CONFIGURATION_BUILD_DIR}/NJKWebViewProgress" "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage" "${PODS_CONFIGURATION_BUILD_DIR}/SocketRocket" "${PODS_CONFIGURATION_BUILD_DIR}/TTTAttributedLabel" "${PODS_CONFIGURATION_BUILD_DIR}/Toast" "${PODS_CONFIGURATION_BUILD_DIR}/UITableView+FDTemplateLayoutCell" "${PODS_CONFIGURATION_BUILD_DIR}/YTKKeyValueStore" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/Headers/Public" "${PODS_ROOT}/Headers/Public/JPush" "${PODS_ROOT}/Headers/Public/WechatOpenSDK" +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +LIBRARY_SEARCH_PATHS = $(inherited) "${PODS_ROOT}/JCore" "${PODS_ROOT}/JPush" "${PODS_ROOT}/WechatOpenSDK/WechatSDK1.8.2" +OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/AFNetworking/AFNetworking.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/FMDB/FMDB.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/IQKeyboardManager/IQKeyboardManager.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/JSONModel/JSONModel.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/LKDBHelper/LKDBHelper.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/MBProgressHUD/MBProgressHUD.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/MJRefresh/MJRefresh.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Masonry/Masonry.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/NJKWebViewProgress/NJKWebViewProgress.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage/SDWebImage.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/SocketRocket/SocketRocket.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/TTTAttributedLabel/TTTAttributedLabel.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/Toast/Toast.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/UITableView+FDTemplateLayoutCell/UITableView_FDTemplateLayoutCell.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/YTKKeyValueStore/YTKKeyValueStore.framework/Headers" -isystem "${PODS_ROOT}/Headers/Public" -isystem "${PODS_ROOT}/Headers/Public/JPush" -isystem "${PODS_ROOT}/Headers/Public/WechatOpenSDK" +OTHER_LDFLAGS = $(inherited) -ObjC -l"WeChatSDK" -l"c++" -l"jcore-ios-1.2.2" -l"jpush-ios-3.1.0" -l"resolv" -l"sqlite3.0" -l"z" -framework "AFNetworking" -framework "CFNetwork" -framework "CoreFoundation" -framework "CoreGraphics" -framework "CoreTelephony" -framework "FMDB" -framework "Foundation" -framework "IQKeyboardManager" -framework "JSONModel" -framework "LKDBHelper" -framework "MBProgressHUD" -framework "MJRefresh" -framework "Masonry" -framework "NJKWebViewProgress" -framework "SDWebImage" -framework "Security" -framework "SocketRocket" -framework "SystemConfiguration" -framework "TTTAttributedLabel" -framework "Toast" -framework "UIKit" -framework "UITableView_FDTemplateLayoutCell" -framework "YTKKeyValueStore" -weak_framework "UserNotifications" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods diff --git a/Pods/Target Support Files/SDWebImage/Info.plist b/Pods/Target Support Files/SDWebImage/Info.plist new file mode 100644 index 0000000..b5cadae --- /dev/null +++ b/Pods/Target Support Files/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 + 4.4.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/SDWebImage/SDWebImage-dummy.m b/Pods/Target Support Files/SDWebImage/SDWebImage-dummy.m new file mode 100644 index 0000000..86d2b5f --- /dev/null +++ b/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/Pods/Target Support Files/SDWebImage/SDWebImage-prefix.pch b/Pods/Target Support Files/SDWebImage/SDWebImage-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/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/Pods/Target Support Files/SDWebImage/SDWebImage-umbrella.h b/Pods/Target Support Files/SDWebImage/SDWebImage-umbrella.h new file mode 100644 index 0000000..9118787 --- /dev/null +++ b/Pods/Target Support Files/SDWebImage/SDWebImage-umbrella.h @@ -0,0 +1,43 @@ +#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+WebCache.h" +#import "SDAnimatedImageRep.h" +#import "SDImageCache.h" +#import "SDImageCacheConfig.h" +#import "SDWebImageCoder.h" +#import "SDWebImageCoderHelper.h" +#import "SDWebImageCodersManager.h" +#import "SDWebImageCompat.h" +#import "SDWebImageDownloader.h" +#import "SDWebImageDownloaderOperation.h" +#import "SDWebImageFrame.h" +#import "SDWebImageGIFCoder.h" +#import "SDWebImageImageIOCoder.h" +#import "SDWebImageManager.h" +#import "SDWebImageOperation.h" +#import "SDWebImagePrefetcher.h" +#import "SDWebImageTransition.h" +#import "UIButton+WebCache.h" +#import "UIImage+ForceDecode.h" +#import "UIImage+GIF.h" +#import "UIImage+MultiFormat.h" +#import "UIImageView+HighlightedWebCache.h" +#import "UIImageView+WebCache.h" +#import "UIView+WebCache.h" +#import "UIView+WebCacheOperation.h" + +FOUNDATION_EXPORT double SDWebImageVersionNumber; +FOUNDATION_EXPORT const unsigned char SDWebImageVersionString[]; + diff --git a/Pods/Target Support Files/SDWebImage/SDWebImage.modulemap b/Pods/Target Support Files/SDWebImage/SDWebImage.modulemap new file mode 100644 index 0000000..91545be --- /dev/null +++ b/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/Pods/Target Support Files/SDWebImage/SDWebImage.xcconfig b/Pods/Target Support Files/SDWebImage/SDWebImage.xcconfig new file mode 100644 index 0000000..0692010 --- /dev/null +++ b/Pods/Target Support Files/SDWebImage/SDWebImage.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SDWebImage +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = -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 diff --git a/Pods/Target Support Files/SocketRocket/Info.plist b/Pods/Target Support Files/SocketRocket/Info.plist new file mode 100644 index 0000000..1c2e79e --- /dev/null +++ b/Pods/Target Support Files/SocketRocket/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.5.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/SocketRocket/SocketRocket-dummy.m b/Pods/Target Support Files/SocketRocket/SocketRocket-dummy.m new file mode 100644 index 0000000..1e9d2c9 --- /dev/null +++ b/Pods/Target Support Files/SocketRocket/SocketRocket-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_SocketRocket : NSObject +@end +@implementation PodsDummy_SocketRocket +@end diff --git a/Pods/Target Support Files/SocketRocket/SocketRocket-prefix.pch b/Pods/Target Support Files/SocketRocket/SocketRocket-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/SocketRocket/SocketRocket-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/SocketRocket/SocketRocket-umbrella.h b/Pods/Target Support Files/SocketRocket/SocketRocket-umbrella.h new file mode 100644 index 0000000..a819b2c --- /dev/null +++ b/Pods/Target Support Files/SocketRocket/SocketRocket-umbrella.h @@ -0,0 +1,18 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "SocketRocket.h" +#import "SRWebSocket.h" + +FOUNDATION_EXPORT double SocketRocketVersionNumber; +FOUNDATION_EXPORT const unsigned char SocketRocketVersionString[]; + diff --git a/Pods/Target Support Files/SocketRocket/SocketRocket.modulemap b/Pods/Target Support Files/SocketRocket/SocketRocket.modulemap new file mode 100644 index 0000000..52acc5d --- /dev/null +++ b/Pods/Target Support Files/SocketRocket/SocketRocket.modulemap @@ -0,0 +1,6 @@ +framework module SocketRocket { + umbrella header "SocketRocket-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/SocketRocket/SocketRocket.xcconfig b/Pods/Target Support Files/SocketRocket/SocketRocket.xcconfig new file mode 100644 index 0000000..1a4e4b2 --- /dev/null +++ b/Pods/Target Support Files/SocketRocket/SocketRocket.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SocketRocket +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = -l"icucore" -framework "CFNetwork" -framework "Security" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/SocketRocket +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/TTTAttributedLabel/Info.plist b/Pods/Target Support Files/TTTAttributedLabel/Info.plist new file mode 100644 index 0000000..0a12077 --- /dev/null +++ b/Pods/Target Support Files/TTTAttributedLabel/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 2.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/TTTAttributedLabel/TTTAttributedLabel-dummy.m b/Pods/Target Support Files/TTTAttributedLabel/TTTAttributedLabel-dummy.m new file mode 100644 index 0000000..7e82a99 --- /dev/null +++ b/Pods/Target Support Files/TTTAttributedLabel/TTTAttributedLabel-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_TTTAttributedLabel : NSObject +@end +@implementation PodsDummy_TTTAttributedLabel +@end diff --git a/Pods/Target Support Files/TTTAttributedLabel/TTTAttributedLabel-prefix.pch b/Pods/Target Support Files/TTTAttributedLabel/TTTAttributedLabel-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/TTTAttributedLabel/TTTAttributedLabel-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/TTTAttributedLabel/TTTAttributedLabel-umbrella.h b/Pods/Target Support Files/TTTAttributedLabel/TTTAttributedLabel-umbrella.h new file mode 100644 index 0000000..2e82bcd --- /dev/null +++ b/Pods/Target Support Files/TTTAttributedLabel/TTTAttributedLabel-umbrella.h @@ -0,0 +1,17 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "TTTAttributedLabel.h" + +FOUNDATION_EXPORT double TTTAttributedLabelVersionNumber; +FOUNDATION_EXPORT const unsigned char TTTAttributedLabelVersionString[]; + diff --git a/Pods/Target Support Files/TTTAttributedLabel/TTTAttributedLabel.modulemap b/Pods/Target Support Files/TTTAttributedLabel/TTTAttributedLabel.modulemap new file mode 100644 index 0000000..3d95b47 --- /dev/null +++ b/Pods/Target Support Files/TTTAttributedLabel/TTTAttributedLabel.modulemap @@ -0,0 +1,6 @@ +framework module TTTAttributedLabel { + umbrella header "TTTAttributedLabel-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/TTTAttributedLabel/TTTAttributedLabel.xcconfig b/Pods/Target Support Files/TTTAttributedLabel/TTTAttributedLabel.xcconfig new file mode 100644 index 0000000..5022119 --- /dev/null +++ b/Pods/Target Support Files/TTTAttributedLabel/TTTAttributedLabel.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/TTTAttributedLabel +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = -framework "CoreGraphics" -framework "CoreText" -framework "QuartzCore" -framework "UIKit" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/TTTAttributedLabel +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/Toast/Info.plist b/Pods/Target Support Files/Toast/Info.plist new file mode 100644 index 0000000..3424ca6 --- /dev/null +++ b/Pods/Target Support Files/Toast/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 4.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Toast/Toast-dummy.m b/Pods/Target Support Files/Toast/Toast-dummy.m new file mode 100644 index 0000000..4c1e812 --- /dev/null +++ b/Pods/Target Support Files/Toast/Toast-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Toast : NSObject +@end +@implementation PodsDummy_Toast +@end diff --git a/Pods/Target Support Files/Toast/Toast-prefix.pch b/Pods/Target Support Files/Toast/Toast-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/Toast/Toast-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/Toast/Toast-umbrella.h b/Pods/Target Support Files/Toast/Toast-umbrella.h new file mode 100644 index 0000000..8f6876d --- /dev/null +++ b/Pods/Target Support Files/Toast/Toast-umbrella.h @@ -0,0 +1,18 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "UIView+Toast.h" +#import "Toast.h" + +FOUNDATION_EXPORT double ToastVersionNumber; +FOUNDATION_EXPORT const unsigned char ToastVersionString[]; + diff --git a/Pods/Target Support Files/Toast/Toast.modulemap b/Pods/Target Support Files/Toast/Toast.modulemap new file mode 100644 index 0000000..da68e27 --- /dev/null +++ b/Pods/Target Support Files/Toast/Toast.modulemap @@ -0,0 +1,6 @@ +framework module Toast { + umbrella header "Toast-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Toast/Toast.xcconfig b/Pods/Target Support Files/Toast/Toast.xcconfig new file mode 100644 index 0000000..83651bc --- /dev/null +++ b/Pods/Target Support Files/Toast/Toast.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Toast +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_LDFLAGS = -framework "QuartzCore" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Toast +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/Info.plist b/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/Info.plist new file mode 100644 index 0000000..2f66809 --- /dev/null +++ b/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.6.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell-dummy.m b/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell-dummy.m new file mode 100644 index 0000000..fa66741 --- /dev/null +++ b/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_UITableView_FDTemplateLayoutCell : NSObject +@end +@implementation PodsDummy_UITableView_FDTemplateLayoutCell +@end diff --git a/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell-prefix.pch b/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell-umbrella.h b/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell-umbrella.h new file mode 100644 index 0000000..b999be9 --- /dev/null +++ b/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell-umbrella.h @@ -0,0 +1,20 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "UITableView+FDIndexPathHeightCache.h" +#import "UITableView+FDKeyedHeightCache.h" +#import "UITableView+FDTemplateLayoutCell.h" +#import "UITableView+FDTemplateLayoutCellDebug.h" + +FOUNDATION_EXPORT double UITableView_FDTemplateLayoutCellVersionNumber; +FOUNDATION_EXPORT const unsigned char UITableView_FDTemplateLayoutCellVersionString[]; + diff --git a/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell.modulemap b/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell.modulemap new file mode 100644 index 0000000..528b5f8 --- /dev/null +++ b/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell.modulemap @@ -0,0 +1,6 @@ +framework module UITableView_FDTemplateLayoutCell { + umbrella header "UITableView+FDTemplateLayoutCell-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell.xcconfig b/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell.xcconfig new file mode 100644 index 0000000..85d59c3 --- /dev/null +++ b/Pods/Target Support Files/UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell.xcconfig @@ -0,0 +1,8 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/UITableView+FDTemplateLayoutCell +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/UITableView+FDTemplateLayoutCell +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/YTKKeyValueStore/Info.plist b/Pods/Target Support Files/YTKKeyValueStore/Info.plist new file mode 100644 index 0000000..7c241fa --- /dev/null +++ b/Pods/Target Support Files/YTKKeyValueStore/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.1.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/YTKKeyValueStore/YTKKeyValueStore-dummy.m b/Pods/Target Support Files/YTKKeyValueStore/YTKKeyValueStore-dummy.m new file mode 100644 index 0000000..d4d529d --- /dev/null +++ b/Pods/Target Support Files/YTKKeyValueStore/YTKKeyValueStore-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_YTKKeyValueStore : NSObject +@end +@implementation PodsDummy_YTKKeyValueStore +@end diff --git a/Pods/Target Support Files/YTKKeyValueStore/YTKKeyValueStore-prefix.pch b/Pods/Target Support Files/YTKKeyValueStore/YTKKeyValueStore-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/YTKKeyValueStore/YTKKeyValueStore-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/YTKKeyValueStore/YTKKeyValueStore-umbrella.h b/Pods/Target Support Files/YTKKeyValueStore/YTKKeyValueStore-umbrella.h new file mode 100644 index 0000000..0e3d802 --- /dev/null +++ b/Pods/Target Support Files/YTKKeyValueStore/YTKKeyValueStore-umbrella.h @@ -0,0 +1,17 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "YTKKeyValueStore.h" + +FOUNDATION_EXPORT double YTKKeyValueStoreVersionNumber; +FOUNDATION_EXPORT const unsigned char YTKKeyValueStoreVersionString[]; + diff --git a/Pods/Target Support Files/YTKKeyValueStore/YTKKeyValueStore.modulemap b/Pods/Target Support Files/YTKKeyValueStore/YTKKeyValueStore.modulemap new file mode 100644 index 0000000..4b84412 --- /dev/null +++ b/Pods/Target Support Files/YTKKeyValueStore/YTKKeyValueStore.modulemap @@ -0,0 +1,6 @@ +framework module YTKKeyValueStore { + umbrella header "YTKKeyValueStore-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/YTKKeyValueStore/YTKKeyValueStore.xcconfig b/Pods/Target Support Files/YTKKeyValueStore/YTKKeyValueStore.xcconfig new file mode 100644 index 0000000..5d9e708 --- /dev/null +++ b/Pods/Target Support Files/YTKKeyValueStore/YTKKeyValueStore.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/YTKKeyValueStore +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/FMDB" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/YTKKeyValueStore +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Toast/README.md b/Pods/Toast/README.md new file mode 100644 index 0000000..c6b8e38 --- /dev/null +++ b/Pods/Toast/README.md @@ -0,0 +1,130 @@ +Toast for iOS +============= + +[![Build Status](https://travis-ci.org/scalessec/Toast.svg?branch=3.0)](https://travis-ci.org/scalessec/Toast) +[![CocoaPods Version](https://img.shields.io/cocoapods/v/Toast.svg)](http://cocoadocs.org/docsets/Toast) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) + +Toast is an Objective-C category that adds toast notifications to the `UIView` object class. It is intended to be simple, lightweight, and easy to use. Most + toast notifications can be triggered with a single line of code. + +**Using Swift? A native swift port of this library is now available: [Toast-Swift](https://github.com/scalessec/Toast-Swift "Toast-Swift")** + +Screenshots +--------- +![Toast Screenshots](toast_screenshots.jpg) + + +Basic Examples +--------- +```objc +// basic usage +[self.view makeToast:@"This is a piece of toast."]; + +// toast with a specific duration and position +[self.view makeToast:@"This is a piece of toast with a specific duration and position." + duration:3.0 + position:CSToastPositionTop]; + +// toast with all possible options +[self.view makeToast:@"This is a piece of toast with a title & image" + duration:3.0 + position:[NSValue valueWithCGPoint:CGPointMake(110, 110)] + title:@"Toast Title" + image:[UIImage imageNamed:@"toast.png"] + style:nil + completion:^(BOOL didTap) { + if (didTap) { + NSLog(@"completion from tap"); + } else { + NSLog(@"completion without tap"); + } + }]; + +// display toast with an activity spinner +[self.view makeToastActivity:CSToastPositionCenter]; + +// display any view as toast +[self.view showToast:myView]; +``` + +But wait, there's more! +--------- +```objc +// create a new style +CSToastStyle *style = [[CSToastStyle alloc] initWithDefaultStyle]; + +// this is just one of many style options +style.messageColor = [UIColor orangeColor]; + +// present the toast with the new style +[self.view makeToast:@"This is a piece of toast." + duration:3.0 + position:CSToastPositionBottom + style:style]; + +// or perhaps you want to use this style for all toasts going forward? +// just set the shared style and there's no need to provide the style again +[CSToastManager setSharedStyle:style]; + +// toggle "tap to dismiss" functionality +[CSToastManager setTapToDismissEnabled:YES]; + +// toggle queueing behavior +[CSToastManager setQueueEnabled:YES]; + +// immediately hides all toast views in self.view +[self.view hideAllToasts]; +``` + +See the demo project for more examples. + +Setup Instructions +------------------ + +[CocoaPods](http://cocoapods.org) +------------------ + +Install with CocoaPods by adding the following to your `Podfile`: +```ruby +pod 'Toast', '~> 4.0.0' +``` + +[Carthage](https://github.com/Carthage/Carthage) +------------------ + +Install with Carthage by adding the following to your `Cartfile`: +```ogdl +github "scalessec/Toast" ~> 4.0.0 +``` +Run `carthage update` to build the framework and link against `Toast.framework`. Then, `#import `. + +Manually +-------- + +1. Add `UIView+Toast.h` & `UIView+Toast.m` to your project. +2. `#import "UIView+Toast.h"` +3. Grab yourself a cold 🍺. + +MIT License +----------- + Copyright (c) 2011-2017 Charles Scalesse. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Pods/Toast/Toast-Framework/Toast.h b/Pods/Toast/Toast-Framework/Toast.h new file mode 100644 index 0000000..ca673d0 --- /dev/null +++ b/Pods/Toast/Toast-Framework/Toast.h @@ -0,0 +1,18 @@ +// +// Toast.h +// Toast +// +// Created by Charles Scalesse on 11/3/16. +// +// + +#import + +//! Project version number for Toast. +FOUNDATION_EXPORT double ToastVersionNumber; + +//! Project version string for Toast. +FOUNDATION_EXPORT const unsigned char ToastVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import +#import diff --git a/Pods/Toast/Toast/UIView+Toast.h b/Pods/Toast/Toast/UIView+Toast.h new file mode 100644 index 0000000..e2b258b --- /dev/null +++ b/Pods/Toast/Toast/UIView+Toast.h @@ -0,0 +1,446 @@ +// +// UIView+Toast.h +// Toast +// +// Copyright (c) 2011-2017 Charles Scalesse. +// +// 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 + +extern const NSString * CSToastPositionTop; +extern const NSString * CSToastPositionCenter; +extern const NSString * CSToastPositionBottom; + +@class CSToastStyle; + +/** + Toast is an Objective-C category that adds toast notifications to the UIView + object class. It is intended to be simple, lightweight, and easy to use. Most + toast notifications can be triggered with a single line of code. + + The `makeToast:` methods create a new view and then display it as toast. + + The `showToast:` methods display any view as toast. + + */ +@interface UIView (Toast) + +/** + Creates and presents a new toast view with a message and displays it with the + default duration and position. Styled using the shared style. + + @param message The message to be displayed + */ +- (void)makeToast:(NSString *)message; + +/** + Creates and presents a new toast view with a message. Duration and position + can be set explicitly. Styled using the shared style. + + @param message The message to be displayed + @param duration The toast duration + @param position The toast's center point. Can be one of the predefined CSToastPosition + constants or a `CGPoint` wrapped in an `NSValue` object. + */ +- (void)makeToast:(NSString *)message + duration:(NSTimeInterval)duration + position:(id)position; + +/** + Creates and presents a new toast view with a message. Duration, position, and + style can be set explicitly. + + @param message The message to be displayed + @param duration The toast duration + @param position The toast's center point. Can be one of the predefined CSToastPosition + constants or a `CGPoint` wrapped in an `NSValue` object. + @param style The style. The shared style will be used when nil + */ +- (void)makeToast:(NSString *)message + duration:(NSTimeInterval)duration + position:(id)position + style:(CSToastStyle *)style; + +/** + Creates and presents a new toast view with a message, title, and image. Duration, + position, and style can be set explicitly. The completion block executes when the + toast view completes. `didTap` will be `YES` if the toast view was dismissed from + a tap. + + @param message The message to be displayed + @param duration The toast duration + @param position The toast's center point. Can be one of the predefined CSToastPosition + constants or a `CGPoint` wrapped in an `NSValue` object. + @param title The title + @param image The image + @param style The style. The shared style will be used when nil + @param completion The completion block, executed after the toast view disappears. + didTap will be `YES` if the toast view was dismissed from a tap. + */ +- (void)makeToast:(NSString *)message + duration:(NSTimeInterval)duration + position:(id)position + title:(NSString *)title + image:(UIImage *)image + style:(CSToastStyle *)style + completion:(void(^)(BOOL didTap))completion; + +/** + Creates a new toast view with any combination of message, title, and image. + The look and feel is configured via the style. Unlike the `makeToast:` methods, + this method does not present the toast view automatically. One of the showToast: + methods must be used to present the resulting view. + + @warning if message, title, and image are all nil, this method will return nil. + + @param message The message to be displayed + @param title The title + @param image The image + @param style The style. The shared style will be used when nil + @return The newly created toast view + */ +- (UIView *)toastViewForMessage:(NSString *)message + title:(NSString *)title + image:(UIImage *)image + style:(CSToastStyle *)style; + +/** + Hides the active toast. If there are multiple toasts active in a view, this method + hides the oldest toast (the first of the toasts to have been presented). + + @see `hideAllToasts` to remove all active toasts from a view. + + @warning This method has no effect on activity toasts. Use `hideToastActivity` to + hide activity toasts. + */ +- (void)hideToast; + +/** + Hides an active toast. + + @param toast The active toast view to dismiss. Any toast that is currently being displayed + on the screen is considered active. + + @warning this does not clear a toast view that is currently waiting in the queue. + */ +- (void)hideToast:(UIView *)toast; + +/** + Hides all active toast views and clears the queue. + */ +- (void)hideAllToasts; + +/** + Hides all active toast views, with options to hide activity and clear the queue. + + @param includeActivity If `true`, toast activity will also be hidden. Default is `false`. + @param clearQueue If `true`, removes all toast views from the queue. Default is `true`. + */ +- (void)hideAllToasts:(BOOL)includeActivity clearQueue:(BOOL)clearQueue; + +/** + Removes all toast views from the queue. This has no effect on toast views that are + active. Use `hideAllToasts` to hide the active toasts views and clear the queue. + */ +- (void)clearToastQueue; + +/** + Creates and displays a new toast activity indicator view at a specified position. + + @warning Only one toast activity indicator view can be presented per superview. Subsequent + calls to `makeToastActivity:` will be ignored until hideToastActivity is called. + + @warning `makeToastActivity:` works independently of the showToast: methods. Toast activity + views can be presented and dismissed while toast views are being displayed. `makeToastActivity:` + has no effect on the queueing behavior of the showToast: methods. + + @param position The toast's center point. Can be one of the predefined CSToastPosition + constants or a `CGPoint` wrapped in an `NSValue` object. + */ +- (void)makeToastActivity:(id)position; + +/** + Dismisses the active toast activity indicator view. + */ +- (void)hideToastActivity; + +/** + Displays any view as toast using the default duration and position. + + @param toast The view to be displayed as toast + */ +- (void)showToast:(UIView *)toast; + +/** + Displays any view as toast at a provided position and duration. The completion block + executes when the toast view completes. `didTap` will be `YES` if the toast view was + dismissed from a tap. + + @param toast The view to be displayed as toast + @param duration The notification duration + @param position The toast's center point. Can be one of the predefined CSToastPosition + constants or a `CGPoint` wrapped in an `NSValue` object. + @param completion The completion block, executed after the toast view disappears. + didTap will be `YES` if the toast view was dismissed from a tap. + */ +- (void)showToast:(UIView *)toast + duration:(NSTimeInterval)duration + position:(id)position + completion:(void(^)(BOOL didTap))completion; + +@end + +/** + `CSToastStyle` instances define the look and feel for toast views created via the + `makeToast:` methods as well for toast views created directly with + `toastViewForMessage:title:image:style:`. + + @warning `CSToastStyle` offers relatively simple styling options for the default + toast view. If you require a toast view with more complex UI, it probably makes more + sense to create your own custom UIView subclass and present it with the `showToast:` + methods. + */ +@interface CSToastStyle : NSObject + +/** + The background color. Default is `[UIColor blackColor]` at 80% opacity. + */ +@property (strong, nonatomic) UIColor *backgroundColor; + +/** + The title color. Default is `[UIColor whiteColor]`. + */ +@property (strong, nonatomic) UIColor *titleColor; + +/** + The message color. Default is `[UIColor whiteColor]`. + */ +@property (strong, nonatomic) UIColor *messageColor; + +/** + A percentage value from 0.0 to 1.0, representing the maximum width of the toast + view relative to it's superview. Default is 0.8 (80% of the superview's width). + */ +@property (assign, nonatomic) CGFloat maxWidthPercentage; + +/** + A percentage value from 0.0 to 1.0, representing the maximum height of the toast + view relative to it's superview. Default is 0.8 (80% of the superview's height). + */ +@property (assign, nonatomic) CGFloat maxHeightPercentage; + +/** + The spacing from the horizontal edge of the toast view to the content. When an image + is present, this is also used as the padding between the image and the text. + Default is 10.0. + */ +@property (assign, nonatomic) CGFloat horizontalPadding; + +/** + The spacing from the vertical edge of the toast view to the content. When a title + is present, this is also used as the padding between the title and the message. + Default is 10.0. + */ +@property (assign, nonatomic) CGFloat verticalPadding; + +/** + The corner radius. Default is 10.0. + */ +@property (assign, nonatomic) CGFloat cornerRadius; + +/** + The title font. Default is `[UIFont boldSystemFontOfSize:16.0]`. + */ +@property (strong, nonatomic) UIFont *titleFont; + +/** + The message font. Default is `[UIFont systemFontOfSize:16.0]`. + */ +@property (strong, nonatomic) UIFont *messageFont; + +/** + The title text alignment. Default is `NSTextAlignmentLeft`. + */ +@property (assign, nonatomic) NSTextAlignment titleAlignment; + +/** + The message text alignment. Default is `NSTextAlignmentLeft`. + */ +@property (assign, nonatomic) NSTextAlignment messageAlignment; + +/** + The maximum number of lines for the title. The default is 0 (no limit). + */ +@property (assign, nonatomic) NSInteger titleNumberOfLines; + +/** + The maximum number of lines for the message. The default is 0 (no limit). + */ +@property (assign, nonatomic) NSInteger messageNumberOfLines; + +/** + Enable or disable a shadow on the toast view. Default is `NO`. + */ +@property (assign, nonatomic) BOOL displayShadow; + +/** + The shadow color. Default is `[UIColor blackColor]`. + */ +@property (strong, nonatomic) UIColor *shadowColor; + +/** + A value from 0.0 to 1.0, representing the opacity of the shadow. + Default is 0.8 (80% opacity). + */ +@property (assign, nonatomic) CGFloat shadowOpacity; + +/** + The shadow radius. Default is 6.0. + */ +@property (assign, nonatomic) CGFloat shadowRadius; + +/** + The shadow offset. The default is `CGSizeMake(4.0, 4.0)`. + */ +@property (assign, nonatomic) CGSize shadowOffset; + +/** + The image size. The default is `CGSizeMake(80.0, 80.0)`. + */ +@property (assign, nonatomic) CGSize imageSize; + +/** + The size of the toast activity view when `makeToastActivity:` is called. + Default is `CGSizeMake(100.0, 100.0)`. + */ +@property (assign, nonatomic) CGSize activitySize; + +/** + The fade in/out animation duration. Default is 0.2. + */ +@property (assign, nonatomic) NSTimeInterval fadeDuration; + +/** + Creates a new instance of `CSToastStyle` with all the default values set. + */ +- (instancetype)initWithDefaultStyle NS_DESIGNATED_INITIALIZER; + +/** + @warning Only the designated initializer should be used to create + an instance of `CSToastStyle`. + */ +- (instancetype)init NS_UNAVAILABLE; + +@end + +/** + `CSToastManager` provides general configuration options for all toast + notifications. Backed by a singleton instance. + */ +@interface CSToastManager : NSObject + +/** + Sets the shared style on the singleton. The shared style is used whenever + a `makeToast:` method (or `toastViewForMessage:title:image:style:`) is called + with with a nil style. By default, this is set to `CSToastStyle`'s default + style. + + @param sharedStyle the shared style + */ ++ (void)setSharedStyle:(CSToastStyle *)sharedStyle; + +/** + Gets the shared style from the singlton. By default, this is + `CSToastStyle`'s default style. + + @return the shared style + */ ++ (CSToastStyle *)sharedStyle; + +/** + Enables or disables tap to dismiss on toast views. Default is `YES`. + + @param tapToDismissEnabled YES or NO + */ ++ (void)setTapToDismissEnabled:(BOOL)tapToDismissEnabled; + +/** + Returns `YES` if tap to dismiss is enabled, otherwise `NO`. + Default is `YES`. + + @return BOOL YES or NO + */ ++ (BOOL)isTapToDismissEnabled; + +/** + Enables or disables queueing behavior for toast views. When `YES`, + toast views will appear one after the other. When `NO`, multiple Toast + views will appear at the same time (potentially overlapping depending + on their positions). This has no effect on the toast activity view, + which operates independently of normal toast views. Default is `NO`. + + @param queueEnabled YES or NO + */ ++ (void)setQueueEnabled:(BOOL)queueEnabled; + +/** + Returns `YES` if the queue is enabled, otherwise `NO`. + Default is `NO`. + + @return BOOL + */ ++ (BOOL)isQueueEnabled; + +/** + Sets the default duration. Used for the `makeToast:` and + `showToast:` methods that don't require an explicit duration. + Default is 3.0. + + @param duration The toast duration + */ ++ (void)setDefaultDuration:(NSTimeInterval)duration; + +/** + Returns the default duration. Default is 3.0. + + @return duration The toast duration +*/ ++ (NSTimeInterval)defaultDuration; + +/** + Sets the default position. Used for the `makeToast:` and + `showToast:` methods that don't require an explicit position. + Default is `CSToastPositionBottom`. + + @param position The default center point. Can be one of the predefined + CSToastPosition constants or a `CGPoint` wrapped in an `NSValue` object. + */ ++ (void)setDefaultPosition:(id)position; + +/** + Returns the default toast position. Default is `CSToastPositionBottom`. + + @return position The default center point. Will be one of the predefined + CSToastPosition constants or a `CGPoint` wrapped in an `NSValue` object. + */ ++ (id)defaultPosition; + +@end diff --git a/Pods/Toast/Toast/UIView+Toast.m b/Pods/Toast/Toast/UIView+Toast.m new file mode 100644 index 0000000..4e5131a --- /dev/null +++ b/Pods/Toast/Toast/UIView+Toast.m @@ -0,0 +1,586 @@ +// +// UIView+Toast.m +// Toast +// +// Copyright (c) 2011-2017 Charles Scalesse. +// +// 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 "UIView+Toast.h" +#import +#import + +// Positions +NSString * CSToastPositionTop = @"CSToastPositionTop"; +NSString * CSToastPositionCenter = @"CSToastPositionCenter"; +NSString * CSToastPositionBottom = @"CSToastPositionBottom"; + +// Keys for values associated with toast views +static const NSString * CSToastTimerKey = @"CSToastTimerKey"; +static const NSString * CSToastDurationKey = @"CSToastDurationKey"; +static const NSString * CSToastPositionKey = @"CSToastPositionKey"; +static const NSString * CSToastCompletionKey = @"CSToastCompletionKey"; + +// Keys for values associated with self +static const NSString * CSToastActiveKey = @"CSToastActiveKey"; +static const NSString * CSToastActivityViewKey = @"CSToastActivityViewKey"; +static const NSString * CSToastQueueKey = @"CSToastQueueKey"; + +@interface UIView (ToastPrivate) + +/** + These private methods are being prefixed with "cs_" to reduce the likelihood of non-obvious + naming conflicts with other UIView methods. + + @discussion Should the public API also use the cs_ prefix? Technically it should, but it + results in code that is less legible. The current public method names seem unlikely to cause + conflicts so I think we should favor the cleaner API for now. + */ +- (void)cs_showToast:(UIView *)toast duration:(NSTimeInterval)duration position:(id)position; +- (void)cs_hideToast:(UIView *)toast; +- (void)cs_hideToast:(UIView *)toast fromTap:(BOOL)fromTap; +- (void)cs_toastTimerDidFinish:(NSTimer *)timer; +- (void)cs_handleToastTapped:(UITapGestureRecognizer *)recognizer; +- (CGPoint)cs_centerPointForPosition:(id)position withToast:(UIView *)toast; +- (NSMutableArray *)cs_toastQueue; + +@end + +@implementation UIView (Toast) + +#pragma mark - Make Toast Methods + +- (void)makeToast:(NSString *)message { + [self makeToast:message duration:[CSToastManager defaultDuration] position:[CSToastManager defaultPosition] style:nil]; +} + +- (void)makeToast:(NSString *)message duration:(NSTimeInterval)duration position:(id)position { + [self makeToast:message duration:duration position:position style:nil]; +} + +- (void)makeToast:(NSString *)message duration:(NSTimeInterval)duration position:(id)position style:(CSToastStyle *)style { + UIView *toast = [self toastViewForMessage:message title:nil image:nil style:style]; + [self showToast:toast duration:duration position:position completion:nil]; +} + +- (void)makeToast:(NSString *)message duration:(NSTimeInterval)duration position:(id)position title:(NSString *)title image:(UIImage *)image style:(CSToastStyle *)style completion:(void(^)(BOOL didTap))completion { + UIView *toast = [self toastViewForMessage:message title:title image:image style:style]; + [self showToast:toast duration:duration position:position completion:completion]; +} + +#pragma mark - Show Toast Methods + +- (void)showToast:(UIView *)toast { + [self showToast:toast duration:[CSToastManager defaultDuration] position:[CSToastManager defaultPosition] completion:nil]; +} + +- (void)showToast:(UIView *)toast duration:(NSTimeInterval)duration position:(id)position completion:(void(^)(BOOL didTap))completion { + // sanity + if (toast == nil) return; + + // store the completion block on the toast view + objc_setAssociatedObject(toast, &CSToastCompletionKey, completion, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + if ([CSToastManager isQueueEnabled] && [self.cs_activeToasts count] > 0) { + // we're about to queue this toast view so we need to store the duration and position as well + objc_setAssociatedObject(toast, &CSToastDurationKey, @(duration), OBJC_ASSOCIATION_RETAIN_NONATOMIC); + objc_setAssociatedObject(toast, &CSToastPositionKey, position, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + // enqueue + [self.cs_toastQueue addObject:toast]; + } else { + // present + [self cs_showToast:toast duration:duration position:position]; + } +} + +#pragma mark - Hide Toast Methods + +- (void)hideToast { + [self hideToast:[[self cs_activeToasts] firstObject]]; +} + +- (void)hideToast:(UIView *)toast { + // sanity + if (!toast || ![[self cs_activeToasts] containsObject:toast]) return; + + [self cs_hideToast:toast]; +} + +- (void)hideAllToasts { + [self hideAllToasts:NO clearQueue:YES]; +} + +- (void)hideAllToasts:(BOOL)includeActivity clearQueue:(BOOL)clearQueue { + if (clearQueue) { + [self clearToastQueue]; + } + + for (UIView *toast in [self cs_activeToasts]) { + [self hideToast:toast]; + } + + if (includeActivity) { + [self hideToastActivity]; + } +} + +- (void)clearToastQueue { + [[self cs_toastQueue] removeAllObjects]; +} + +#pragma mark - Private Show/Hide Methods + +- (void)cs_showToast:(UIView *)toast duration:(NSTimeInterval)duration position:(id)position { + toast.center = [self cs_centerPointForPosition:position withToast:toast]; + toast.alpha = 0.0; + + if ([CSToastManager isTapToDismissEnabled]) { + UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cs_handleToastTapped:)]; + [toast addGestureRecognizer:recognizer]; + toast.userInteractionEnabled = YES; + toast.exclusiveTouch = YES; + } + + [[self cs_activeToasts] addObject:toast]; + + [self addSubview:toast]; + + [UIView animateWithDuration:[[CSToastManager sharedStyle] fadeDuration] + delay:0.0 + options:(UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionAllowUserInteraction) + animations:^{ + toast.alpha = 1.0; + } completion:^(BOOL finished) { + NSTimer *timer = [NSTimer timerWithTimeInterval:duration target:self selector:@selector(cs_toastTimerDidFinish:) userInfo:toast repeats:NO]; + [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; + objc_setAssociatedObject(toast, &CSToastTimerKey, timer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + }]; +} + +- (void)cs_hideToast:(UIView *)toast { + [self cs_hideToast:toast fromTap:NO]; +} + +- (void)cs_hideToast:(UIView *)toast fromTap:(BOOL)fromTap { + NSTimer *timer = (NSTimer *)objc_getAssociatedObject(toast, &CSToastTimerKey); + [timer invalidate]; + + [UIView animateWithDuration:[[CSToastManager sharedStyle] fadeDuration] + delay:0.0 + options:(UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionBeginFromCurrentState) + animations:^{ + toast.alpha = 0.0; + } completion:^(BOOL finished) { + [toast removeFromSuperview]; + + // remove + [[self cs_activeToasts] removeObject:toast]; + + // execute the completion block, if necessary + void (^completion)(BOOL didTap) = objc_getAssociatedObject(toast, &CSToastCompletionKey); + if (completion) { + completion(fromTap); + } + + if ([self.cs_toastQueue count] > 0) { + // dequeue + UIView *nextToast = [[self cs_toastQueue] firstObject]; + [[self cs_toastQueue] removeObjectAtIndex:0]; + + // present the next toast + NSTimeInterval duration = [objc_getAssociatedObject(nextToast, &CSToastDurationKey) doubleValue]; + id position = objc_getAssociatedObject(nextToast, &CSToastPositionKey); + [self cs_showToast:nextToast duration:duration position:position]; + } + }]; +} + +#pragma mark - View Construction + +- (UIView *)toastViewForMessage:(NSString *)message title:(NSString *)title image:(UIImage *)image style:(CSToastStyle *)style { + // sanity + if (message == nil && title == nil && image == nil) return nil; + + // default to the shared style + if (style == nil) { + style = [CSToastManager sharedStyle]; + } + + // dynamically build a toast view with any combination of message, title, & image + UILabel *messageLabel = nil; + UILabel *titleLabel = nil; + UIImageView *imageView = nil; + + UIView *wrapperView = [[UIView alloc] init]; + wrapperView.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin); + wrapperView.layer.cornerRadius = style.cornerRadius; + + if (style.displayShadow) { + wrapperView.layer.shadowColor = style.shadowColor.CGColor; + wrapperView.layer.shadowOpacity = style.shadowOpacity; + wrapperView.layer.shadowRadius = style.shadowRadius; + wrapperView.layer.shadowOffset = style.shadowOffset; + } + + wrapperView.backgroundColor = style.backgroundColor; + + if(image != nil) { + imageView = [[UIImageView alloc] initWithImage:image]; + imageView.contentMode = UIViewContentModeScaleAspectFit; + imageView.frame = CGRectMake(style.horizontalPadding, style.verticalPadding, style.imageSize.width, style.imageSize.height); + } + + CGRect imageRect = CGRectZero; + + if(imageView != nil) { + imageRect.origin.x = style.horizontalPadding; + imageRect.origin.y = style.verticalPadding; + imageRect.size.width = imageView.bounds.size.width; + imageRect.size.height = imageView.bounds.size.height; + } + + if (title != nil) { + titleLabel = [[UILabel alloc] init]; + titleLabel.numberOfLines = style.titleNumberOfLines; + titleLabel.font = style.titleFont; + titleLabel.textAlignment = style.titleAlignment; + titleLabel.lineBreakMode = NSLineBreakByTruncatingTail; + titleLabel.textColor = style.titleColor; + titleLabel.backgroundColor = [UIColor clearColor]; + titleLabel.alpha = 1.0; + titleLabel.text = title; + + // size the title label according to the length of the text + CGSize maxSizeTitle = CGSizeMake((self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, self.bounds.size.height * style.maxHeightPercentage); + CGSize expectedSizeTitle = [titleLabel sizeThatFits:maxSizeTitle]; + // UILabel can return a size larger than the max size when the number of lines is 1 + expectedSizeTitle = CGSizeMake(MIN(maxSizeTitle.width, expectedSizeTitle.width), MIN(maxSizeTitle.height, expectedSizeTitle.height)); + titleLabel.frame = CGRectMake(0.0, 0.0, expectedSizeTitle.width, expectedSizeTitle.height); + } + + if (message != nil) { + messageLabel = [[UILabel alloc] init]; + messageLabel.numberOfLines = style.messageNumberOfLines; + messageLabel.font = style.messageFont; + messageLabel.textAlignment = style.messageAlignment; + messageLabel.lineBreakMode = NSLineBreakByTruncatingTail; + messageLabel.textColor = style.messageColor; + messageLabel.backgroundColor = [UIColor clearColor]; + messageLabel.alpha = 1.0; + messageLabel.text = message; + + CGSize maxSizeMessage = CGSizeMake((self.bounds.size.width * style.maxWidthPercentage) - imageRect.size.width, self.bounds.size.height * style.maxHeightPercentage); + CGSize expectedSizeMessage = [messageLabel sizeThatFits:maxSizeMessage]; + // UILabel can return a size larger than the max size when the number of lines is 1 + expectedSizeMessage = CGSizeMake(MIN(maxSizeMessage.width, expectedSizeMessage.width), MIN(maxSizeMessage.height, expectedSizeMessage.height)); + messageLabel.frame = CGRectMake(0.0, 0.0, expectedSizeMessage.width, expectedSizeMessage.height); + } + + CGRect titleRect = CGRectZero; + + if(titleLabel != nil) { + titleRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding; + titleRect.origin.y = style.verticalPadding; + titleRect.size.width = titleLabel.bounds.size.width; + titleRect.size.height = titleLabel.bounds.size.height; + } + + CGRect messageRect = CGRectZero; + + if(messageLabel != nil) { + messageRect.origin.x = imageRect.origin.x + imageRect.size.width + style.horizontalPadding; + messageRect.origin.y = titleRect.origin.y + titleRect.size.height + style.verticalPadding; + messageRect.size.width = messageLabel.bounds.size.width; + messageRect.size.height = messageLabel.bounds.size.height; + } + + CGFloat longerWidth = MAX(titleRect.size.width, messageRect.size.width); + CGFloat longerX = MAX(titleRect.origin.x, messageRect.origin.x); + + // Wrapper width uses the longerWidth or the image width, whatever is larger. Same logic applies to the wrapper height. + CGFloat wrapperWidth = MAX((imageRect.size.width + (style.horizontalPadding * 2.0)), (longerX + longerWidth + style.horizontalPadding)); + CGFloat wrapperHeight = MAX((messageRect.origin.y + messageRect.size.height + style.verticalPadding), (imageRect.size.height + (style.verticalPadding * 2.0))); + + wrapperView.frame = CGRectMake(0.0, 0.0, wrapperWidth, wrapperHeight); + + if(titleLabel != nil) { + titleLabel.frame = titleRect; + [wrapperView addSubview:titleLabel]; + } + + if(messageLabel != nil) { + messageLabel.frame = messageRect; + [wrapperView addSubview:messageLabel]; + } + + if(imageView != nil) { + [wrapperView addSubview:imageView]; + } + + return wrapperView; +} + +#pragma mark - Storage + +- (NSMutableArray *)cs_activeToasts { + NSMutableArray *cs_activeToasts = objc_getAssociatedObject(self, &CSToastActiveKey); + if (cs_activeToasts == nil) { + cs_activeToasts = [[NSMutableArray alloc] init]; + objc_setAssociatedObject(self, &CSToastActiveKey, cs_activeToasts, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return cs_activeToasts; +} + +- (NSMutableArray *)cs_toastQueue { + NSMutableArray *cs_toastQueue = objc_getAssociatedObject(self, &CSToastQueueKey); + if (cs_toastQueue == nil) { + cs_toastQueue = [[NSMutableArray alloc] init]; + objc_setAssociatedObject(self, &CSToastQueueKey, cs_toastQueue, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return cs_toastQueue; +} + +#pragma mark - Events + +- (void)cs_toastTimerDidFinish:(NSTimer *)timer { + [self cs_hideToast:(UIView *)timer.userInfo]; +} + +- (void)cs_handleToastTapped:(UITapGestureRecognizer *)recognizer { + UIView *toast = recognizer.view; + NSTimer *timer = (NSTimer *)objc_getAssociatedObject(toast, &CSToastTimerKey); + [timer invalidate]; + + [self cs_hideToast:toast fromTap:YES]; +} + +#pragma mark - Activity Methods + +- (void)makeToastActivity:(id)position { + // sanity + UIView *existingActivityView = (UIView *)objc_getAssociatedObject(self, &CSToastActivityViewKey); + if (existingActivityView != nil) return; + + CSToastStyle *style = [CSToastManager sharedStyle]; + + UIView *activityView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, style.activitySize.width, style.activitySize.height)]; + activityView.center = [self cs_centerPointForPosition:position withToast:activityView]; + activityView.backgroundColor = style.backgroundColor; + activityView.alpha = 0.0; + activityView.autoresizingMask = (UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin); + activityView.layer.cornerRadius = style.cornerRadius; + + if (style.displayShadow) { + activityView.layer.shadowColor = style.shadowColor.CGColor; + activityView.layer.shadowOpacity = style.shadowOpacity; + activityView.layer.shadowRadius = style.shadowRadius; + activityView.layer.shadowOffset = style.shadowOffset; + } + + UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; + activityIndicatorView.center = CGPointMake(activityView.bounds.size.width / 2, activityView.bounds.size.height / 2); + [activityView addSubview:activityIndicatorView]; + [activityIndicatorView startAnimating]; + + // associate the activity view with self + objc_setAssociatedObject (self, &CSToastActivityViewKey, activityView, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + [self addSubview:activityView]; + + [UIView animateWithDuration:style.fadeDuration + delay:0.0 + options:UIViewAnimationOptionCurveEaseOut + animations:^{ + activityView.alpha = 1.0; + } completion:nil]; +} + +- (void)hideToastActivity { + UIView *existingActivityView = (UIView *)objc_getAssociatedObject(self, &CSToastActivityViewKey); + if (existingActivityView != nil) { + [UIView animateWithDuration:[[CSToastManager sharedStyle] fadeDuration] + delay:0.0 + options:(UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionBeginFromCurrentState) + animations:^{ + existingActivityView.alpha = 0.0; + } completion:^(BOOL finished) { + [existingActivityView removeFromSuperview]; + objc_setAssociatedObject (self, &CSToastActivityViewKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + }]; + } +} + +#pragma mark - Helpers + +- (CGPoint)cs_centerPointForPosition:(id)point withToast:(UIView *)toast { + CSToastStyle *style = [CSToastManager sharedStyle]; + + UIEdgeInsets safeInsets = UIEdgeInsetsZero; + if (@available(iOS 11.0, *)) { + safeInsets = self.safeAreaInsets; + } + + CGFloat topPadding = style.verticalPadding + safeInsets.top; + CGFloat bottomPadding = style.verticalPadding + safeInsets.bottom; + + if([point isKindOfClass:[NSString class]]) { + if([point caseInsensitiveCompare:CSToastPositionTop] == NSOrderedSame) { + return CGPointMake(self.bounds.size.width / 2.0, (toast.frame.size.height / 2.0) + topPadding); + } else if([point caseInsensitiveCompare:CSToastPositionCenter] == NSOrderedSame) { + return CGPointMake(self.bounds.size.width / 2.0, self.bounds.size.height / 2.0); + } + } else if ([point isKindOfClass:[NSValue class]]) { + return [point CGPointValue]; + } + + // default to bottom + return CGPointMake(self.bounds.size.width / 2.0, (self.bounds.size.height - (toast.frame.size.height / 2.0)) - bottomPadding); +} + +@end + +@implementation CSToastStyle + +#pragma mark - Constructors + +- (instancetype)initWithDefaultStyle { + self = [super init]; + if (self) { + self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8]; + self.titleColor = [UIColor whiteColor]; + self.messageColor = [UIColor whiteColor]; + self.maxWidthPercentage = 0.8; + self.maxHeightPercentage = 0.8; + self.horizontalPadding = 10.0; + self.verticalPadding = 10.0; + self.cornerRadius = 10.0; + self.titleFont = [UIFont boldSystemFontOfSize:16.0]; + self.messageFont = [UIFont systemFontOfSize:16.0]; + self.titleAlignment = NSTextAlignmentLeft; + self.messageAlignment = NSTextAlignmentLeft; + self.titleNumberOfLines = 0; + self.messageNumberOfLines = 0; + self.displayShadow = NO; + self.shadowOpacity = 0.8; + self.shadowRadius = 6.0; + self.shadowOffset = CGSizeMake(4.0, 4.0); + self.imageSize = CGSizeMake(80.0, 80.0); + self.activitySize = CGSizeMake(100.0, 100.0); + self.fadeDuration = 0.2; + } + return self; +} + +- (void)setMaxWidthPercentage:(CGFloat)maxWidthPercentage { + _maxWidthPercentage = MAX(MIN(maxWidthPercentage, 1.0), 0.0); +} + +- (void)setMaxHeightPercentage:(CGFloat)maxHeightPercentage { + _maxHeightPercentage = MAX(MIN(maxHeightPercentage, 1.0), 0.0); +} + +- (instancetype)init NS_UNAVAILABLE { + return nil; +} + +@end + +@interface CSToastManager () + +@property (strong, nonatomic) CSToastStyle *sharedStyle; +@property (assign, nonatomic, getter=isTapToDismissEnabled) BOOL tapToDismissEnabled; +@property (assign, nonatomic, getter=isQueueEnabled) BOOL queueEnabled; +@property (assign, nonatomic) NSTimeInterval defaultDuration; +@property (strong, nonatomic) id defaultPosition; + +@end + +@implementation CSToastManager + +#pragma mark - Constructors + ++ (instancetype)sharedManager { + static CSToastManager *_sharedManager = nil; + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + _sharedManager = [[self alloc] init]; + }); + + return _sharedManager; +} + +- (instancetype)init { + self = [super init]; + if (self) { + self.sharedStyle = [[CSToastStyle alloc] initWithDefaultStyle]; + self.tapToDismissEnabled = YES; + self.queueEnabled = NO; + self.defaultDuration = 3.0; + self.defaultPosition = CSToastPositionBottom; + } + return self; +} + +#pragma mark - Singleton Methods + ++ (void)setSharedStyle:(CSToastStyle *)sharedStyle { + [[self sharedManager] setSharedStyle:sharedStyle]; +} + ++ (CSToastStyle *)sharedStyle { + return [[self sharedManager] sharedStyle]; +} + ++ (void)setTapToDismissEnabled:(BOOL)tapToDismissEnabled { + [[self sharedManager] setTapToDismissEnabled:tapToDismissEnabled]; +} + ++ (BOOL)isTapToDismissEnabled { + return [[self sharedManager] isTapToDismissEnabled]; +} + ++ (void)setQueueEnabled:(BOOL)queueEnabled { + [[self sharedManager] setQueueEnabled:queueEnabled]; +} + ++ (BOOL)isQueueEnabled { + return [[self sharedManager] isQueueEnabled]; +} + ++ (void)setDefaultDuration:(NSTimeInterval)duration { + [[self sharedManager] setDefaultDuration:duration]; +} + ++ (NSTimeInterval)defaultDuration { + return [[self sharedManager] defaultDuration]; +} + ++ (void)setDefaultPosition:(id)position { + if ([position isKindOfClass:[NSString class]] || [position isKindOfClass:[NSValue class]]) { + [[self sharedManager] setDefaultPosition:position]; + } +} + ++ (id)defaultPosition { + return [[self sharedManager] defaultPosition]; +} + +@end diff --git a/Pods/Toast/license b/Pods/Toast/license new file mode 100644 index 0000000..824646d --- /dev/null +++ b/Pods/Toast/license @@ -0,0 +1,20 @@ +Copyright (c) 2011-2017 Charles Scalesse. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDIndexPathHeightCache.h b/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDIndexPathHeightCache.h new file mode 100644 index 0000000..0c0d20e --- /dev/null +++ b/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDIndexPathHeightCache.h @@ -0,0 +1,49 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2016 forkingdog ( https://github.com/forkingdog ) +// +// 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 + +@interface FDIndexPathHeightCache : NSObject + +// Enable automatically if you're using index path driven height cache +@property (nonatomic, assign) BOOL automaticallyInvalidateEnabled; + +// Height cache +- (BOOL)existsHeightAtIndexPath:(NSIndexPath *)indexPath; +- (void)cacheHeight:(CGFloat)height byIndexPath:(NSIndexPath *)indexPath; +- (CGFloat)heightForIndexPath:(NSIndexPath *)indexPath; +- (void)invalidateHeightAtIndexPath:(NSIndexPath *)indexPath; +- (void)invalidateAllHeightCache; + +@end + +@interface UITableView (FDIndexPathHeightCache) +/// Height cache by index path. Generally, you don't need to use it directly. +@property (nonatomic, strong, readonly) FDIndexPathHeightCache *fd_indexPathHeightCache; +@end + +@interface UITableView (FDIndexPathHeightCacheInvalidation) +/// Call this method when you want to reload data but don't want to invalidate +/// all height cache by index path, for example, load more data at the bottom of +/// table view. +- (void)fd_reloadDataWithoutInvalidateIndexPathHeightCache; +@end diff --git a/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDIndexPathHeightCache.m b/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDIndexPathHeightCache.m new file mode 100644 index 0000000..1e3a8a2 --- /dev/null +++ b/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDIndexPathHeightCache.m @@ -0,0 +1,288 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2016 forkingdog ( https://github.com/forkingdog ) +// +// 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 "UITableView+FDIndexPathHeightCache.h" +#import + +typedef NSMutableArray *> FDIndexPathHeightsBySection; + +@interface FDIndexPathHeightCache () +@property (nonatomic, strong) FDIndexPathHeightsBySection *heightsBySectionForPortrait; +@property (nonatomic, strong) FDIndexPathHeightsBySection *heightsBySectionForLandscape; +@end + +@implementation FDIndexPathHeightCache + +- (instancetype)init { + self = [super init]; + if (self) { + _heightsBySectionForPortrait = [NSMutableArray array]; + _heightsBySectionForLandscape = [NSMutableArray array]; + } + return self; +} + +- (FDIndexPathHeightsBySection *)heightsBySectionForCurrentOrientation { + return UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation) ? self.heightsBySectionForPortrait: self.heightsBySectionForLandscape; +} + +- (void)enumerateAllOrientationsUsingBlock:(void (^)(FDIndexPathHeightsBySection *heightsBySection))block { + block(self.heightsBySectionForPortrait); + block(self.heightsBySectionForLandscape); +} + +- (BOOL)existsHeightAtIndexPath:(NSIndexPath *)indexPath { + [self buildCachesAtIndexPathsIfNeeded:@[indexPath]]; + NSNumber *number = self.heightsBySectionForCurrentOrientation[indexPath.section][indexPath.row]; + return ![number isEqualToNumber:@-1]; +} + +- (void)cacheHeight:(CGFloat)height byIndexPath:(NSIndexPath *)indexPath { + self.automaticallyInvalidateEnabled = YES; + [self buildCachesAtIndexPathsIfNeeded:@[indexPath]]; + self.heightsBySectionForCurrentOrientation[indexPath.section][indexPath.row] = @(height); +} + +- (CGFloat)heightForIndexPath:(NSIndexPath *)indexPath { + [self buildCachesAtIndexPathsIfNeeded:@[indexPath]]; + NSNumber *number = self.heightsBySectionForCurrentOrientation[indexPath.section][indexPath.row]; +#if CGFLOAT_IS_DOUBLE + return number.doubleValue; +#else + return number.floatValue; +#endif +} + +- (void)invalidateHeightAtIndexPath:(NSIndexPath *)indexPath { + [self buildCachesAtIndexPathsIfNeeded:@[indexPath]]; + [self enumerateAllOrientationsUsingBlock:^(FDIndexPathHeightsBySection *heightsBySection) { + heightsBySection[indexPath.section][indexPath.row] = @-1; + }]; +} + +- (void)invalidateAllHeightCache { + [self enumerateAllOrientationsUsingBlock:^(FDIndexPathHeightsBySection *heightsBySection) { + [heightsBySection removeAllObjects]; + }]; +} + +- (void)buildCachesAtIndexPathsIfNeeded:(NSArray *)indexPaths { + // Build every section array or row array which is smaller than given index path. + [indexPaths enumerateObjectsUsingBlock:^(NSIndexPath *indexPath, NSUInteger idx, BOOL *stop) { + [self buildSectionsIfNeeded:indexPath.section]; + [self buildRowsIfNeeded:indexPath.row inExistSection:indexPath.section]; + }]; +} + +- (void)buildSectionsIfNeeded:(NSInteger)targetSection { + [self enumerateAllOrientationsUsingBlock:^(FDIndexPathHeightsBySection *heightsBySection) { + for (NSInteger section = 0; section <= targetSection; ++section) { + if (section >= heightsBySection.count) { + heightsBySection[section] = [NSMutableArray array]; + } + } + }]; +} + +- (void)buildRowsIfNeeded:(NSInteger)targetRow inExistSection:(NSInteger)section { + [self enumerateAllOrientationsUsingBlock:^(FDIndexPathHeightsBySection *heightsBySection) { + NSMutableArray *heightsByRow = heightsBySection[section]; + for (NSInteger row = 0; row <= targetRow; ++row) { + if (row >= heightsByRow.count) { + heightsByRow[row] = @-1; + } + } + }]; +} + +@end + +@implementation UITableView (FDIndexPathHeightCache) + +- (FDIndexPathHeightCache *)fd_indexPathHeightCache { + FDIndexPathHeightCache *cache = objc_getAssociatedObject(self, _cmd); + if (!cache) { + cache = [FDIndexPathHeightCache new]; + objc_setAssociatedObject(self, _cmd, cache, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return cache; +} + +@end + +// We just forward primary call, in crash report, top most method in stack maybe FD's, +// but it's really not our bug, you should check whether your table view's data source and +// displaying cells are not matched when reloading. +static void __FD_TEMPLATE_LAYOUT_CELL_PRIMARY_CALL_IF_CRASH_NOT_OUR_BUG__(void (^callout)(void)) { + callout(); +} +#define FDPrimaryCall(...) do {__FD_TEMPLATE_LAYOUT_CELL_PRIMARY_CALL_IF_CRASH_NOT_OUR_BUG__(^{__VA_ARGS__});} while(0) + +@implementation UITableView (FDIndexPathHeightCacheInvalidation) + +- (void)fd_reloadDataWithoutInvalidateIndexPathHeightCache { + FDPrimaryCall([self fd_reloadData];); +} + ++ (void)load { + // All methods that trigger height cache's invalidation + SEL selectors[] = { + @selector(reloadData), + @selector(insertSections:withRowAnimation:), + @selector(deleteSections:withRowAnimation:), + @selector(reloadSections:withRowAnimation:), + @selector(moveSection:toSection:), + @selector(insertRowsAtIndexPaths:withRowAnimation:), + @selector(deleteRowsAtIndexPaths:withRowAnimation:), + @selector(reloadRowsAtIndexPaths:withRowAnimation:), + @selector(moveRowAtIndexPath:toIndexPath:) + }; + + for (NSUInteger index = 0; index < sizeof(selectors) / sizeof(SEL); ++index) { + SEL originalSelector = selectors[index]; + SEL swizzledSelector = NSSelectorFromString([@"fd_" stringByAppendingString:NSStringFromSelector(originalSelector)]); + Method originalMethod = class_getInstanceMethod(self, originalSelector); + Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector); + method_exchangeImplementations(originalMethod, swizzledMethod); + } +} + +- (void)fd_reloadData { + if (self.fd_indexPathHeightCache.automaticallyInvalidateEnabled) { + [self.fd_indexPathHeightCache enumerateAllOrientationsUsingBlock:^(FDIndexPathHeightsBySection *heightsBySection) { + [heightsBySection removeAllObjects]; + }]; + } + FDPrimaryCall([self fd_reloadData];); +} + +- (void)fd_insertSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation { + if (self.fd_indexPathHeightCache.automaticallyInvalidateEnabled) { + [sections enumerateIndexesUsingBlock:^(NSUInteger section, BOOL *stop) { + [self.fd_indexPathHeightCache buildSectionsIfNeeded:section]; + [self.fd_indexPathHeightCache enumerateAllOrientationsUsingBlock:^(FDIndexPathHeightsBySection *heightsBySection) { + [heightsBySection insertObject:[NSMutableArray array] atIndex:section]; + }]; + }]; + } + FDPrimaryCall([self fd_insertSections:sections withRowAnimation:animation];); +} + +- (void)fd_deleteSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation { + if (self.fd_indexPathHeightCache.automaticallyInvalidateEnabled) { + [sections enumerateIndexesUsingBlock:^(NSUInteger section, BOOL *stop) { + [self.fd_indexPathHeightCache buildSectionsIfNeeded:section]; + [self.fd_indexPathHeightCache enumerateAllOrientationsUsingBlock:^(FDIndexPathHeightsBySection *heightsBySection) { + [heightsBySection removeObjectAtIndex:section]; + }]; + }]; + } + FDPrimaryCall([self fd_deleteSections:sections withRowAnimation:animation];); +} + +- (void)fd_reloadSections:(NSIndexSet *)sections withRowAnimation:(UITableViewRowAnimation)animation { + if (self.fd_indexPathHeightCache.automaticallyInvalidateEnabled) { + [sections enumerateIndexesUsingBlock: ^(NSUInteger section, BOOL *stop) { + [self.fd_indexPathHeightCache buildSectionsIfNeeded:section]; + [self.fd_indexPathHeightCache enumerateAllOrientationsUsingBlock:^(FDIndexPathHeightsBySection *heightsBySection) { + [heightsBySection[section] removeAllObjects]; + }]; + + }]; + } + FDPrimaryCall([self fd_reloadSections:sections withRowAnimation:animation];); +} + +- (void)fd_moveSection:(NSInteger)section toSection:(NSInteger)newSection { + if (self.fd_indexPathHeightCache.automaticallyInvalidateEnabled) { + [self.fd_indexPathHeightCache buildSectionsIfNeeded:section]; + [self.fd_indexPathHeightCache buildSectionsIfNeeded:newSection]; + [self.fd_indexPathHeightCache enumerateAllOrientationsUsingBlock:^(FDIndexPathHeightsBySection *heightsBySection) { + [heightsBySection exchangeObjectAtIndex:section withObjectAtIndex:newSection]; + }]; + } + FDPrimaryCall([self fd_moveSection:section toSection:newSection];); +} + +- (void)fd_insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation { + if (self.fd_indexPathHeightCache.automaticallyInvalidateEnabled) { + [self.fd_indexPathHeightCache buildCachesAtIndexPathsIfNeeded:indexPaths]; + [indexPaths enumerateObjectsUsingBlock:^(NSIndexPath *indexPath, NSUInteger idx, BOOL *stop) { + [self.fd_indexPathHeightCache enumerateAllOrientationsUsingBlock:^(FDIndexPathHeightsBySection *heightsBySection) { + [heightsBySection[indexPath.section] insertObject:@-1 atIndex:indexPath.row]; + }]; + }]; + } + FDPrimaryCall([self fd_insertRowsAtIndexPaths:indexPaths withRowAnimation:animation];); +} + +- (void)fd_deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation { + if (self.fd_indexPathHeightCache.automaticallyInvalidateEnabled) { + [self.fd_indexPathHeightCache buildCachesAtIndexPathsIfNeeded:indexPaths]; + + NSMutableDictionary *mutableIndexSetsToRemove = [NSMutableDictionary dictionary]; + [indexPaths enumerateObjectsUsingBlock:^(NSIndexPath *indexPath, NSUInteger idx, BOOL *stop) { + NSMutableIndexSet *mutableIndexSet = mutableIndexSetsToRemove[@(indexPath.section)]; + if (!mutableIndexSet) { + mutableIndexSet = [NSMutableIndexSet indexSet]; + mutableIndexSetsToRemove[@(indexPath.section)] = mutableIndexSet; + } + [mutableIndexSet addIndex:indexPath.row]; + }]; + + [mutableIndexSetsToRemove enumerateKeysAndObjectsUsingBlock:^(NSNumber *key, NSIndexSet *indexSet, BOOL *stop) { + [self.fd_indexPathHeightCache enumerateAllOrientationsUsingBlock:^(FDIndexPathHeightsBySection *heightsBySection) { + [heightsBySection[key.integerValue] removeObjectsAtIndexes:indexSet]; + }]; + }]; + } + FDPrimaryCall([self fd_deleteRowsAtIndexPaths:indexPaths withRowAnimation:animation];); +} + +- (void)fd_reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation { + if (self.fd_indexPathHeightCache.automaticallyInvalidateEnabled) { + [self.fd_indexPathHeightCache buildCachesAtIndexPathsIfNeeded:indexPaths]; + [indexPaths enumerateObjectsUsingBlock:^(NSIndexPath *indexPath, NSUInteger idx, BOOL *stop) { + [self.fd_indexPathHeightCache enumerateAllOrientationsUsingBlock:^(FDIndexPathHeightsBySection *heightsBySection) { + heightsBySection[indexPath.section][indexPath.row] = @-1; + }]; + }]; + } + FDPrimaryCall([self fd_reloadRowsAtIndexPaths:indexPaths withRowAnimation:animation];); +} + +- (void)fd_moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath { + if (self.fd_indexPathHeightCache.automaticallyInvalidateEnabled) { + [self.fd_indexPathHeightCache buildCachesAtIndexPathsIfNeeded:@[sourceIndexPath, destinationIndexPath]]; + [self.fd_indexPathHeightCache enumerateAllOrientationsUsingBlock:^(FDIndexPathHeightsBySection *heightsBySection) { + NSMutableArray *sourceRows = heightsBySection[sourceIndexPath.section]; + NSMutableArray *destinationRows = heightsBySection[destinationIndexPath.section]; + NSNumber *sourceValue = sourceRows[sourceIndexPath.row]; + NSNumber *destinationValue = destinationRows[destinationIndexPath.row]; + sourceRows[sourceIndexPath.row] = destinationValue; + destinationRows[destinationIndexPath.row] = sourceValue; + }]; + } + FDPrimaryCall([self fd_moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];); +} + +@end diff --git a/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDKeyedHeightCache.h b/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDKeyedHeightCache.h new file mode 100644 index 0000000..00c08de --- /dev/null +++ b/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDKeyedHeightCache.h @@ -0,0 +1,40 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2016 forkingdog ( https://github.com/forkingdog ) +// +// 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 + +@interface FDKeyedHeightCache : NSObject + +- (BOOL)existsHeightForKey:(id)key; +- (void)cacheHeight:(CGFloat)height byKey:(id)key; +- (CGFloat)heightForKey:(id)key; + +// Invalidation +- (void)invalidateHeightForKey:(id)key; +- (void)invalidateAllHeightCache; +@end + +@interface UITableView (FDKeyedHeightCache) + +/// Height cache by key. Generally, you don't need to use it directly. +@property (nonatomic, strong, readonly) FDKeyedHeightCache *fd_keyedHeightCache; +@end diff --git a/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDKeyedHeightCache.m b/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDKeyedHeightCache.m new file mode 100644 index 0000000..7d78d58 --- /dev/null +++ b/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDKeyedHeightCache.m @@ -0,0 +1,86 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2016 forkingdog ( https://github.com/forkingdog ) +// +// 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 "UITableView+FDKeyedHeightCache.h" +#import + +@interface FDKeyedHeightCache () +@property (nonatomic, strong) NSMutableDictionary, NSNumber *> *mutableHeightsByKeyForPortrait; +@property (nonatomic, strong) NSMutableDictionary, NSNumber *> *mutableHeightsByKeyForLandscape; +@end + +@implementation FDKeyedHeightCache + +- (instancetype)init { + self = [super init]; + if (self) { + _mutableHeightsByKeyForPortrait = [NSMutableDictionary dictionary]; + _mutableHeightsByKeyForLandscape = [NSMutableDictionary dictionary]; + } + return self; +} + +- (NSMutableDictionary, NSNumber *> *)mutableHeightsByKeyForCurrentOrientation { + return UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation) ? self.mutableHeightsByKeyForPortrait: self.mutableHeightsByKeyForLandscape; +} + +- (BOOL)existsHeightForKey:(id)key { + NSNumber *number = self.mutableHeightsByKeyForCurrentOrientation[key]; + return number && ![number isEqualToNumber:@-1]; +} + +- (void)cacheHeight:(CGFloat)height byKey:(id)key { + self.mutableHeightsByKeyForCurrentOrientation[key] = @(height); +} + +- (CGFloat)heightForKey:(id)key { +#if CGFLOAT_IS_DOUBLE + return [self.mutableHeightsByKeyForCurrentOrientation[key] doubleValue]; +#else + return [self.mutableHeightsByKeyForCurrentOrientation[key] floatValue]; +#endif +} + +- (void)invalidateHeightForKey:(id)key { + [self.mutableHeightsByKeyForPortrait removeObjectForKey:key]; + [self.mutableHeightsByKeyForLandscape removeObjectForKey:key]; +} + +- (void)invalidateAllHeightCache { + [self.mutableHeightsByKeyForPortrait removeAllObjects]; + [self.mutableHeightsByKeyForLandscape removeAllObjects]; +} + +@end + +@implementation UITableView (FDKeyedHeightCache) + +- (FDKeyedHeightCache *)fd_keyedHeightCache { + FDKeyedHeightCache *cache = objc_getAssociatedObject(self, _cmd); + if (!cache) { + cache = [FDKeyedHeightCache new]; + objc_setAssociatedObject(self, _cmd, cache, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return cache; +} + +@end diff --git a/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDTemplateLayoutCell.h b/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDTemplateLayoutCell.h new file mode 100644 index 0000000..ed628fc --- /dev/null +++ b/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDTemplateLayoutCell.h @@ -0,0 +1,108 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2016 forkingdog ( https://github.com/forkingdog ) +// +// 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 +#import "UITableView+FDKeyedHeightCache.h" +#import "UITableView+FDIndexPathHeightCache.h" +#import "UITableView+FDTemplateLayoutCellDebug.h" + +@interface UITableView (FDTemplateLayoutCell) + +/// Access to internal template layout cell for given reuse identifier. +/// Generally, you don't need to know these template layout cells. +/// +/// @param identifier Reuse identifier for cell which must be registered. +/// +- (__kindof UITableViewCell *)fd_templateCellForReuseIdentifier:(NSString *)identifier; + +/// Returns height of cell of type specifed by a reuse identifier and configured +/// by the configuration block. +/// +/// The cell would be layed out on a fixed-width, vertically expanding basis with +/// respect to its dynamic content, using auto layout. Thus, it is imperative that +/// the cell was set up to be self-satisfied, i.e. its content always determines +/// its height given the width is equal to the tableview's. +/// +/// @param identifier A string identifier for retrieving and maintaining template +/// cells with system's "-dequeueReusableCellWithIdentifier:" call. +/// @param configuration An optional block for configuring and providing content +/// to the template cell. The configuration should be minimal for scrolling +/// performance yet sufficient for calculating cell's height. +/// +- (CGFloat)fd_heightForCellWithIdentifier:(NSString *)identifier configuration:(void (^)(id cell))configuration; + +/// This method does what "-fd_heightForCellWithIdentifier:configuration" does, and +/// calculated height will be cached by its index path, returns a cached height +/// when needed. Therefore lots of extra height calculations could be saved. +/// +/// No need to worry about invalidating cached heights when data source changes, it +/// will be done automatically when you call "-reloadData" or any method that triggers +/// UITableView's reloading. +/// +/// @param indexPath where this cell's height cache belongs. +/// +- (CGFloat)fd_heightForCellWithIdentifier:(NSString *)identifier cacheByIndexPath:(NSIndexPath *)indexPath configuration:(void (^)(id cell))configuration; + +/// This method caches height by your model entity's identifier. +/// If your model's changed, call "-invalidateHeightForKey:(id )key" to +/// invalidate cache and re-calculate, it's much cheaper and effective than "cacheByIndexPath". +/// +/// @param key model entity's identifier whose data configures a cell. +/// +- (CGFloat)fd_heightForCellWithIdentifier:(NSString *)identifier cacheByKey:(id)key configuration:(void (^)(id cell))configuration; + +@end + +@interface UITableView (FDTemplateLayoutHeaderFooterView) + +/// Returns header or footer view's height that registered in table view with reuse identifier. +/// +/// Use it after calling "-[UITableView registerNib/Class:forHeaderFooterViewReuseIdentifier]", +/// same with "-fd_heightForCellWithIdentifier:configuration:", it will call "-sizeThatFits:" for +/// subclass of UITableViewHeaderFooterView which is not using Auto Layout. +/// +- (CGFloat)fd_heightForHeaderFooterViewWithIdentifier:(NSString *)identifier configuration:(void (^)(id headerFooterView))configuration; + +@end + +@interface UITableViewCell (FDTemplateLayoutCell) + +/// Indicate this is a template layout cell for calculation only. +/// You may need this when there are non-UI side effects when configure a cell. +/// Like: +/// - (void)configureCell:(FooCell *)cell atIndexPath:(NSIndexPath *)indexPath { +/// cell.entity = [self entityAtIndexPath:indexPath]; +/// if (!cell.fd_isTemplateLayoutCell) { +/// [self notifySomething]; // non-UI side effects +/// } +/// } +/// +@property (nonatomic, assign) BOOL fd_isTemplateLayoutCell; + +/// Enable to enforce this template layout cell to use "frame layout" rather than "auto layout", +/// and will ask cell's height by calling "-sizeThatFits:", so you must override this method. +/// Use this property only when you want to manually control this template layout cell's height +/// calculation mode, default to NO. +/// +@property (nonatomic, assign) BOOL fd_enforceFrameLayout; + +@end diff --git a/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDTemplateLayoutCell.m b/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDTemplateLayoutCell.m new file mode 100644 index 0000000..f21752b --- /dev/null +++ b/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDTemplateLayoutCell.m @@ -0,0 +1,266 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2016 forkingdog ( https://github.com/forkingdog ) +// +// 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 "UITableView+FDTemplateLayoutCell.h" +#import + +@implementation UITableView (FDTemplateLayoutCell) + +- (CGFloat)fd_systemFittingHeightForConfiguratedCell:(UITableViewCell *)cell { + CGFloat contentViewWidth = CGRectGetWidth(self.frame); + + // If a cell has accessory view or system accessory type, its content view's width is smaller + // than cell's by some fixed values. + if (cell.accessoryView) { + contentViewWidth -= 16 + CGRectGetWidth(cell.accessoryView.frame); + } else { + static const CGFloat systemAccessoryWidths[] = { + [UITableViewCellAccessoryNone] = 0, + [UITableViewCellAccessoryDisclosureIndicator] = 34, + [UITableViewCellAccessoryDetailDisclosureButton] = 68, + [UITableViewCellAccessoryCheckmark] = 40, + [UITableViewCellAccessoryDetailButton] = 48 + }; + contentViewWidth -= systemAccessoryWidths[cell.accessoryType]; + } + + // If not using auto layout, you have to override "-sizeThatFits:" to provide a fitting size by yourself. + // This is the same height calculation passes used in iOS8 self-sizing cell's implementation. + // + // 1. Try "- systemLayoutSizeFittingSize:" first. (skip this step if 'fd_enforceFrameLayout' set to YES.) + // 2. Warning once if step 1 still returns 0 when using AutoLayout + // 3. Try "- sizeThatFits:" if step 1 returns 0 + // 4. Use a valid height or default row height (44) if not exist one + + CGFloat fittingHeight = 0; + + if (!cell.fd_enforceFrameLayout && contentViewWidth > 0) { + // Add a hard width constraint to make dynamic content views (like labels) expand vertically instead + // of growing horizontally, in a flow-layout manner. + NSLayoutConstraint *widthFenceConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:contentViewWidth]; + + // [bug fix] after iOS 10.3, Auto Layout engine will add an additional 0 width constraint onto cell's content view, to avoid that, we add constraints to content view's left, right, top and bottom. + static BOOL isSystemVersionEqualOrGreaterThen10_2 = NO; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + isSystemVersionEqualOrGreaterThen10_2 = [UIDevice.currentDevice.systemVersion compare:@"10.2" options:NSNumericSearch] != NSOrderedAscending; + }); + + NSArray *edgeConstraints; + if (isSystemVersionEqualOrGreaterThen10_2) { + // To avoid confilicts, make width constraint softer than required (1000) + widthFenceConstraint.priority = UILayoutPriorityRequired - 1; + + // Build edge constraints + NSLayoutConstraint *leftConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeLeft multiplier:1.0 constant:0]; + NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeRight multiplier:1.0 constant:0]; + NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]; + NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]; + edgeConstraints = @[leftConstraint, rightConstraint, topConstraint, bottomConstraint]; + [cell addConstraints:edgeConstraints]; + } + + [cell.contentView addConstraint:widthFenceConstraint]; + + // Auto layout engine does its math + fittingHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height; + + // Clean-ups + [cell.contentView removeConstraint:widthFenceConstraint]; + if (isSystemVersionEqualOrGreaterThen10_2) { + [cell removeConstraints:edgeConstraints]; + } + + [self fd_debugLog:[NSString stringWithFormat:@"calculate using system fitting size (AutoLayout) - %@", @(fittingHeight)]]; + } + + if (fittingHeight == 0) { +#if DEBUG + // Warn if using AutoLayout but get zero height. + if (cell.contentView.constraints.count > 0) { + if (!objc_getAssociatedObject(self, _cmd)) { + NSLog(@"[FDTemplateLayoutCell] Warning once only: Cannot get a proper cell height (now 0) from '- systemFittingSize:'(AutoLayout). You should check how constraints are built in cell, making it into 'self-sizing' cell."); + objc_setAssociatedObject(self, _cmd, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + } +#endif + // Try '- sizeThatFits:' for frame layout. + // Note: fitting height should not include separator view. + fittingHeight = [cell sizeThatFits:CGSizeMake(contentViewWidth, 0)].height; + + [self fd_debugLog:[NSString stringWithFormat:@"calculate using sizeThatFits - %@", @(fittingHeight)]]; + } + + // Still zero height after all above. + if (fittingHeight == 0) { + // Use default row height. + fittingHeight = 44; + } + + // Add 1px extra space for separator line if needed, simulating default UITableViewCell. + if (self.separatorStyle != UITableViewCellSeparatorStyleNone) { + fittingHeight += 1.0 / [UIScreen mainScreen].scale; + } + + return fittingHeight; +} + +- (__kindof UITableViewCell *)fd_templateCellForReuseIdentifier:(NSString *)identifier { + NSAssert(identifier.length > 0, @"Expect a valid identifier - %@", identifier); + + NSMutableDictionary *templateCellsByIdentifiers = objc_getAssociatedObject(self, _cmd); + if (!templateCellsByIdentifiers) { + templateCellsByIdentifiers = @{}.mutableCopy; + objc_setAssociatedObject(self, _cmd, templateCellsByIdentifiers, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + + UITableViewCell *templateCell = templateCellsByIdentifiers[identifier]; + + if (!templateCell) { + templateCell = [self dequeueReusableCellWithIdentifier:identifier]; + NSAssert(templateCell != nil, @"Cell must be registered to table view for identifier - %@", identifier); + templateCell.fd_isTemplateLayoutCell = YES; + templateCell.contentView.translatesAutoresizingMaskIntoConstraints = NO; + templateCellsByIdentifiers[identifier] = templateCell; + [self fd_debugLog:[NSString stringWithFormat:@"layout cell created - %@", identifier]]; + } + + return templateCell; +} + +- (CGFloat)fd_heightForCellWithIdentifier:(NSString *)identifier configuration:(void (^)(id cell))configuration { + if (!identifier) { + return 0; + } + + UITableViewCell *templateLayoutCell = [self fd_templateCellForReuseIdentifier:identifier]; + + // Manually calls to ensure consistent behavior with actual cells. (that are displayed on screen) + [templateLayoutCell prepareForReuse]; + + // Customize and provide content for our template cell. + if (configuration) { + configuration(templateLayoutCell); + } + + return [self fd_systemFittingHeightForConfiguratedCell:templateLayoutCell]; +} + +- (CGFloat)fd_heightForCellWithIdentifier:(NSString *)identifier cacheByIndexPath:(NSIndexPath *)indexPath configuration:(void (^)(id cell))configuration { + if (!identifier || !indexPath) { + return 0; + } + + // Hit cache + if ([self.fd_indexPathHeightCache existsHeightAtIndexPath:indexPath]) { + [self fd_debugLog:[NSString stringWithFormat:@"hit cache by index path[%@:%@] - %@", @(indexPath.section), @(indexPath.row), @([self.fd_indexPathHeightCache heightForIndexPath:indexPath])]]; + return [self.fd_indexPathHeightCache heightForIndexPath:indexPath]; + } + + CGFloat height = [self fd_heightForCellWithIdentifier:identifier configuration:configuration]; + [self.fd_indexPathHeightCache cacheHeight:height byIndexPath:indexPath]; + [self fd_debugLog:[NSString stringWithFormat: @"cached by index path[%@:%@] - %@", @(indexPath.section), @(indexPath.row), @(height)]]; + + return height; +} + +- (CGFloat)fd_heightForCellWithIdentifier:(NSString *)identifier cacheByKey:(id)key configuration:(void (^)(id cell))configuration { + if (!identifier || !key) { + return 0; + } + + // Hit cache + if ([self.fd_keyedHeightCache existsHeightForKey:key]) { + CGFloat cachedHeight = [self.fd_keyedHeightCache heightForKey:key]; + [self fd_debugLog:[NSString stringWithFormat:@"hit cache by key[%@] - %@", key, @(cachedHeight)]]; + return cachedHeight; + } + + CGFloat height = [self fd_heightForCellWithIdentifier:identifier configuration:configuration]; + [self.fd_keyedHeightCache cacheHeight:height byKey:key]; + [self fd_debugLog:[NSString stringWithFormat:@"cached by key[%@] - %@", key, @(height)]]; + + return height; +} + +@end + +@implementation UITableView (FDTemplateLayoutHeaderFooterView) + +- (__kindof UITableViewHeaderFooterView *)fd_templateHeaderFooterViewForReuseIdentifier:(NSString *)identifier { + NSAssert(identifier.length > 0, @"Expect a valid identifier - %@", identifier); + + NSMutableDictionary *templateHeaderFooterViews = objc_getAssociatedObject(self, _cmd); + if (!templateHeaderFooterViews) { + templateHeaderFooterViews = @{}.mutableCopy; + objc_setAssociatedObject(self, _cmd, templateHeaderFooterViews, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + + UITableViewHeaderFooterView *templateHeaderFooterView = templateHeaderFooterViews[identifier]; + + if (!templateHeaderFooterView) { + templateHeaderFooterView = [self dequeueReusableHeaderFooterViewWithIdentifier:identifier]; + NSAssert(templateHeaderFooterView != nil, @"HeaderFooterView must be registered to table view for identifier - %@", identifier); + templateHeaderFooterView.contentView.translatesAutoresizingMaskIntoConstraints = NO; + templateHeaderFooterViews[identifier] = templateHeaderFooterView; + [self fd_debugLog:[NSString stringWithFormat:@"layout header footer view created - %@", identifier]]; + } + + return templateHeaderFooterView; +} + +- (CGFloat)fd_heightForHeaderFooterViewWithIdentifier:(NSString *)identifier configuration:(void (^)(id))configuration { + UITableViewHeaderFooterView *templateHeaderFooterView = [self fd_templateHeaderFooterViewForReuseIdentifier:identifier]; + + NSLayoutConstraint *widthFenceConstraint = [NSLayoutConstraint constraintWithItem:templateHeaderFooterView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:CGRectGetWidth(self.frame)]; + [templateHeaderFooterView addConstraint:widthFenceConstraint]; + CGFloat fittingHeight = [templateHeaderFooterView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height; + [templateHeaderFooterView removeConstraint:widthFenceConstraint]; + + if (fittingHeight == 0) { + fittingHeight = [templateHeaderFooterView sizeThatFits:CGSizeMake(CGRectGetWidth(self.frame), 0)].height; + } + + return fittingHeight; +} + +@end + +@implementation UITableViewCell (FDTemplateLayoutCell) + +- (BOOL)fd_isTemplateLayoutCell { + return [objc_getAssociatedObject(self, _cmd) boolValue]; +} + +- (void)setFd_isTemplateLayoutCell:(BOOL)isTemplateLayoutCell { + objc_setAssociatedObject(self, @selector(fd_isTemplateLayoutCell), @(isTemplateLayoutCell), OBJC_ASSOCIATION_RETAIN); +} + +- (BOOL)fd_enforceFrameLayout { + return [objc_getAssociatedObject(self, _cmd) boolValue]; +} + +- (void)setFd_enforceFrameLayout:(BOOL)enforceFrameLayout { + objc_setAssociatedObject(self, @selector(fd_enforceFrameLayout), @(enforceFrameLayout), OBJC_ASSOCIATION_RETAIN); +} + +@end diff --git a/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDTemplateLayoutCellDebug.h b/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDTemplateLayoutCellDebug.h new file mode 100644 index 0000000..ddd0d50 --- /dev/null +++ b/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDTemplateLayoutCellDebug.h @@ -0,0 +1,37 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2016 forkingdog ( https://github.com/forkingdog ) +// +// 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 + +@interface UITableView (FDTemplateLayoutCellDebug) + +/// Helps to debug or inspect what is this "FDTemplateLayoutCell" extention doing, +/// turning on to print logs when "creating", "calculating", "precaching" or "hitting cache". +/// +/// Default to NO, log by NSLog. +/// +@property (nonatomic, assign) BOOL fd_debugLogEnabled; + +/// Debug log controlled by "fd_debugLogEnabled". +- (void)fd_debugLog:(NSString *)message; + +@end diff --git a/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDTemplateLayoutCellDebug.m b/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDTemplateLayoutCellDebug.m new file mode 100644 index 0000000..4af2aad --- /dev/null +++ b/Pods/UITableView+FDTemplateLayoutCell/Classes/UITableView+FDTemplateLayoutCellDebug.m @@ -0,0 +1,42 @@ +// The MIT License (MIT) +// +// Copyright (c) 2015-2016 forkingdog ( https://github.com/forkingdog ) +// +// 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 "UITableView+FDTemplateLayoutCellDebug.h" +#import + +@implementation UITableView (FDTemplateLayoutCellDebug) + +- (BOOL)fd_debugLogEnabled { + return [objc_getAssociatedObject(self, _cmd) boolValue]; +} + +- (void)setFd_debugLogEnabled:(BOOL)debugLogEnabled { + objc_setAssociatedObject(self, @selector(fd_debugLogEnabled), @(debugLogEnabled), OBJC_ASSOCIATION_RETAIN); +} + +- (void)fd_debugLog:(NSString *)message { + if (self.fd_debugLogEnabled) { + NSLog(@"** FDTemplateLayoutCell ** %@", message); + } +} + +@end diff --git a/Pods/UITableView+FDTemplateLayoutCell/LICENSE b/Pods/UITableView+FDTemplateLayoutCell/LICENSE new file mode 100644 index 0000000..20efd1b --- /dev/null +++ b/Pods/UITableView+FDTemplateLayoutCell/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/Pods/UITableView+FDTemplateLayoutCell/README.md b/Pods/UITableView+FDTemplateLayoutCell/README.md new file mode 100644 index 0000000..16525f4 --- /dev/null +++ b/Pods/UITableView+FDTemplateLayoutCell/README.md @@ -0,0 +1,154 @@ +# UITableView-FDTemplateLayoutCell + + +## Overview +Template auto layout cell for **automatically** UITableViewCell height calculating. + +![Demo Overview](https://github.com/forkingdog/UITableView-FDTemplateLayoutCell/blob/master/Sceenshots/screenshot2.gif) + +## Basic usage + +If you have a **self-satisfied** cell, then all you have to do is: + +``` objc +#import "UITableView+FDTemplateLayoutCell.h" + +- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath +{ + return [tableView fd_heightForCellWithIdentifier:@"reuse identifer" configuration:^(id cell) { + // Configure this cell with data, same as what you've done in "-tableView:cellForRowAtIndexPath:" + // Like: + // cell.entity = self.feedEntities[indexPath.row]; + }]; +} +``` + +## Height Caching API + +Since iOS8, `-tableView:heightForRowAtIndexPath:` will be called more times than we expect, we can feel these extra calculations when scrolling. So we provide another API with cache by index path: + +``` objc +- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { + return [tableView fd_heightForCellWithIdentifier:@"identifer" cacheByIndexPath:indexPath configuration:^(id cell) { + // configurations + }]; +} +``` + +Or, if your entity has an unique identifier, use cache by key API: + +``` objc +- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { + Entity *entity = self.entities[indexPath.row]; + return [tableView fd_heightForCellWithIdentifier:@"identifer" cacheByKey:entity.uid configuration:^(id cell) { + // configurations + }]; +} +``` + +## Frame layout mode + +`FDTemplateLayoutCell` offers 2 modes for asking cell's height. + +1. Auto layout mode using "-systemLayoutSizeFittingSize:" +2. Frame layout mode using "-sizeThatFits:" + +Generally, no need to care about modes, it will **automatically** choose a proper mode by whether you have set auto layout constrants on cell's content view. If you want to enforce frame layout mode, enable this property in your cell's configuration block: + +``` objc +cell.fd_enforceFrameLayout = YES; +``` +And if you're using frame layout mode, you must override `-sizeThatFits:` in your customized cell and return content view's height (separator excluded) + +``` +- (CGSize)sizeThatFits:(CGSize)size { + return CGSizeMake(size.width, A+B+C+D+E+....); +} +``` + +## Debug log + +Debug log helps to debug or inspect what is this "FDTemplateLayoutCell" extention doing, turning on to print logs when "calculating", "precaching" or "hitting cache".Default to "NO", log by "NSLog". + +``` objc +self.tableView.fd_debugLogEnabled = YES; +``` + +It will print like this: + +``` objc +** FDTemplateLayoutCell ** layout cell created - FDFeedCell +** FDTemplateLayoutCell ** calculate - [0:0] 233.5 +** FDTemplateLayoutCell ** calculate - [0:1] 155.5 +** FDTemplateLayoutCell ** calculate - [0:2] 258 +** FDTemplateLayoutCell ** calculate - [0:3] 284 +** FDTemplateLayoutCell ** precached - [0:3] 284 +** FDTemplateLayoutCell ** calculate - [0:4] 278.5 +** FDTemplateLayoutCell ** precached - [0:4] 278.5 +** FDTemplateLayoutCell ** hit cache - [0:3] 284 +** FDTemplateLayoutCell ** hit cache - [0:4] 278.5 +** FDTemplateLayoutCell ** hit cache - [0:5] 156 +** FDTemplateLayoutCell ** hit cache - [0:6] 165 +``` + +## About self-satisfied cell + +a fully **self-satisfied** cell is constrainted by auto layout and each edge("top", "left", "bottom", "right") has at least one layout constraint against it. It's the same concept introduced as "self-sizing cell" in iOS8 using auto layout. + +A bad one :( - missing right and bottom +![non-self-satisfied](https://github.com/forkingdog/UITableView-FDTemplateLayoutCell/blob/master/Sceenshots/screenshot0.png) + +A good one :) +![self-satisfied](https://github.com/forkingdog/UITableView-FDTemplateLayoutCell/blob/master/Sceenshots/screenshot1.png) + +## Notes + +A template layout cell is created by `-dequeueReusableCellWithIdentifier:` method, it means that you MUST have registered this cell reuse identifier by one of: + +- A prototype cell of UITableView in storyboard. +- Use `-registerNib:forCellReuseIdentifier:` +- Use `-registerClass:forCellReuseIdentifier:` + +## 如果你在天朝 +可以看这篇中文博客: +[http://blog.sunnyxx.com/2015/05/17/cell-height-calculation/](http://blog.sunnyxx.com/2015/05/17/cell-height-calculation/) + +## Installation + +Latest version: **1.6** + +``` +pod search UITableView+FDTemplateLayoutCell +``` +If you cannot search out the latest version, try: + +``` +pod setup +``` + +## Release Notes + +We recommend to use the latest release in cocoapods. + +- 1.6 +fix bug in iOS 10 + +- 1.4 +Refactor, add "cacheByKey" mode, bug fixed + +- 1.3 +Frame layout mode, handle cell's accessory view/type + +- 1.2 +Precache and auto cache invalidation + +- 1.1 +Height cache + +- 1.0 +Basic automatically height calculation + +## License +MIT + + diff --git a/Pods/WechatOpenSDK/WechatSDK1.8.2/WXApi.h b/Pods/WechatOpenSDK/WechatSDK1.8.2/WXApi.h new file mode 100644 index 0000000..739cbf9 --- /dev/null +++ b/Pods/WechatOpenSDK/WechatSDK1.8.2/WXApi.h @@ -0,0 +1,193 @@ +// +// WXApi.h +// 所有Api接口 +// +// Created by Wechat on 12-2-28. +// Copyright (c) 2012年 Tencent. All rights reserved. +// + +#import +#import "WXApiObject.h" + + +#pragma mark - WXApiDelegate +/*! @brief 接收并处理来自微信终端程序的事件消息 + * + * 接收并处理来自微信终端程序的事件消息,期间微信界面会切换到第三方应用程序。 + * WXApiDelegate 会在handleOpenURL:delegate:中使用并触发。 + */ +@protocol WXApiDelegate +@optional + +/*! @brief 收到一个来自微信的请求,第三方应用程序处理完后调用sendResp向微信发送结果 + * + * 收到一个来自微信的请求,异步处理完成后必须调用sendResp发送处理结果给微信。 + * 可能收到的请求有GetMessageFromWXReq、ShowMessageFromWXReq等。 + * @param req 具体请求内容,是自动释放的 + */ +-(void) onReq:(BaseReq*)req; + + + +/*! @brief 发送一个sendReq后,收到微信的回应 + * + * 收到一个来自微信的处理结果。调用一次sendReq后会收到onResp。 + * 可能收到的处理结果有SendMessageToWXResp、SendAuthResp等。 + * @param resp具体的回应内容,是自动释放的 + */ +-(void) onResp:(BaseResp*)resp; + +@end + +#pragma mark - WXApiLogDelegate + +@protocol WXApiLogDelegate + +-(void) onLog:(NSString*)log logLevel:(WXLogLevel)level; + +@end + +#pragma mark - WXApi + +/*! @brief 微信Api接口函数类 + * + * 该类封装了微信终端SDK的所有接口 + */ +@interface WXApi : NSObject + +/*! @brief WXApi的成员函数,向微信终端程序注册第三方应用。 + * + * 需要在每次启动第三方应用程序时调用。第一次调用后,会在微信的可用应用列表中出现,默认开启MTA数据上报。 + * iOS7及以上系统需要调起一次微信才会出现在微信的可用应用列表中。 + * @attention 请保证在主线程中调用此函数 + * @param appid 微信开发者ID + * @param typeFlag 应用支持打开的文件类型 + * @return 成功返回YES,失败返回NO。 + */ ++(BOOL) registerApp:(NSString *)appid; + +/*! @brief WXApi的成员函数,向微信终端程序注册第三方应用。 + * + * 需要在每次启动第三方应用程序时调用。第一次调用后,会在微信的可用应用列表中出现。 + * iOS7及以上系统需要调起一次微信才会出现在微信的可用应用列表中。 + * @attention 请保证在主线程中调用此函数 + * @param appid 微信开发者ID + * @param isEnableMTA 是否支持MTA数据上报 + * @return 成功返回YES,失败返回NO。 + */ ++(BOOL) registerApp:(NSString *)appid enableMTA:(BOOL)isEnableMTA; + + +/*! @brief WXApi的成员函数,向微信终端程序注册应用支持打开的文件类型。 + * + * 需要在每次启动第三方应用程序时调用。调用后并第一次成功分享数据到微信后,会在微信的可用应用列表中出现。 + * @see registerApp + * @param typeFlag 应用支持打开的数据类型, enAppSupportContentFlag枚举类型 “|” 操作后结果 + */ ++(void) registerAppSupportContentFlag:(UInt64)typeFlag; + + + +/*! @brief 处理微信通过URL启动App时传递的数据 + * + * 需要在 application:openURL:sourceApplication:annotation:或者application:handleOpenURL中调用。 + * @param url 微信启动第三方应用时传递过来的URL + * @param delegate WXApiDelegate对象,用来接收微信触发的消息。 + * @return 成功返回YES,失败返回NO。 + */ ++(BOOL) handleOpenURL:(NSURL *) url delegate:(id) delegate; + + + +/*! @brief 检查微信是否已被用户安装 + * + * @return 微信已安装返回YES,未安装返回NO。 + */ ++(BOOL) isWXAppInstalled; + + + +/*! @brief 判断当前微信的版本是否支持OpenApi + * + * @return 支持返回YES,不支持返回NO。 + */ ++(BOOL) isWXAppSupportApi; + + + +/*! @brief 获取微信的itunes安装地址 + * + * @return 微信的安装地址字符串。 + */ ++(NSString *) getWXAppInstallUrl; + + + +/*! @brief 获取当前微信SDK的版本号 + * + * @return 返回当前微信SDK的版本号 + */ ++(NSString *) getApiVersion; + + + +/*! @brief 打开微信 + * + * @return 成功返回YES,失败返回NO。 + */ ++(BOOL) openWXApp; + + + +/*! @brief 发送请求到微信,等待微信返回onResp + * + * 函数调用后,会切换到微信的界面。第三方应用程序等待微信返回onResp。微信在异步处理完成后一定会调用onResp。支持以下类型 + * SendAuthReq、SendMessageToWXReq、PayReq等。 + * @param req 具体的发送请求,在调用函数后,请自己释放。 + * @return 成功返回YES,失败返回NO。 + */ ++(BOOL) sendReq:(BaseReq*)req; + +/*! @brief 发送Auth请求到微信,支持用户没安装微信,等待微信返回onResp + * + * 函数调用后,会切换到微信的界面。第三方应用程序等待微信返回onResp。微信在异步处理完成后一定会调用onResp。支持SendAuthReq类型。 + * @param req 具体的发送请求,在调用函数后,请自己释放。 + * @param viewController 当前界面对象。 + * @param delegate WXApiDelegate对象,用来接收微信触发的消息。 + * @return 成功返回YES,失败返回NO。 + */ ++(BOOL) sendAuthReq:(SendAuthReq*)req viewController:(UIViewController*)viewController delegate:(id)delegate; + + +/*! @brief 收到微信onReq的请求,发送对应的应答给微信,并切换到微信界面 + * + * 函数调用后,会切换到微信的界面。第三方应用程序收到微信onReq的请求,异步处理该请求,完成后必须调用该函数。可能发送的相应有 + * GetMessageFromWXResp、ShowMessageFromWXResp等。 + * @param resp 具体的应答内容,调用函数后,请自己释放 + * @return 成功返回YES,失败返回NO。 + */ ++(BOOL) sendResp:(BaseResp*)resp; + + +/*! @brief WXApi的成员函数,接受微信的log信息。byBlock + 注意1:SDK会强引用这个block,注意不要导致内存泄漏,注意不要导致内存泄漏 + 注意2:调用过一次startLog by block之后,如果再调用一次任意方式的startLoad,会释放上一次logBlock,不再回调上一个logBlock + * + * @param level 打印log的级别 + * @param logBlock 打印log的回调block + */ ++(void) startLogByLevel:(WXLogLevel)level logBlock:(WXLogBolock)logBlock; + +/*! @brief WXApi的成员函数,接受微信的log信息。byDelegate + 注意1:sdk会弱引用这个delegate,这里可加任意对象为代理,不需要与WXApiDelegate同一个对象 + 注意2:调用过一次startLog by delegate之后,再调用一次任意方式的startLoad,不会再回调上一个logDelegate对象 + * @param level 打印log的级别 + * @param logDelegate 打印log的回调代理, + */ ++ (void)startLogByLevel:(WXLogLevel)level logDelegate:(id)logDelegate; + +/*! @brief 停止打印log,会清理block或者delegate为空,释放block + * @param + */ ++ (void)stopLog; +@end diff --git a/Pods/WechatOpenSDK/WechatSDK1.8.2/WXApiObject.h b/Pods/WechatOpenSDK/WechatSDK1.8.2/WXApiObject.h new file mode 100644 index 0000000..8ec14c8 --- /dev/null +++ b/Pods/WechatOpenSDK/WechatSDK1.8.2/WXApiObject.h @@ -0,0 +1,959 @@ +// +// MMApiObject.h +// Api对象,包含所有接口和对象数据定义 +// +// Created by Wechat on 12-2-28. +// Copyright (c) 2012年 Tencent. All rights reserved. +// + +#import +#import +/*! @brief 错误码 + * + */ +enum WXErrCode { + WXSuccess = 0, /**< 成功 */ + WXErrCodeCommon = -1, /**< 普通错误类型 */ + WXErrCodeUserCancel = -2, /**< 用户点击取消并返回 */ + WXErrCodeSentFail = -3, /**< 发送失败 */ + WXErrCodeAuthDeny = -4, /**< 授权失败 */ + WXErrCodeUnsupport = -5, /**< 微信不支持 */ +}; + + + +/*! @brief 请求发送场景 + * + */ +enum WXScene { + WXSceneSession = 0, /**< 聊天界面 */ + WXSceneTimeline = 1, /**< 朋友圈 */ + WXSceneFavorite = 2, /**< 收藏 */ +}; + + + +enum WXAPISupport { + WXAPISupportSession = 0, +}; + + + +/*! @brief 跳转profile类型 + * + */ +enum WXBizProfileType{ + WXBizProfileType_Normal = 0, //**< 普通公众号 */ + WXBizProfileType_Device = 1, //**< 硬件公众号 */ +}; + +/*! @brief 分享小程序类型 + * + */ +typedef NS_ENUM(NSUInteger, WXMiniProgramType){ + WXMiniProgramTypeRelease = 0, //**< 正式版 */ + WXMiniProgramTypeTest = 1, //**< 开发版 */ + WXMiniProgramTypePreview = 2, //**< 体验版 */ +}; + +/*! @brief 跳转mp网页类型 + * + */ +enum WXMPWebviewType { + WXMPWebviewType_Ad = 0, /**< 广告网页 **/ +}; + + + +/*! @brief 应用支持接收微信的文件类型 + * + */ +typedef NS_ENUM(UInt64, enAppSupportContentFlag) +{ + MMAPP_SUPPORT_NOCONTENT = 0x0, + MMAPP_SUPPORT_TEXT = 0x1, + MMAPP_SUPPORT_PICTURE = 0x2, + MMAPP_SUPPORT_LOCATION = 0x4, + MMAPP_SUPPORT_VIDEO = 0x8, + MMAPP_SUPPORT_AUDIO = 0x10, + MMAPP_SUPPORT_WEBPAGE = 0x20, + + // Suport File Type + MMAPP_SUPPORT_DOC = 0x40, // doc + MMAPP_SUPPORT_DOCX = 0x80, // docx + MMAPP_SUPPORT_PPT = 0x100, // ppt + MMAPP_SUPPORT_PPTX = 0x200, // pptx + MMAPP_SUPPORT_XLS = 0x400, // xls + MMAPP_SUPPORT_XLSX = 0x800, // xlsx + MMAPP_SUPPORT_PDF = 0x1000, // pdf +}; + +/*! @brief log的级别 + * + */ +typedef NS_ENUM(NSInteger,WXLogLevel){ + WXLogLevelNormal = 0, // 打印日常的日志 + WXLogLevelDetail = 1, // 打印详细的日志 +}; + + +/*! @brief 打印回调的block + * + */ +typedef void(^WXLogBolock)(NSString * log); + +#pragma mark - BaseReq +/*! @brief 该类为微信终端SDK所有请求类的基类 + * + */ +@interface BaseReq : NSObject + +/** 请求类型 */ +@property (nonatomic, assign) int type; +/** 由用户微信号和AppID组成的唯一标识,发送请求时第三方程序必须填写,用于校验微信用户是否换号登录*/ +@property (nonatomic, retain) NSString* openID; + +@end + + + +#pragma mark - BaseResp +/*! @brief 该类为微信终端SDK所有响应类的基类 + * + */ +@interface BaseResp : NSObject +/** 错误码 */ +@property (nonatomic, assign) int errCode; +/** 错误提示字符串 */ +@property (nonatomic, retain) NSString *errStr; +/** 响应类型 */ +@property (nonatomic, assign) int type; + +@end + + + +#pragma mark - WXMediaMessage +@class WXMediaMessage; + +#ifndef BUILD_WITHOUT_PAY + +/*! @brief 第三方向微信终端发起支付的消息结构体 + * + * 第三方向微信终端发起支付的消息结构体,微信终端处理后会向第三方返回处理结果 + * @see PayResp + */ +@interface PayReq : BaseReq + +/** 商家向财付通申请的商家id */ +@property (nonatomic, retain) NSString *partnerId; +/** 预支付订单 */ +@property (nonatomic, retain) NSString *prepayId; +/** 随机串,防重发 */ +@property (nonatomic, retain) NSString *nonceStr; +/** 时间戳,防重发 */ +@property (nonatomic, assign) UInt32 timeStamp; +/** 商家根据财付通文档填写的数据和签名 */ +@property (nonatomic, retain) NSString *package; +/** 商家根据微信开放平台文档对数据做的签名 */ +@property (nonatomic, retain) NSString *sign; + +@end + +#endif + + +#ifndef BUILD_WITHOUT_PAY + +#pragma mark - PayResp +/*! @brief 微信终端返回给第三方的关于支付结果的结构体 + * + * 微信终端返回给第三方的关于支付结果的结构体 + */ +@interface PayResp : BaseResp + +/** 财付通返回给商家的信息 */ +@property (nonatomic, retain) NSString *returnKey; + +@end + +#endif + + + +#pragma mark - SendAuthReq +/*! @brief 第三方程序向微信终端请求认证的消息结构 + * + * 第三方程序要向微信申请认证,并请求某些权限,需要调用WXApi的sendReq成员函数, + * 向微信终端发送一个SendAuthReq消息结构。微信终端处理完后会向第三方程序发送一个处理结果。 + * @see SendAuthResp + */ +@interface SendAuthReq : BaseReq +/** 第三方程序要向微信申请认证,并请求某些权限,需要调用WXApi的sendReq成员函数,向微信终端发送一个SendAuthReq消息结构。微信终端处理完后会向第三方程序发送一个处理结果。 + * @see SendAuthResp + * @note scope字符串长度不能超过1K + */ +@property (nonatomic, retain) NSString* scope; +/** 第三方程序本身用来标识其请求的唯一性,最后跳转回第三方程序时,由微信终端回传。 + * @note state字符串长度不能超过1K + */ +@property (nonatomic, retain) NSString* state; +@end + + + +#pragma mark - SendAuthResp +/*! @brief 微信处理完第三方程序的认证和权限申请后向第三方程序回送的处理结果。 + * + * 第三方程序要向微信申请认证,并请求某些权限,需要调用WXApi的sendReq成员函数,向微信终端发送一个SendAuthReq消息结构。 + * 微信终端处理完后会向第三方程序发送一个SendAuthResp。 + * @see onResp + */ +@interface SendAuthResp : BaseResp +@property (nonatomic, retain) NSString* code; +/** 第三方程序发送时用来标识其请求的唯一性的标志,由第三方程序调用sendReq时传入,由微信终端回传 + * @note state字符串长度不能超过1K + */ +@property (nonatomic, retain) NSString* state; +@property (nonatomic, retain) NSString* lang; +@property (nonatomic, retain) NSString* country; +@end + + + +#pragma mark - SendMessageToWXReq +/*! @brief 第三方程序发送消息至微信终端程序的消息结构体 + * + * 第三方程序向微信发送信息需要传入SendMessageToWXReq结构体,信息类型包括文本消息和多媒体消息, + * 分别对应于text和message成员。调用该方法后,微信处理完信息会向第三方程序发送一个处理结果。 + * @see SendMessageToWXResp + */ +@interface SendMessageToWXReq : BaseReq +/** 发送消息的文本内容 + * @note 文本长度必须大于0且小于10K + */ +@property (nonatomic, retain) NSString* text; +/** 发送消息的多媒体内容 + * @see WXMediaMessage + */ +@property (nonatomic, retain) WXMediaMessage* message; +/** 发送消息的类型,包括文本消息和多媒体消息两种,两者只能选择其一,不能同时发送文本和多媒体消息 */ +@property (nonatomic, assign) BOOL bText; +/** 发送的目标场景,可以选择发送到会话(WXSceneSession)或者朋友圈(WXSceneTimeline)。 默认发送到会话。 + * @see WXScene + */ +@property (nonatomic, assign) int scene; + +@end + + + +#pragma mark - SendMessageToWXResp +/*! @brief 微信终端向第三方程序返回的SendMessageToWXReq处理结果。 + * + * 第三方程序向微信终端发送SendMessageToWXReq后,微信发送回来的处理结果,该结果用SendMessageToWXResp表示。 + */ +@interface SendMessageToWXResp : BaseResp +@property(nonatomic, retain) NSString* lang; +@property(nonatomic, retain) NSString* country; +@end + + + +#pragma mark - GetMessageFromWXReq +/*! @brief 微信终端向第三方程序请求提供内容的消息结构体。 + * + * 微信终端向第三方程序请求提供内容,微信终端会向第三方程序发送GetMessageFromWXReq消息结构体, + * 需要第三方程序调用sendResp返回一个GetMessageFromWXResp消息结构体。 + */ +@interface GetMessageFromWXReq : BaseReq +@property (nonatomic, retain) NSString* lang; +@property (nonatomic, retain) NSString* country; +@end + + + +#pragma mark - GetMessageFromWXResp +/*! @brief 微信终端向第三方程序请求提供内容,第三方程序向微信终端返回的消息结构体。 + * + * 微信终端向第三方程序请求提供内容,第三方程序调用sendResp向微信终端返回一个GetMessageFromWXResp消息结构体。 + */ +@interface GetMessageFromWXResp : BaseResp +/** 向微信终端提供的文本内容 + @note 文本长度必须大于0且小于10K + */ +@property (nonatomic, retain) NSString* text; +/** 向微信终端提供的多媒体内容。 + * @see WXMediaMessage + */ +@property (nonatomic, retain) WXMediaMessage* message; +/** 向微信终端提供内容的消息类型,包括文本消息和多媒体消息两种,两者只能选择其一,不能同时发送文本和多媒体消息 */ +@property (nonatomic, assign) BOOL bText; +@end + + + +#pragma mark - ShowMessageFromWXReq +/*! @brief 微信通知第三方程序,要求第三方程序显示的消息结构体。 + * + * 微信需要通知第三方程序显示或处理某些内容时,会向第三方程序发送ShowMessageFromWXReq消息结构体。 + * 第三方程序处理完内容后调用sendResp向微信终端发送ShowMessageFromWXResp。 + */ +@interface ShowMessageFromWXReq : BaseReq +/** 微信终端向第三方程序发送的要求第三方程序处理的多媒体内容 + * @see WXMediaMessage + */ +@property (nonatomic, retain) WXMediaMessage* message; +@property (nonatomic, retain) NSString* lang; +@property (nonatomic, retain) NSString* country; +@end + + + +#pragma mark - ShowMessageFromWXResp +/*! @brief 微信通知第三方程序,要求第三方程序显示或处理某些消息,第三方程序处理完后向微信终端发送的处理结果。 + * + * 微信需要通知第三方程序显示或处理某些内容时,会向第三方程序发送ShowMessageFromWXReq消息结构体。 + * 第三方程序处理完内容后调用sendResp向微信终端发送ShowMessageFromWXResp。 + */ +@interface ShowMessageFromWXResp : BaseResp +@end + + + +#pragma mark - LaunchFromWXReq +/*! @brief 微信终端打开第三方程序携带的消息结构体 + * + * 微信向第三方发送的结构体,第三方不需要返回 + */ +@interface LaunchFromWXReq : BaseReq +@property (nonatomic, retain) WXMediaMessage* message; +@property (nonatomic, retain) NSString* lang; +@property (nonatomic, retain) NSString* country; +@end + +#pragma mark - OpenTempSessionReq +/* ! @brief 第三方通知微信,打开临时会话 + * + * 第三方通知微信,打开临时会话 + */ +@interface OpenTempSessionReq : BaseReq +/** 需要打开的用户名 + * @attention 长度不能超过512字节 + */ +@property (nonatomic, retain) NSString* username; +/** 开发者自定义参数,拉起临时会话后会发给开发者后台,可以用于识别场景 + * @attention 长度不能超过32位 + */ +@property (nonatomic, retain) NSString* sessionFrom; +@end + +#pragma mark - OpenTempSessionResp +/*! @brief 微信终端向第三方程序返回的OpenTempSessionReq处理结果。 + * + * 第三方程序向微信终端发送OpenTempSessionReq后,微信发送回来的处理结果,该结果用OpenTempSessionResp表示。 + */ +@interface OpenTempSessionResp : BaseResp + +@end + +#pragma mark - OpenWebviewReq +/* ! @brief 第三方通知微信启动内部浏览器,打开指定网页 + * + * 第三方通知微信启动内部浏览器,打开指定Url对应的网页 + */ +@interface OpenWebviewReq : BaseReq +/** 需要打开的网页对应的Url + * @attention 长度不能超过1024 + */ +@property(nonatomic,retain)NSString* url; + +@end + +#pragma mark - OpenWebviewResp +/*! @brief 微信终端向第三方程序返回的OpenWebviewReq处理结果 + * + * 第三方程序向微信终端发送OpenWebviewReq后,微信发送回来的处理结果,该结果用OpenWebviewResp表示 + */ +@interface OpenWebviewResp : BaseResp + +@end + +#pragma mark - OpenRankListReq +/* ! @brief 第三方通知微信,打开硬件排行榜 + * + * 第三方通知微信,打开硬件排行榜 + */ +@interface OpenRankListReq : BaseReq + +@end + +#pragma mark - OpenRanklistResp +/*! @brief 微信终端向第三方程序返回的OpenRankListReq处理结果。 + * + * 第三方程序向微信终端发送OpenRankListReq后,微信发送回来的处理结果,该结果用OpenRankListResp表示。 + */ +@interface OpenRankListResp : BaseResp + +@end + +#pragma mark - JumpToBizProfileReq +/* ! @brief 第三方通知微信,打开指定微信号profile页面 + * + * 第三方通知微信,打开指定微信号profile页面 + */ +@interface JumpToBizProfileReq : BaseReq +/** 跳转到该公众号的profile + * @attention 长度不能超过512字节 + */ +@property (nonatomic, retain) NSString* username; +/** 如果用户加了该公众号为好友,extMsg会上传到服务器 + * @attention 长度不能超过1024字节 + */ +@property (nonatomic, retain) NSString* extMsg; +/** + * 跳转的公众号类型 + * @see WXBizProfileType + */ +@property (nonatomic, assign) int profileType; +@end + + + +#pragma mark - JumpToBizWebviewReq +/* ! @brief 第三方通知微信,打开指定usrname的profile网页版 + * + */ +@interface JumpToBizWebviewReq : BaseReq +/** 跳转的网页类型,目前只支持广告页 + * @see WXMPWebviewType + */ +@property(nonatomic, assign) int webType; +/** 跳转到该公众号的profile网页版 + * @attention 长度不能超过512字节 + */ +@property(nonatomic, retain) NSString* tousrname; +/** 如果用户加了该公众号为好友,extMsg会上传到服务器 + * @attention 长度不能超过1024字节 + */ +@property(nonatomic, retain) NSString* extMsg; + +@end + +#pragma mark - WXCardItem + +@interface WXCardItem : NSObject +/** 卡id + * @attention 长度不能超过1024字节 + */ +@property (nonatomic,retain) NSString* cardId; +/** ext信息 + * @attention 长度不能超过2024字节 + */ +@property (nonatomic,retain) NSString* extMsg; +/** + * @attention 卡的状态,req不需要填。resp:0为未添加,1为已添加。 + */ +@property (nonatomic,assign) UInt32 cardState; +/** + * @attention req不需要填,chooseCard返回的。 + */ +@property (nonatomic,retain) NSString* encryptCode; +/** + * @attention req不需要填,chooseCard返回的。 + */ +@property (nonatomic,retain) NSString* appID; +@end; + +#pragma mark - WXInvoiceItem + +@interface WXInvoiceItem : NSObject +/** 卡id + * @attention 长度不能超过1024字节 + */ +@property (nonatomic,retain) NSString* cardId; +/** ext信息 + * @attention 长度不能超过2024字节 + */ +@property (nonatomic,retain) NSString* extMsg; +/** + * @attention 卡的状态,req不需要填。resp:0为未添加,1为已添加。 + */ +@property (nonatomic,assign) UInt32 cardState; +/** + * @attention req不需要填,chooseCard返回的。 + */ +@property (nonatomic,retain) NSString* encryptCode; +/** + * @attention req不需要填,chooseCard返回的。 + */ +@property (nonatomic,retain) NSString* appID; + +@end + +#pragma mark - AddCardToWXCardPackageReq +/* ! @brief 请求添加卡券至微信卡包 + * + */ + +@interface AddCardToWXCardPackageReq : BaseReq +/** 卡列表 + * @attention 个数不能超过40个 类型WXCardItem + */ +@property (nonatomic,retain) NSArray* cardAry; + +@end + + +#pragma mark - AddCardToWXCardPackageResp +/** ! @brief 微信返回第三方添加卡券结果 + * + */ + +@interface AddCardToWXCardPackageResp : BaseResp +/** 卡列表 + * @attention 个数不能超过40个 类型WXCardItem + */ +@property (nonatomic,retain) NSArray* cardAry; +@end + +#pragma mark - WXChooseCardReq +/* ! @brief 请求从微信选取卡券 + * + */ + +@interface WXChooseCardReq : BaseReq +@property(nonatomic, strong) NSString *appID; +@property(nonatomic, assign) UInt32 shopID; +@property(nonatomic, assign) UInt32 canMultiSelect; +@property(nonatomic, strong) NSString *cardType; +@property(nonatomic, strong) NSString *cardTpID; +@property(nonatomic, strong) NSString *signType; +@property(nonatomic, strong) NSString *cardSign; +@property(nonatomic, assign) UInt32 timeStamp; +@property(nonatomic, strong) NSString *nonceStr; +@end + + +#pragma mark - WXChooseCardResp +/** ! @brief 微信返回第三方请求选择卡券结果 + * + */ + +@interface WXChooseCardResp : BaseResp +@property (nonatomic,retain) NSArray* cardAry; +@end + + +#pragma mark - WXChooseInvoiceReq +/* ! @brief 请求从微信选取发票 + * + */ +@interface WXChooseInvoiceReq : BaseReq +@property (nonatomic, strong) NSString *appID; +@property (nonatomic, assign) UInt32 shopID; +@property (nonatomic, strong) NSString *signType; +@property (nonatomic, strong) NSString *cardSign; +@property (nonatomic, assign) UInt32 timeStamp; +@property (nonatomic, strong) NSString *nonceStr; +@end + +#pragma mark - WXChooseInvoiceResp +/** ! @brief 微信返回第三方请求选择发票结果 + * + */ +@interface WXChooseInvoiceResp : BaseResp +@property (nonatomic, strong) NSArray* cardAry; +@end + +#pragma mark - WXSubscriptionReq +@interface WXSubscribeMsgReq : BaseReq +@property (nonatomic, assign) UInt32 scene; +@property (nonatomic, strong) NSString * templateId; +@property (nonatomic, strong) NSString * reserved; +@end + +#pragma mark - WXSubscriptionReq +@interface WXSubscribeMsgResp : BaseResp + +@property (nonatomic, strong) NSString *templateId; +@property (nonatomic, assign) UInt32 scene; +@property (nonatomic, strong) NSString *action; +@property (nonatomic, strong) NSString * reserved; +@property (nonatomic, strong) NSString * openId; + +@end + +#pragma mark - WXinvoiceAuthInsertReq +@interface WXInvoiceAuthInsertReq : BaseReq + +@property (nonatomic, strong) NSString *urlString; + +@end + +#pragma mark - WXinvoiceAuthInsertResp + +@interface WXInvoiceAuthInsertResp : BaseResp + +@property (nonatomic, strong) NSString * wxOrderId; + +@end + +#pragma mark - WXNontaxPayReq +@interface WXNontaxPayReq:BaseReq + +@property (nonatomic, strong) NSString *urlString; + +@end + +#pragma mark - WXNontaxPayResp +@interface WXNontaxPayResp : BaseResp + +@property (nonatomic, strong) NSString *wxOrderId; + +@end + +#pragma mark - WXPayInsuranceReq +@interface WXPayInsuranceReq : BaseReq + +@property (nonatomic, strong) NSString *urlString; + +@end + +#pragma mark - WXPayInsuranceResp +@interface WXPayInsuranceResp : BaseResp + +@property (nonatomic, strong) NSString *wxOrderId; + +@end + +#pragma mark - WXMediaMessage + + +#pragma mark - WXMediaMessage + +/*! @brief 多媒体消息结构体 + * + * 用于微信终端和第三方程序之间传递消息的多媒体消息内容 + */ +@interface WXMediaMessage : NSObject + ++(WXMediaMessage *) message; + +/** 标题 + * @note 长度不能超过512字节 + */ +@property (nonatomic, retain) NSString *title; +/** 描述内容 + * @note 长度不能超过1K + */ +@property (nonatomic, retain) NSString *description; +/** 缩略图数据 + * @note 大小不能超过32K + */ +@property (nonatomic, retain) NSData *thumbData; +/** + * @note 长度不能超过64字节 + */ +@property (nonatomic, retain) NSString *mediaTagName; +/** + * + */ +@property (nonatomic, retain) NSString *messageExt; +@property (nonatomic, retain) NSString *messageAction; +/** + * 多媒体数据对象,可以为WXImageObject,WXMusicObject,WXVideoObject,WXWebpageObject等。 + */ +@property (nonatomic, retain) id mediaObject; + +/*! @brief 设置消息缩略图的方法 + * + * @param image 缩略图 + * @note 大小不能超过32K + */ +- (void) setThumbImage:(UIImage *)image; + +@end + + + +#pragma mark - WXImageObject +/*! @brief 多媒体消息中包含的图片数据对象 + * + * 微信终端和第三方程序之间传递消息中包含的图片数据对象。 + * @note imageData成员不能为空 + * @see WXMediaMessage + */ +@interface WXImageObject : NSObject +/*! @brief 返回一个WXImageObject对象 + * + * @note 返回的WXImageObject对象是自动释放的 + */ ++(WXImageObject *) object; + +/** 图片真实数据内容 + * @note 大小不能超过10M + */ +@property (nonatomic, retain) NSData *imageData; + +@end + + +#pragma mark - WXMusicObject +/*! @brief 多媒体消息中包含的音乐数据对象 + * + * 微信终端和第三方程序之间传递消息中包含的音乐数据对象。 + * @note musicUrl和musicLowBandUrl成员不能同时为空。 + * @see WXMediaMessage + */ +@interface WXMusicObject : NSObject +/*! @brief 返回一个WXMusicObject对象 + * + * @note 返回的WXMusicObject对象是自动释放的 + */ ++(WXMusicObject *) object; + +/** 音乐网页的url地址 + * @note 长度不能超过10K + */ +@property (nonatomic, retain) NSString *musicUrl; +/** 音乐lowband网页的url地址 + * @note 长度不能超过10K + */ +@property (nonatomic, retain) NSString *musicLowBandUrl; +/** 音乐数据url地址 + * @note 长度不能超过10K + */ +@property (nonatomic, retain) NSString *musicDataUrl; + +/**音乐lowband数据url地址 + * @note 长度不能超过10K + */ +@property (nonatomic, retain) NSString *musicLowBandDataUrl; + +@end + + + +#pragma mark - WXVideoObject +/*! @brief 多媒体消息中包含的视频数据对象 + * + * 微信终端和第三方程序之间传递消息中包含的视频数据对象。 + * @note videoUrl和videoLowBandUrl不能同时为空。 + * @see WXMediaMessage + */ +@interface WXVideoObject : NSObject +/*! @brief 返回一个WXVideoObject对象 + * + * @note 返回的WXVideoObject对象是自动释放的 + */ ++(WXVideoObject *) object; + +/** 视频网页的url地址 + * @note 长度不能超过10K + */ +@property (nonatomic, retain) NSString *videoUrl; +/** 视频lowband网页的url地址 + * @note 长度不能超过10K + */ +@property (nonatomic, retain) NSString *videoLowBandUrl; + +@end + + + +#pragma mark - WXWebpageObject +/*! @brief 多媒体消息中包含的网页数据对象 + * + * 微信终端和第三方程序之间传递消息中包含的网页数据对象。 + * @see WXMediaMessage + */ +@interface WXWebpageObject : NSObject +/*! @brief 返回一个WXWebpageObject对象 + * + * @note 返回的WXWebpageObject对象是自动释放的 + */ ++(WXWebpageObject *) object; + +/** 网页的url地址 + * @note 不能为空且长度不能超过10K + */ +@property (nonatomic, retain) NSString *webpageUrl; + +@end + + + +#pragma mark - WXAppExtendObject +/*! @brief 多媒体消息中包含的App扩展数据对象 + * + * 第三方程序向微信终端发送包含WXAppExtendObject的多媒体消息, + * 微信需要处理该消息时,会调用该第三方程序来处理多媒体消息内容。 + * @note url,extInfo和fileData不能同时为空 + * @see WXMediaMessage + */ +@interface WXAppExtendObject : NSObject +/*! @brief 返回一个WXAppExtendObject对象 + * + * @note 返回的WXAppExtendObject对象是自动释放的 + */ ++(WXAppExtendObject *) object; + +/** 若第三方程序不存在,微信终端会打开该url所指的App下载地址 + * @note 长度不能超过10K + */ +@property (nonatomic, retain) NSString *url; +/** 第三方程序自定义简单数据,微信终端会回传给第三方程序处理 + * @note 长度不能超过2K + */ +@property (nonatomic, retain) NSString *extInfo; +/** App文件数据,该数据发送给微信好友,微信好友需要点击后下载数据,微信终端会回传给第三方程序处理 + * @note 大小不能超过10M + */ +@property (nonatomic, retain) NSData *fileData; + +@end + + + +#pragma mark - WXEmoticonObject +/*! @brief 多媒体消息中包含的表情数据对象 + * + * 微信终端和第三方程序之间传递消息中包含的表情数据对象。 + * @see WXMediaMessage + */ +@interface WXEmoticonObject : NSObject + +/*! @brief 返回一个WXEmoticonObject对象 + * + * @note 返回的WXEmoticonObject对象是自动释放的 + */ ++(WXEmoticonObject *) object; + +/** 表情真实数据内容 + * @note 大小不能超过10M + */ +@property (nonatomic, retain) NSData *emoticonData; + +@end + + + +#pragma mark - WXFileObject +/*! @brief 多媒体消息中包含的文件数据对象 + * + * @see WXMediaMessage + */ +@interface WXFileObject : NSObject + +/*! @brief 返回一个WXFileObject对象 + * + * @note 返回的WXFileObject对象是自动释放的 + */ ++(WXFileObject *) object; + +/** 文件后缀名 + * @note 长度不超过64字节 + */ +@property (nonatomic, retain) NSString *fileExtension; + +/** 文件真实数据内容 + * @note 大小不能超过10M + */ +@property (nonatomic, retain) NSData *fileData; + +@end + + +#pragma mark - WXLocationObject +/*! @brief 多媒体消息中包含的地理位置数据对象 + * + * 微信终端和第三方程序之间传递消息中包含的地理位置数据对象。 + * @see WXMediaMessage + */ +@interface WXLocationObject : NSObject + +/*! @brief 返回一个WXLocationObject对象 + * + * @note 返回的WXLocationObject对象是自动释放的 + */ ++(WXLocationObject *) object; + +/** 地理位置信息 + * @note 经纬度 + */ +@property (nonatomic, assign) double lng; //经度 +@property (nonatomic, assign) double lat; //纬度 + +@end + +@interface WXMiniProgramObject : NSObject + +/*! @brief WXMiniProgramObject对象 + * + * @note 返回的WXMiniProgramObject对象是自动释放的 + */ ++(WXMiniProgramObject *) object; + +@property (nonatomic, strong) NSString *webpageUrl; //低版本网页链接 + +@property (nonatomic, strong) NSString *userName; //小程序username + +@property (nonatomic, strong) NSString *path; //小程序页面的路径 + +@property (nonatomic, strong) NSData *hdImageData; // 小程序新版本的预览图 128k + +@property (nonatomic, assign) BOOL withShareTicket; //是否使用带 shareTicket 的转发 + +@property (nonatomic, assign) WXMiniProgramType miniProgramType; // 分享小程序的版本(正式,开发,体验) + +@end + +#pragma mark - WXLaunchMiniProgramReq + +/*! @brief WXLaunchMiniProgramReq对象, 可实现通过sdk拉起微信小程序 + * + * @note 返回的WXLaunchMiniProgramReq对象是自动释放的 + */ +@interface WXLaunchMiniProgramReq : BaseReq + ++(WXLaunchMiniProgramReq *) object; + +@property (nonatomic, strong) NSString *userName; //拉起的小程序的username +@property (nonatomic, strong) NSString *path; //拉起小程序页面的路径,不填默认拉起小程序首页 +@property (nonatomic, assign) WXMiniProgramType miniProgramType; //拉起小程序的类型 + +@end + +#pragma mark - WXLaunchMiniProgramResp +/*! @brief 微信终端向第三方程序返回的WXLaunchMiniProgramReq处理结果。 + * + * 第三方程序向微信终端发送WXLaunchMiniProgramReq后,微信发送回来的处理结果,该结果用WXLaunchMiniProgramResp表示。 + */ +@interface WXLaunchMiniProgramResp : BaseResp + +@property (nonatomic, retain) NSString *extMsg; + +@end + + +#pragma mark - WXTextObject +/*! @brief 多媒体消息中包含的文本数据对象 + * + * 微信终端和第三方程序之间传递消息中包含的文本数据对象。 + * @see WXMediaMessage + */ +@interface WXTextObject : NSObject + +/*! @brief 返回一个WXTextObject对象 + * + * @note 返回的WXTextObject对象是自动释放的 + */ ++(WXTextObject *) object; + +/** 地理位置信息 + * @note 文本内容 + */ +@property (nonatomic, retain) NSString *contentText; + +@end diff --git a/Pods/WechatOpenSDK/WechatSDK1.8.2/WechatAuthSDK.h b/Pods/WechatOpenSDK/WechatSDK1.8.2/WechatAuthSDK.h new file mode 100644 index 0000000..076b1d7 --- /dev/null +++ b/Pods/WechatOpenSDK/WechatSDK1.8.2/WechatAuthSDK.h @@ -0,0 +1,64 @@ +// +// WechatAuthSDK.h +// WechatAuthSDK +// +// Created by 李凯 on 13-11-29. +// Copyright (c) 2013年 Tencent. All rights reserved. +// + +#import +#import + +enum AuthErrCode { + WechatAuth_Err_Ok = 0, //Auth成功 + WechatAuth_Err_NormalErr = -1, //普通错误 + WechatAuth_Err_NetworkErr = -2, //网络错误 + WechatAuth_Err_GetQrcodeFailed = -3, //获取二维码失败 + WechatAuth_Err_Cancel = -4, //用户取消授权 + WechatAuth_Err_Timeout = -5, //超时 +}; + +@protocol WechatAuthAPIDelegate +@optional + +- (void)onAuthGotQrcode:(UIImage *)image; //得到二维码 +- (void)onQrcodeScanned; //二维码被扫描 +- (void)onAuthFinish:(int)errCode AuthCode:(NSString *)authCode; //成功登录 + +@end + +@interface WechatAuthSDK : NSObject{ + NSString *_sdkVersion; + __weak id _delegate; +} + +@property(nonatomic, weak) id delegate; +@property(nonatomic, readonly) NSString *sdkVersion; //authSDK版本号 + +/*! @brief 发送登录请求,等待WechatAuthAPIDelegate回调 + * + * @param appId 微信开发者ID + * @param nonceStr 一个随机的尽量不重复的字符串,用来使得每次的signature不同 + * @param timeStamp 时间戳 + * @param scope 应用授权作用域,拥有多个作用域用逗号(,)分隔 + * @param signature 签名 + * @param schemeData 会在扫码后拼在scheme后 + * @return 成功返回YES,失败返回NO + 注:该实现只保证同时只有一个Auth在运行,Auth未完成或未Stop再次调用Auth接口时会返回NO。 + */ + +- (BOOL)Auth:(NSString *)appId + nonceStr:(NSString *)nonceStr + timeStamp:(NSString*)timeStamp + scope:(NSString *)scope + signature:(NSString *)signature + schemeData:(NSString *)schemeData; + + +/*! @brief 暂停登录请求 + * + * @return 成功返回YES,失败返回NO。 + */ +- (BOOL)StopAuth; + +@end diff --git a/Pods/WechatOpenSDK/WechatSDK1.8.2/libWeChatSDK.a b/Pods/WechatOpenSDK/WechatSDK1.8.2/libWeChatSDK.a new file mode 100644 index 0000000..49cdb65 Binary files /dev/null and b/Pods/WechatOpenSDK/WechatSDK1.8.2/libWeChatSDK.a differ diff --git a/Pods/YTKKeyValueStore/LICENSE b/Pods/YTKKeyValueStore/LICENSE new file mode 100644 index 0000000..c126dab --- /dev/null +++ b/Pods/YTKKeyValueStore/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012-2014 YTKKeyValueStore https://github.com/yuantiku + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Pods/YTKKeyValueStore/README.md b/Pods/YTKKeyValueStore/README.md new file mode 100644 index 0000000..4f1d1d1 --- /dev/null +++ b/Pods/YTKKeyValueStore/README.md @@ -0,0 +1,132 @@ + +## 前言 + +还记得大学刚学数据库那会儿,天真地以为世界上所有的存储都需要用数据库来做。后来毕业后,正值NOSQL流行,那时我在网易参与了网易微博的开发,我们当时使用了有道自己做的“BigTable”— OMAP来存储微博数据,那个时候才发现,其实Key-Value这种简单的存储也能搞定微博这类不太简单的存储逻辑。 + +相比MYSQL,当数据量上千万后,NOSQL的优势体现出来了:对于海量数据,NOSQL在存取速度上没有任何影响,另外,天生的多备份和分布式,也说数据安全和扩容变得异常容易。 + +## iOS端的尝试 + +后来我从后台转做iOS端的开发,我就尝试了在iOS端直接使用Key-Value式的存储。经过在粉笔网、猿题库、小猿搜题三个客户端中的尝试后,我发现Key-Value式的存储不但完全能够满足大多数移动端开发的需求,而且非常适合移动端采用。主要原因是:移动端存储的数据量不会很大: + + * 如果是单机的应用(例如效率工具Clear),用户自己一个人创建的数据最多也就上万条。 + * 如果是有服务端的应用(例如网易新闻,微博),那移动端通常不会保存全量的数据,每次会从服务器上获取数据,本地只是做一些内容的缓存而已,所以也不会有很大的数据量。 + +如果数据量不大的话,那么在iOS端使用最简单直接的Key-Value存储就能带来开发上的效率优势。它能保证: + + 1. Model层的代码编写简单,易于测试。 + 2. 由于Value是JSON格式,所以在做Model字段更改时,易于扩展和兼容。 + +## 实现方案 + +在存储引擎上,2年前我直接选择了Sqlite当做存储引擎,相当于每个数据库表只有Key,Value两个字段。后来,随着LevelDB的流行,业界也有一些应用采用了LevelDB来做iOS端的Key-Value存储引擎,例如开源的[ViewFinder](https://github.com/viewfinderco/viewfinder)。 + +因为LevelDB本身并不是为移动端设计的,我担心它过于占用内存,我自己也没有看到业界有在移动端针对LevelDB做很详细的测试,连LevelDB的iOS端移植都不是官方做的。加上我自己写的基于Sqlite的Key-Value存储用着也没有什么问题,所以我也就一直没有更换成LevelDB。 + +## 开源 + +经过两年的使用和测试,我认为它非常好用,而且代码也非常简单,只有不到400行。所以现在开源分享给大家,这个项目叫`YTKKeyValueStore`,项目在[这里](https://github.com/yuantiku/YTKKeyValueStore)。以下是一个简单的使用示例: + +``` +YTKKeyValueStore *store = [[YTKKeyValueStore alloc] initDBWithName:@"test.db"]; +NSString *tableName = @"user_table"; +[store createTableWithName:tableName]; +// 保存 +NSString *key = @"1"; +NSDictionary *user = @{@"id": @1, @"name": @"tangqiao", @"age": @30}; +[store putObject:user withId:key intoTable:tableName]; +// 查询 +NSDictionary *queryUser = [store getObjectById:key fromTable:tableName]; +NSLog(@"query data result: %@", queryUser); +``` + +## 集成说明 + +使用本项目,你需要将开源代码中的`YTKKeyValueStore.h`和`YTKKeyValueStore.m`添加到你的工程中,并且在工程设置的`Link Binary With Libraries`中,增加`libsqlite3.dylib`,如下图所示: + +![](http://blog.devtang.com/images/key-value-store-setup.jpg) + +由于时间关系,当前还未提供Cocoapods方式集成。 + +## 使用说明 + +所有的接口都封装在`YTKKeyValueStore`类中。以下是一些常用方法说明。 + +### 打开(或创建)数据库 + +通过`initDBWithName`方法,即可在程序的`Document`目录打开指定的数据库文件。如果该文件不存在,则会创建一个新的数据库。 + +``` +// 打开名为test.db的数据库,如果该文件不存在,则创新一个新的。 +YTKKeyValueStore *store = [[YTKKeyValueStore alloc] initDBWithName:@"test.db"]; +``` + +### 创建数据库表 + +通过`createTableWithName`方法,我们可以在打开的数据库中创建表,如果表名已经存在,则会忽略该操作。如下所示: + +``` +YTKKeyValueStore *store = [[YTKKeyValueStore alloc] initDBWithName:@"test.db"]; +NSString *tableName = @"user_table"; +// 创建名为user_table的表,如果已存在,则忽略该操作 +[store createTableWithName:tableName]; +``` + +### 读写数据 + +`YTKKeyValueStore`类提供key-value的存储接口,存入的所有数据需要提供key以及其对应的value,读取的时候需要提供key来获得相应的value。 + +`YTKKeyValueStore`类支持的value类型包括:NSString, NSNumber, NSDictionary和NSArray,为此提供了以下接口: + +``` +- (void)putString:(NSString *)string withId:(NSString *)stringId intoTable:(NSString *)tableName; +- (void)putNumber:(NSNumber *)number withId:(NSString *)numberId intoTable:(NSString *)tableName; +- (void)putObject:(id)object withId:(NSString *)objectId intoTable:(NSString *)tableName; +``` + +与此对应,有以下value为NSString, NSNumber, NSDictionary和NSArray的读取接口: + +``` +- (NSString *)getStringById:(NSString *)stringId fromTable:(NSString *)tableName; +- (NSNumber *)getNumberById:(NSString *)numberId fromTable:(NSString *)tableName; +- (id)getObjectById:(NSString *)objectId fromTable:(NSString *)tableName; +``` + +### 删除数据接口 + +`YTKKeyValueStore`提供了以下接口用于删除数据。 + +``` +// 清除数据表中所有数据 +- (void)clearTable:(NSString *)tableName; + +// 删除指定key的数据 +- (void)deleteObjectById:(NSString *)objectId fromTable:(NSString *)tableName; + +// 批量删除一组key数组的数据 +- (void)deleteObjectsByIdArray:(NSArray *)objectIdArray fromTable:(NSString *)tableName; + +// 批量删除所有带指定前缀的数据 +- (void)deleteObjectsByIdPrefix:(NSString *)objectIdPrefix fromTable:(NSString *)tableName; +``` + +### 更多接口 + +`YTKKeyValueStore`还提供了以下接口来获取表示内部存储的key-value对象。 + +``` +// 获得指定key的数据 +- (YTKKeyValueItem *)getYTKKeyValueItemById:(NSString *)objectId fromTable:(NSString *)tableName; +// 获得所有数据 +- (NSArray *)getAllItemsFromTable:(NSString *)tableName; +``` + +由于`YTKKeyValueItem`类带有`createdTime`字段,可以获得该条数据的插入(或更新)时间,以便上层做复杂的处理(例如用来做缓存过期逻辑)。 + +## 协议 + +YTKKeyValueStore 被许可在 MIT 协议下使用。查阅 LICENSE 文件来获得更多信息。 + +## 其它 + +两年前写过不少测试用例,后来给弄丢了,所以现在开项项目中还没有测试用例。由于时间关系,更详细的使用说明稍后会更新到项目中。 diff --git a/Pods/YTKKeyValueStore/YTKKeyValueStore/YTKKeyValueStore.h b/Pods/YTKKeyValueStore/YTKKeyValueStore/YTKKeyValueStore.h new file mode 100644 index 0000000..88e0e32 --- /dev/null +++ b/Pods/YTKKeyValueStore/YTKKeyValueStore/YTKKeyValueStore.h @@ -0,0 +1,57 @@ +// +// YTKKeyValueStore.h +// Ape +// +// Created by TangQiao on 12-11-6. +// Copyright (c) 2012年 TangQiao. All rights reserved. +// + +#import + +@interface YTKKeyValueItem : NSObject + +@property (strong, nonatomic) NSString *itemId; +@property (strong, nonatomic) id itemObject; +@property (strong, nonatomic) NSDate *createdTime; + +@end + + +@interface YTKKeyValueStore : NSObject + +- (id)initDBWithName:(NSString *)dbName; + +- (id)initWithDBWithPath:(NSString *)dbPath; + +- (void)createTableWithName:(NSString *)tableName; + +- (void)clearTable:(NSString *)tableName; + +- (void)close; + +///************************ Put&Get methods ***************************************** + +- (void)putObject:(id)object withId:(NSString *)objectId intoTable:(NSString *)tableName; + +- (id)getObjectById:(NSString *)objectId fromTable:(NSString *)tableName; + +- (YTKKeyValueItem *)getYTKKeyValueItemById:(NSString *)objectId fromTable:(NSString *)tableName; + +- (void)putString:(NSString *)string withId:(NSString *)stringId intoTable:(NSString *)tableName; + +- (NSString *)getStringById:(NSString *)stringId fromTable:(NSString *)tableName; + +- (void)putNumber:(NSNumber *)number withId:(NSString *)numberId intoTable:(NSString *)tableName; + +- (NSNumber *)getNumberById:(NSString *)numberId fromTable:(NSString *)tableName; + +- (NSArray *)getAllItemsFromTable:(NSString *)tableName; + +- (void)deleteObjectById:(NSString *)objectId fromTable:(NSString *)tableName; + +- (void)deleteObjectsByIdArray:(NSArray *)objectIdArray fromTable:(NSString *)tableName; + +- (void)deleteObjectsByIdPrefix:(NSString *)objectIdPrefix fromTable:(NSString *)tableName; + + +@end diff --git a/Pods/YTKKeyValueStore/YTKKeyValueStore/YTKKeyValueStore.m b/Pods/YTKKeyValueStore/YTKKeyValueStore/YTKKeyValueStore.m new file mode 100644 index 0000000..ea57d34 --- /dev/null +++ b/Pods/YTKKeyValueStore/YTKKeyValueStore/YTKKeyValueStore.m @@ -0,0 +1,316 @@ +// +// YTKKeyValueStore.m +// Ape +// +// Created by TangQiao on 12-11-6. +// Copyright (c) 2012年 TangQiao. All rights reserved. +// + +#import "YTKKeyValueStore.h" +#import "FMDatabase.h" +#import "FMDatabaseQueue.h" + +#ifdef DEBUG +#define debugLog(...) NSLog(__VA_ARGS__) +#define debugMethod() NSLog(@"%s", __func__) +#define debugError() NSLog(@"Error at %s Line:%d", __func__, __LINE__) +#else +#define debugLog(...) +#define debugMethod() +#define debugError() +#endif + +#define PATH_OF_DOCUMENT [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] + +@implementation YTKKeyValueItem + +- (NSString *)description { + return [NSString stringWithFormat:@"id=%@, value=%@, timeStamp=%@", _itemId, _itemObject, _createdTime]; +} + +@end + +@interface YTKKeyValueStore() + +@property (strong, nonatomic) FMDatabaseQueue * dbQueue; + +@end + +@implementation YTKKeyValueStore + +static NSString *const DEFAULT_DB_NAME = @"database.sqlite"; + +static NSString *const CREATE_TABLE_SQL = +@"CREATE TABLE IF NOT EXISTS %@ ( \ +id TEXT NOT NULL, \ +json TEXT NOT NULL, \ +createdTime TEXT NOT NULL, \ +PRIMARY KEY(id)) \ +"; + +static NSString *const UPDATE_ITEM_SQL = @"REPLACE INTO %@ (id, json, createdTime) values (?, ?, ?)"; + +static NSString *const QUERY_ITEM_SQL = @"SELECT json, createdTime from %@ where id = ? Limit 1"; + +static NSString *const SELECT_ALL_SQL = @"SELECT * from %@"; + +static NSString *const CLEAR_ALL_SQL = @"DELETE from %@"; + +static NSString *const DELETE_ITEM_SQL = @"DELETE from %@ where id = ?"; + +static NSString *const DELETE_ITEMS_SQL = @"DELETE from %@ where id in ( %@ )"; + +static NSString *const DELETE_ITEMS_WITH_PREFIX_SQL = @"DELETE from %@ where id like ? "; + ++ (BOOL)checkTableName:(NSString *)tableName { + if (tableName == nil || tableName.length == 0 || [tableName rangeOfString:@" "].location != NSNotFound) { + debugLog(@"ERROR, table name: %@ format error.", tableName); + return NO; + } + return YES; +} + +- (id)init { + return [self initDBWithName:DEFAULT_DB_NAME]; +} + +- (id)initDBWithName:(NSString *)dbName { + self = [super init]; + if (self) { + NSString * dbPath = [PATH_OF_DOCUMENT stringByAppendingPathComponent:dbName]; + debugLog(@"dbPath = %@", dbPath); + if (_dbQueue) { + [self close]; + } + _dbQueue = [FMDatabaseQueue databaseQueueWithPath:dbPath]; + } + return self; +} + +- (id)initWithDBWithPath:(NSString *)dbPath { + self = [super init]; + if (self) { + debugLog(@"dbPath = %@", dbPath); + if (_dbQueue) { + [self close]; + } + _dbQueue = [FMDatabaseQueue databaseQueueWithPath:dbPath]; + } + return self; +} + +- (void)createTableWithName:(NSString *)tableName { + if ([YTKKeyValueStore checkTableName:tableName] == NO) { + return; + } + NSString * sql = [NSString stringWithFormat:CREATE_TABLE_SQL, tableName]; + __block BOOL result; + [_dbQueue inDatabase:^(FMDatabase *db) { + result = [db executeUpdate:sql]; + }]; + if (!result) { + debugLog(@"ERROR, failed to create table: %@", tableName); + } +} + +- (void)clearTable:(NSString *)tableName { + if ([YTKKeyValueStore checkTableName:tableName] == NO) { + return; + } + NSString * sql = [NSString stringWithFormat:CLEAR_ALL_SQL, tableName]; + __block BOOL result; + [_dbQueue inDatabase:^(FMDatabase *db) { + result = [db executeUpdate:sql]; + }]; + if (!result) { + debugLog(@"ERROR, failed to clear table: %@", tableName); + } +} + +- (void)putObject:(id)object withId:(NSString *)objectId intoTable:(NSString *)tableName { + if ([YTKKeyValueStore checkTableName:tableName] == NO) { + return; + } + NSError * error; + NSData * data = [NSJSONSerialization dataWithJSONObject:object options:0 error:&error]; + if (error) { + debugLog(@"ERROR, faild to get json data"); + return; + } + NSString * jsonString = [[NSString alloc] initWithData:data encoding:(NSUTF8StringEncoding)]; + NSDate * createdTime = [NSDate date]; + NSString * sql = [NSString stringWithFormat:UPDATE_ITEM_SQL, tableName]; + __block BOOL result; + [_dbQueue inDatabase:^(FMDatabase *db) { + result = [db executeUpdate:sql, objectId, jsonString, createdTime]; + }]; + if (!result) { + debugLog(@"ERROR, failed to insert/replace into table: %@", tableName); + } +} + +- (id)getObjectById:(NSString *)objectId fromTable:(NSString *)tableName { + YTKKeyValueItem * item = [self getYTKKeyValueItemById:objectId fromTable:tableName]; + if (item) { + return item.itemObject; + } else { + return nil; + } +} + +- (YTKKeyValueItem *)getYTKKeyValueItemById:(NSString *)objectId fromTable:(NSString *)tableName { + if ([YTKKeyValueStore checkTableName:tableName] == NO) { + return nil; + } + NSString * sql = [NSString stringWithFormat:QUERY_ITEM_SQL, tableName]; + __block NSString * json = nil; + __block NSDate * createdTime = nil; + [_dbQueue inDatabase:^(FMDatabase *db) { + FMResultSet * rs = [db executeQuery:sql, objectId]; + if ([rs next]) { + json = [rs stringForColumn:@"json"]; + createdTime = [rs dateForColumn:@"createdTime"]; + } + [rs close]; + }]; + if (json) { + NSError * error; + id result = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] + options:(NSJSONReadingAllowFragments) error:&error]; + if (error) { + debugLog(@"ERROR, faild to prase to json"); + return nil; + } + YTKKeyValueItem * item = [[YTKKeyValueItem alloc] init]; + item.itemId = objectId; + item.itemObject = result; + item.createdTime = createdTime; + return item; + } else { + return nil; + } +} + +- (void)putString:(NSString *)string withId:(NSString *)stringId intoTable:(NSString *)tableName { + if (string == nil) { + debugLog(@"error, string is nil"); + return; + } + [self putObject:@[string] withId:stringId intoTable:tableName]; +} + +- (NSString *)getStringById:(NSString *)stringId fromTable:(NSString *)tableName { + NSArray * array = [self getObjectById:stringId fromTable:tableName]; + if (array && [array isKindOfClass:[NSArray class]]) { + return array[0]; + } + return nil; +} + +- (void)putNumber:(NSNumber *)number withId:(NSString *)numberId intoTable:(NSString *)tableName { + if (number == nil) { + debugLog(@"error, number is nil"); + return; + } + [self putObject:@[number] withId:numberId intoTable:tableName]; +} + +- (NSNumber *)getNumberById:(NSString *)numberId fromTable:(NSString *)tableName { + NSArray * array = [self getObjectById:numberId fromTable:tableName]; + if (array && [array isKindOfClass:[NSArray class]]) { + return array[0]; + } + return nil; +} + +- (NSArray *)getAllItemsFromTable:(NSString *)tableName { + if ([YTKKeyValueStore checkTableName:tableName] == NO) { + return nil; + } + NSString * sql = [NSString stringWithFormat:SELECT_ALL_SQL, tableName]; + __block NSMutableArray * result = [NSMutableArray array]; + [_dbQueue inDatabase:^(FMDatabase *db) { + FMResultSet * rs = [db executeQuery:sql]; + while ([rs next]) { + YTKKeyValueItem * item = [[YTKKeyValueItem alloc] init]; + item.itemId = [rs stringForColumn:@"id"]; + item.itemObject = [rs stringForColumn:@"json"]; + item.createdTime = [rs dateForColumn:@"createdTime"]; + [result addObject:item]; + } + [rs close]; + }]; + // parse json string to object + NSError * error; + for (YTKKeyValueItem * item in result) { + error = nil; + id object = [NSJSONSerialization JSONObjectWithData:[item.itemObject dataUsingEncoding:NSUTF8StringEncoding] + options:(NSJSONReadingAllowFragments) error:&error]; + if (error) { + debugLog(@"ERROR, faild to prase to json."); + } else { + item.itemObject = object; + } + } + return result; +} + +- (void)deleteObjectById:(NSString *)objectId fromTable:(NSString *)tableName { + if ([YTKKeyValueStore checkTableName:tableName] == NO) { + return; + } + NSString * sql = [NSString stringWithFormat:DELETE_ITEM_SQL, tableName]; + __block BOOL result; + [_dbQueue inDatabase:^(FMDatabase *db) { + result = [db executeUpdate:sql, objectId]; + }]; + if (!result) { + debugLog(@"ERROR, failed to delete item from table: %@", tableName); + } +} + +- (void)deleteObjectsByIdArray:(NSArray *)objectIdArray fromTable:(NSString *)tableName { + if ([YTKKeyValueStore checkTableName:tableName] == NO) { + return; + } + NSMutableString *stringBuilder = [NSMutableString string]; + for (id objectId in objectIdArray) { + NSString *item = [NSString stringWithFormat:@" '%@' ", objectId]; + if (stringBuilder.length == 0) { + [stringBuilder appendString:item]; + } else { + [stringBuilder appendString:@","]; + [stringBuilder appendString:item]; + } + } + NSString *sql = [NSString stringWithFormat:DELETE_ITEMS_SQL, tableName, stringBuilder]; + __block BOOL result; + [_dbQueue inDatabase:^(FMDatabase *db) { + result = [db executeUpdate:sql]; + }]; + if (!result) { + debugLog(@"ERROR, failed to delete items by ids from table: %@", tableName); + } +} + +- (void)deleteObjectsByIdPrefix:(NSString *)objectIdPrefix fromTable:(NSString *)tableName { + if ([YTKKeyValueStore checkTableName:tableName] == NO) { + return; + } + NSString *sql = [NSString stringWithFormat:DELETE_ITEMS_WITH_PREFIX_SQL, tableName]; + NSString *prefixArgument = [NSString stringWithFormat:@"%@%%", objectIdPrefix]; + __block BOOL result; + [_dbQueue inDatabase:^(FMDatabase *db) { + result = [db executeUpdate:sql, prefixArgument]; + }]; + if (!result) { + debugLog(@"ERROR, failed to delete items by id prefix from table: %@", tableName); + } +} + +- (void)close { + [_dbQueue close]; + _dbQueue = nil; +} + +@end