├── README.gif ├── README.md ├── YWCLocalizeTool.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ │ └── YangWeicheng.xcuserdatad │ │ └── UserInterfaceState.xcuserstate └── xcuserdata │ └── YangWeicheng.xcuserdatad │ ├── xcdebugger │ └── Breakpoints_v2.xcbkptlist │ └── xcschemes │ ├── YWCLocalizeTool.xcscheme │ └── xcschememanagement.plist └── YWCLocalizeTool ├── AFNetworking ├── AFHTTPSessionManager.h ├── AFHTTPSessionManager.m ├── AFNetworkReachabilityManager.h ├── AFNetworkReachabilityManager.m ├── AFNetworking.h ├── AFSecurityPolicy.h ├── AFSecurityPolicy.m ├── AFURLRequestSerialization.h ├── AFURLRequestSerialization.m ├── AFURLResponseSerialization.h ├── AFURLResponseSerialization.m ├── AFURLSessionManager.h └── AFURLSessionManager.m ├── AppDelegate.h ├── AppDelegate.m ├── Assets.xcassets └── AppIcon.appiconset │ └── Contents.json ├── Base.lproj └── Main.storyboard ├── Info.plist ├── ViewController.h ├── ViewController.m └── main.m /README.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Andy1984/YWCLocalizeTool/417dfe56946b42c076432e5c4732e5c20bcd9052/README.gif -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # YWCLocalizeTool 2 | ![licecap.gif](https://raw.githubusercontent.com/Andy1984/YWCLocalizeTool/master/README.gif) 3 | ## How to use 4 | There are three tabs 5 | 6 | * In the first tab, input what you want to translate. 7 | * In the second tab, the translated would be output. 8 | * The third tab demonstrate the table of comparisons. 9 | * Input source language and destination language in the below, according to the table of comparisons. 10 | 11 | Attention: There cannot be `";` in the comment. The logic is search `";` and the `"` before. Extract the content in the middle and use Baidu api to translate. 12 | 13 | ## 使用方法 14 | 整个app分3栏 15 | 16 | * 第一栏输入要翻译的文字 17 | * 第二栏输出翻译完的文字 18 | * 第三栏是国际化语言的对照表 19 | * 第一栏第二栏下可以填写源语言和目标语言 20 | 注意: 注释里不能有`";` 21 | [具体思路](http://www.jianshu.com/p/ec2bf75a9d41) 22 | 23 | -------------------------------------------------------------------------------- /YWCLocalizeTool.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | E438B46E1D73D16800001DD4 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = E438B46D1D73D16800001DD4 /* AppDelegate.m */; }; 11 | E438B4711D73D16800001DD4 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = E438B4701D73D16800001DD4 /* main.m */; }; 12 | E438B4741D73D16800001DD4 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = E438B4731D73D16800001DD4 /* ViewController.m */; }; 13 | E438B4761D73D16800001DD4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = E438B4751D73D16800001DD4 /* Assets.xcassets */; }; 14 | E438B4791D73D16800001DD4 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = E438B4771D73D16800001DD4 /* Main.storyboard */; }; 15 | E438B48E1D73D76100001DD4 /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E438B4821D73D76100001DD4 /* AFHTTPSessionManager.m */; }; 16 | E438B48F1D73D76100001DD4 /* AFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E438B4851D73D76100001DD4 /* AFNetworkReachabilityManager.m */; }; 17 | E438B4901D73D76100001DD4 /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = E438B4871D73D76100001DD4 /* AFSecurityPolicy.m */; }; 18 | E438B4911D73D76100001DD4 /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = E438B4891D73D76100001DD4 /* AFURLRequestSerialization.m */; }; 19 | E438B4921D73D76100001DD4 /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = E438B48B1D73D76100001DD4 /* AFURLResponseSerialization.m */; }; 20 | E438B4931D73D76100001DD4 /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E438B48D1D73D76100001DD4 /* AFURLSessionManager.m */; }; 21 | /* End PBXBuildFile section */ 22 | 23 | /* Begin PBXFileReference section */ 24 | E438B4691D73D16800001DD4 /* YWCLocalizeTool.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = YWCLocalizeTool.app; sourceTree = BUILT_PRODUCTS_DIR; }; 25 | E438B46C1D73D16800001DD4 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 26 | E438B46D1D73D16800001DD4 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; 27 | E438B4701D73D16800001DD4 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 28 | E438B4721D73D16800001DD4 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; 29 | E438B4731D73D16800001DD4 /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; 30 | E438B4751D73D16800001DD4 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 31 | E438B4781D73D16800001DD4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 32 | E438B47A1D73D16800001DD4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 33 | E438B4811D73D76100001DD4 /* AFHTTPSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPSessionManager.h; sourceTree = ""; }; 34 | E438B4821D73D76100001DD4 /* AFHTTPSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPSessionManager.m; sourceTree = ""; }; 35 | E438B4831D73D76100001DD4 /* AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworking.h; sourceTree = ""; }; 36 | E438B4841D73D76100001DD4 /* AFNetworkReachabilityManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkReachabilityManager.h; sourceTree = ""; }; 37 | E438B4851D73D76100001DD4 /* AFNetworkReachabilityManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkReachabilityManager.m; sourceTree = ""; }; 38 | E438B4861D73D76100001DD4 /* AFSecurityPolicy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFSecurityPolicy.h; sourceTree = ""; }; 39 | E438B4871D73D76100001DD4 /* AFSecurityPolicy.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFSecurityPolicy.m; sourceTree = ""; }; 40 | E438B4881D73D76100001DD4 /* AFURLRequestSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLRequestSerialization.h; sourceTree = ""; }; 41 | E438B4891D73D76100001DD4 /* AFURLRequestSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLRequestSerialization.m; sourceTree = ""; }; 42 | E438B48A1D73D76100001DD4 /* AFURLResponseSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLResponseSerialization.h; sourceTree = ""; }; 43 | E438B48B1D73D76100001DD4 /* AFURLResponseSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLResponseSerialization.m; sourceTree = ""; }; 44 | E438B48C1D73D76100001DD4 /* AFURLSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLSessionManager.h; sourceTree = ""; }; 45 | E438B48D1D73D76100001DD4 /* AFURLSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLSessionManager.m; sourceTree = ""; }; 46 | /* End PBXFileReference section */ 47 | 48 | /* Begin PBXFrameworksBuildPhase section */ 49 | E438B4661D73D16800001DD4 /* Frameworks */ = { 50 | isa = PBXFrameworksBuildPhase; 51 | buildActionMask = 2147483647; 52 | files = ( 53 | ); 54 | runOnlyForDeploymentPostprocessing = 0; 55 | }; 56 | /* End PBXFrameworksBuildPhase section */ 57 | 58 | /* Begin PBXGroup section */ 59 | E438B4601D73D16800001DD4 = { 60 | isa = PBXGroup; 61 | children = ( 62 | E438B46B1D73D16800001DD4 /* YWCLocalizeTool */, 63 | E438B46A1D73D16800001DD4 /* Products */, 64 | ); 65 | sourceTree = ""; 66 | }; 67 | E438B46A1D73D16800001DD4 /* Products */ = { 68 | isa = PBXGroup; 69 | children = ( 70 | E438B4691D73D16800001DD4 /* YWCLocalizeTool.app */, 71 | ); 72 | name = Products; 73 | sourceTree = ""; 74 | }; 75 | E438B46B1D73D16800001DD4 /* YWCLocalizeTool */ = { 76 | isa = PBXGroup; 77 | children = ( 78 | E438B4801D73D76100001DD4 /* AFNetworking */, 79 | E438B46C1D73D16800001DD4 /* AppDelegate.h */, 80 | E438B46D1D73D16800001DD4 /* AppDelegate.m */, 81 | E438B4721D73D16800001DD4 /* ViewController.h */, 82 | E438B4731D73D16800001DD4 /* ViewController.m */, 83 | E438B4751D73D16800001DD4 /* Assets.xcassets */, 84 | E438B4771D73D16800001DD4 /* Main.storyboard */, 85 | E438B47A1D73D16800001DD4 /* Info.plist */, 86 | E438B46F1D73D16800001DD4 /* Supporting Files */, 87 | ); 88 | path = YWCLocalizeTool; 89 | sourceTree = ""; 90 | }; 91 | E438B46F1D73D16800001DD4 /* Supporting Files */ = { 92 | isa = PBXGroup; 93 | children = ( 94 | E438B4701D73D16800001DD4 /* main.m */, 95 | ); 96 | name = "Supporting Files"; 97 | sourceTree = ""; 98 | }; 99 | E438B4801D73D76100001DD4 /* AFNetworking */ = { 100 | isa = PBXGroup; 101 | children = ( 102 | E438B4811D73D76100001DD4 /* AFHTTPSessionManager.h */, 103 | E438B4821D73D76100001DD4 /* AFHTTPSessionManager.m */, 104 | E438B4831D73D76100001DD4 /* AFNetworking.h */, 105 | E438B4841D73D76100001DD4 /* AFNetworkReachabilityManager.h */, 106 | E438B4851D73D76100001DD4 /* AFNetworkReachabilityManager.m */, 107 | E438B4861D73D76100001DD4 /* AFSecurityPolicy.h */, 108 | E438B4871D73D76100001DD4 /* AFSecurityPolicy.m */, 109 | E438B4881D73D76100001DD4 /* AFURLRequestSerialization.h */, 110 | E438B4891D73D76100001DD4 /* AFURLRequestSerialization.m */, 111 | E438B48A1D73D76100001DD4 /* AFURLResponseSerialization.h */, 112 | E438B48B1D73D76100001DD4 /* AFURLResponseSerialization.m */, 113 | E438B48C1D73D76100001DD4 /* AFURLSessionManager.h */, 114 | E438B48D1D73D76100001DD4 /* AFURLSessionManager.m */, 115 | ); 116 | path = AFNetworking; 117 | sourceTree = ""; 118 | }; 119 | /* End PBXGroup section */ 120 | 121 | /* Begin PBXNativeTarget section */ 122 | E438B4681D73D16800001DD4 /* YWCLocalizeTool */ = { 123 | isa = PBXNativeTarget; 124 | buildConfigurationList = E438B47D1D73D16800001DD4 /* Build configuration list for PBXNativeTarget "YWCLocalizeTool" */; 125 | buildPhases = ( 126 | E438B4651D73D16800001DD4 /* Sources */, 127 | E438B4661D73D16800001DD4 /* Frameworks */, 128 | E438B4671D73D16800001DD4 /* Resources */, 129 | ); 130 | buildRules = ( 131 | ); 132 | dependencies = ( 133 | ); 134 | name = YWCLocalizeTool; 135 | productName = YWCLocalizeTool; 136 | productReference = E438B4691D73D16800001DD4 /* YWCLocalizeTool.app */; 137 | productType = "com.apple.product-type.application"; 138 | }; 139 | /* End PBXNativeTarget section */ 140 | 141 | /* Begin PBXProject section */ 142 | E438B4611D73D16800001DD4 /* Project object */ = { 143 | isa = PBXProject; 144 | attributes = { 145 | LastUpgradeCheck = 0730; 146 | ORGANIZATIONNAME = YangWeicheng; 147 | TargetAttributes = { 148 | E438B4681D73D16800001DD4 = { 149 | CreatedOnToolsVersion = 7.3.1; 150 | }; 151 | }; 152 | }; 153 | buildConfigurationList = E438B4641D73D16800001DD4 /* Build configuration list for PBXProject "YWCLocalizeTool" */; 154 | compatibilityVersion = "Xcode 3.2"; 155 | developmentRegion = English; 156 | hasScannedForEncodings = 0; 157 | knownRegions = ( 158 | en, 159 | Base, 160 | ); 161 | mainGroup = E438B4601D73D16800001DD4; 162 | productRefGroup = E438B46A1D73D16800001DD4 /* Products */; 163 | projectDirPath = ""; 164 | projectRoot = ""; 165 | targets = ( 166 | E438B4681D73D16800001DD4 /* YWCLocalizeTool */, 167 | ); 168 | }; 169 | /* End PBXProject section */ 170 | 171 | /* Begin PBXResourcesBuildPhase section */ 172 | E438B4671D73D16800001DD4 /* Resources */ = { 173 | isa = PBXResourcesBuildPhase; 174 | buildActionMask = 2147483647; 175 | files = ( 176 | E438B4761D73D16800001DD4 /* Assets.xcassets in Resources */, 177 | E438B4791D73D16800001DD4 /* Main.storyboard in Resources */, 178 | ); 179 | runOnlyForDeploymentPostprocessing = 0; 180 | }; 181 | /* End PBXResourcesBuildPhase section */ 182 | 183 | /* Begin PBXSourcesBuildPhase section */ 184 | E438B4651D73D16800001DD4 /* Sources */ = { 185 | isa = PBXSourcesBuildPhase; 186 | buildActionMask = 2147483647; 187 | files = ( 188 | E438B4931D73D76100001DD4 /* AFURLSessionManager.m in Sources */, 189 | E438B4741D73D16800001DD4 /* ViewController.m in Sources */, 190 | E438B4711D73D16800001DD4 /* main.m in Sources */, 191 | E438B48F1D73D76100001DD4 /* AFNetworkReachabilityManager.m in Sources */, 192 | E438B46E1D73D16800001DD4 /* AppDelegate.m in Sources */, 193 | E438B4901D73D76100001DD4 /* AFSecurityPolicy.m in Sources */, 194 | E438B4911D73D76100001DD4 /* AFURLRequestSerialization.m in Sources */, 195 | E438B4921D73D76100001DD4 /* AFURLResponseSerialization.m in Sources */, 196 | E438B48E1D73D76100001DD4 /* AFHTTPSessionManager.m in Sources */, 197 | ); 198 | runOnlyForDeploymentPostprocessing = 0; 199 | }; 200 | /* End PBXSourcesBuildPhase section */ 201 | 202 | /* Begin PBXVariantGroup section */ 203 | E438B4771D73D16800001DD4 /* Main.storyboard */ = { 204 | isa = PBXVariantGroup; 205 | children = ( 206 | E438B4781D73D16800001DD4 /* Base */, 207 | ); 208 | name = Main.storyboard; 209 | sourceTree = ""; 210 | }; 211 | /* End PBXVariantGroup section */ 212 | 213 | /* Begin XCBuildConfiguration section */ 214 | E438B47B1D73D16800001DD4 /* Debug */ = { 215 | isa = XCBuildConfiguration; 216 | buildSettings = { 217 | ALWAYS_SEARCH_USER_PATHS = NO; 218 | CLANG_ANALYZER_NONNULL = YES; 219 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 220 | CLANG_CXX_LIBRARY = "libc++"; 221 | CLANG_ENABLE_MODULES = YES; 222 | CLANG_ENABLE_OBJC_ARC = YES; 223 | CLANG_WARN_BOOL_CONVERSION = YES; 224 | CLANG_WARN_CONSTANT_CONVERSION = YES; 225 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 226 | CLANG_WARN_EMPTY_BODY = YES; 227 | CLANG_WARN_ENUM_CONVERSION = YES; 228 | CLANG_WARN_INT_CONVERSION = YES; 229 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 230 | CLANG_WARN_UNREACHABLE_CODE = YES; 231 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 232 | CODE_SIGN_IDENTITY = "-"; 233 | COPY_PHASE_STRIP = NO; 234 | DEBUG_INFORMATION_FORMAT = dwarf; 235 | ENABLE_STRICT_OBJC_MSGSEND = YES; 236 | ENABLE_TESTABILITY = YES; 237 | GCC_C_LANGUAGE_STANDARD = gnu99; 238 | GCC_DYNAMIC_NO_PIC = NO; 239 | GCC_NO_COMMON_BLOCKS = YES; 240 | GCC_OPTIMIZATION_LEVEL = 0; 241 | GCC_PREPROCESSOR_DEFINITIONS = ( 242 | "DEBUG=1", 243 | "$(inherited)", 244 | ); 245 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 246 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 247 | GCC_WARN_UNDECLARED_SELECTOR = YES; 248 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 249 | GCC_WARN_UNUSED_FUNCTION = YES; 250 | GCC_WARN_UNUSED_VARIABLE = YES; 251 | MACOSX_DEPLOYMENT_TARGET = 10.11; 252 | MTL_ENABLE_DEBUG_INFO = YES; 253 | ONLY_ACTIVE_ARCH = YES; 254 | SDKROOT = macosx; 255 | }; 256 | name = Debug; 257 | }; 258 | E438B47C1D73D16800001DD4 /* Release */ = { 259 | isa = XCBuildConfiguration; 260 | buildSettings = { 261 | ALWAYS_SEARCH_USER_PATHS = NO; 262 | CLANG_ANALYZER_NONNULL = YES; 263 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 264 | CLANG_CXX_LIBRARY = "libc++"; 265 | CLANG_ENABLE_MODULES = YES; 266 | CLANG_ENABLE_OBJC_ARC = YES; 267 | CLANG_WARN_BOOL_CONVERSION = YES; 268 | CLANG_WARN_CONSTANT_CONVERSION = YES; 269 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 270 | CLANG_WARN_EMPTY_BODY = YES; 271 | CLANG_WARN_ENUM_CONVERSION = YES; 272 | CLANG_WARN_INT_CONVERSION = YES; 273 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 274 | CLANG_WARN_UNREACHABLE_CODE = YES; 275 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 276 | CODE_SIGN_IDENTITY = "-"; 277 | COPY_PHASE_STRIP = NO; 278 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 279 | ENABLE_NS_ASSERTIONS = NO; 280 | ENABLE_STRICT_OBJC_MSGSEND = YES; 281 | GCC_C_LANGUAGE_STANDARD = gnu99; 282 | GCC_NO_COMMON_BLOCKS = YES; 283 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 284 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 285 | GCC_WARN_UNDECLARED_SELECTOR = YES; 286 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 287 | GCC_WARN_UNUSED_FUNCTION = YES; 288 | GCC_WARN_UNUSED_VARIABLE = YES; 289 | MACOSX_DEPLOYMENT_TARGET = 10.11; 290 | MTL_ENABLE_DEBUG_INFO = NO; 291 | SDKROOT = macosx; 292 | }; 293 | name = Release; 294 | }; 295 | E438B47E1D73D16800001DD4 /* Debug */ = { 296 | isa = XCBuildConfiguration; 297 | buildSettings = { 298 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 299 | COMBINE_HIDPI_IMAGES = YES; 300 | INFOPLIST_FILE = YWCLocalizeTool/Info.plist; 301 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; 302 | PRODUCT_BUNDLE_IDENTIFIER = YI.YWCLocalizeTool; 303 | PRODUCT_NAME = "$(TARGET_NAME)"; 304 | }; 305 | name = Debug; 306 | }; 307 | E438B47F1D73D16800001DD4 /* Release */ = { 308 | isa = XCBuildConfiguration; 309 | buildSettings = { 310 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 311 | COMBINE_HIDPI_IMAGES = YES; 312 | INFOPLIST_FILE = YWCLocalizeTool/Info.plist; 313 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; 314 | PRODUCT_BUNDLE_IDENTIFIER = YI.YWCLocalizeTool; 315 | PRODUCT_NAME = "$(TARGET_NAME)"; 316 | }; 317 | name = Release; 318 | }; 319 | /* End XCBuildConfiguration section */ 320 | 321 | /* Begin XCConfigurationList section */ 322 | E438B4641D73D16800001DD4 /* Build configuration list for PBXProject "YWCLocalizeTool" */ = { 323 | isa = XCConfigurationList; 324 | buildConfigurations = ( 325 | E438B47B1D73D16800001DD4 /* Debug */, 326 | E438B47C1D73D16800001DD4 /* Release */, 327 | ); 328 | defaultConfigurationIsVisible = 0; 329 | defaultConfigurationName = Release; 330 | }; 331 | E438B47D1D73D16800001DD4 /* Build configuration list for PBXNativeTarget "YWCLocalizeTool" */ = { 332 | isa = XCConfigurationList; 333 | buildConfigurations = ( 334 | E438B47E1D73D16800001DD4 /* Debug */, 335 | E438B47F1D73D16800001DD4 /* Release */, 336 | ); 337 | defaultConfigurationIsVisible = 0; 338 | }; 339 | /* End XCConfigurationList section */ 340 | }; 341 | rootObject = E438B4611D73D16800001DD4 /* Project object */; 342 | } 343 | -------------------------------------------------------------------------------- /YWCLocalizeTool.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /YWCLocalizeTool.xcodeproj/project.xcworkspace/xcuserdata/YangWeicheng.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Andy1984/YWCLocalizeTool/417dfe56946b42c076432e5c4732e5c20bcd9052/YWCLocalizeTool.xcodeproj/project.xcworkspace/xcuserdata/YangWeicheng.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /YWCLocalizeTool.xcodeproj/xcuserdata/YangWeicheng.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 8 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /YWCLocalizeTool.xcodeproj/xcuserdata/YangWeicheng.xcuserdatad/xcschemes/YWCLocalizeTool.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 32 | 33 | 39 | 40 | 41 | 42 | 43 | 44 | 54 | 56 | 62 | 63 | 64 | 65 | 66 | 67 | 73 | 75 | 81 | 82 | 83 | 84 | 86 | 87 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /YWCLocalizeTool.xcodeproj/xcuserdata/YangWeicheng.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | YWCLocalizeTool.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | E438B4681D73D16800001DD4 16 | 17 | primary 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /YWCLocalizeTool/AFNetworking/AFHTTPSessionManager.h: -------------------------------------------------------------------------------- 1 | // AFHTTPSessionManager.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | #if !TARGET_OS_WATCH 24 | #import 25 | #endif 26 | #import 27 | 28 | #if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV 29 | #import 30 | #else 31 | #import 32 | #endif 33 | 34 | #import "AFURLSessionManager.h" 35 | 36 | /** 37 | `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. 38 | 39 | ## Subclassing Notes 40 | 41 | 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. 42 | 43 | For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect. 44 | 45 | ## Methods to Override 46 | 47 | 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:`. 48 | 49 | ## Serialization 50 | 51 | Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to ``. 52 | 53 | Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `` 54 | 55 | ## URL Construction Using Relative Paths 56 | 57 | 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:`. 58 | 59 | Below are a few examples of how `baseURL` and relative paths interact: 60 | 61 | NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]; 62 | [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo 63 | [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz 64 | [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo 65 | [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo 66 | [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/ 67 | [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/ 68 | 69 | 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. 70 | 71 | @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. 72 | */ 73 | 74 | NS_ASSUME_NONNULL_BEGIN 75 | 76 | @interface AFHTTPSessionManager : AFURLSessionManager 77 | 78 | /** 79 | The URL used to construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. 80 | */ 81 | @property (readonly, nonatomic, strong, nullable) NSURL *baseURL; 82 | 83 | /** 84 | 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. 85 | 86 | @warning `requestSerializer` must not be `nil`. 87 | */ 88 | @property (nonatomic, strong) AFHTTPRequestSerializer * requestSerializer; 89 | 90 | /** 91 | 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`. 92 | 93 | @warning `responseSerializer` must not be `nil`. 94 | */ 95 | @property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; 96 | 97 | ///--------------------- 98 | /// @name Initialization 99 | ///--------------------- 100 | 101 | /** 102 | Creates and returns an `AFHTTPSessionManager` object. 103 | */ 104 | + (instancetype)manager; 105 | 106 | /** 107 | Initializes an `AFHTTPSessionManager` object with the specified base URL. 108 | 109 | @param url The base URL for the HTTP client. 110 | 111 | @return The newly-initialized HTTP client 112 | */ 113 | - (instancetype)initWithBaseURL:(nullable NSURL *)url; 114 | 115 | /** 116 | Initializes an `AFHTTPSessionManager` object with the specified base URL. 117 | 118 | This is the designated initializer. 119 | 120 | @param url The base URL for the HTTP client. 121 | @param configuration The configuration used to create the managed session. 122 | 123 | @return The newly-initialized HTTP client 124 | */ 125 | - (instancetype)initWithBaseURL:(nullable NSURL *)url 126 | sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; 127 | 128 | ///--------------------------- 129 | /// @name Making HTTP Requests 130 | ///--------------------------- 131 | 132 | /** 133 | Creates and runs an `NSURLSessionDataTask` with a `GET` request. 134 | 135 | @param URLString The URL string used to create the request URL. 136 | @param parameters The parameters to be encoded according to the client request serializer. 137 | @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. 138 | @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. 139 | 140 | @see -dataTaskWithRequest:completionHandler: 141 | */ 142 | - (nullable NSURLSessionDataTask *)GET:(NSString *)URLString 143 | parameters:(nullable id)parameters 144 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 145 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; 146 | 147 | 148 | /** 149 | Creates and runs an `NSURLSessionDataTask` with a `GET` request. 150 | 151 | @param URLString The URL string used to create the request URL. 152 | @param parameters The parameters to be encoded according to the client request serializer. 153 | @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. 154 | @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. 155 | @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. 156 | 157 | @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: 158 | */ 159 | - (nullable NSURLSessionDataTask *)GET:(NSString *)URLString 160 | parameters:(nullable id)parameters 161 | progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress 162 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 163 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; 164 | 165 | /** 166 | Creates and runs an `NSURLSessionDataTask` with a `HEAD` request. 167 | 168 | @param URLString The URL string used to create the request URL. 169 | @param parameters The parameters to be encoded according to the client request serializer. 170 | @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. 171 | @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. 172 | 173 | @see -dataTaskWithRequest:completionHandler: 174 | */ 175 | - (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString 176 | parameters:(nullable id)parameters 177 | success:(nullable void (^)(NSURLSessionDataTask *task))success 178 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; 179 | 180 | /** 181 | Creates and runs an `NSURLSessionDataTask` with a `POST` request. 182 | 183 | @param URLString The URL string used to create the request URL. 184 | @param parameters The parameters to be encoded according to the client request serializer. 185 | @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. 186 | @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. 187 | 188 | @see -dataTaskWithRequest:completionHandler: 189 | */ 190 | - (nullable NSURLSessionDataTask *)POST:(NSString *)URLString 191 | parameters:(nullable id)parameters 192 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 193 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; 194 | 195 | /** 196 | Creates and runs an `NSURLSessionDataTask` with a `POST` request. 197 | 198 | @param URLString The URL string used to create the request URL. 199 | @param parameters The parameters to be encoded according to the client request serializer. 200 | @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. 201 | @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. 202 | @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. 203 | 204 | @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: 205 | */ 206 | - (nullable NSURLSessionDataTask *)POST:(NSString *)URLString 207 | parameters:(nullable id)parameters 208 | progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress 209 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 210 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; 211 | 212 | /** 213 | Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. 214 | 215 | @param URLString The URL string used to create the request URL. 216 | @param parameters The parameters to be encoded according to the client request serializer. 217 | @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. 218 | @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. 219 | @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. 220 | 221 | @see -dataTaskWithRequest:completionHandler: 222 | */ 223 | - (nullable NSURLSessionDataTask *)POST:(NSString *)URLString 224 | parameters:(nullable id)parameters 225 | constructingBodyWithBlock:(nullable void (^)(id formData))block 226 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 227 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; 228 | 229 | /** 230 | Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. 231 | 232 | @param URLString The URL string used to create the request URL. 233 | @param parameters The parameters to be encoded according to the client request serializer. 234 | @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. 235 | @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. 236 | @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. 237 | @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. 238 | 239 | @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: 240 | */ 241 | - (nullable NSURLSessionDataTask *)POST:(NSString *)URLString 242 | parameters:(nullable id)parameters 243 | constructingBodyWithBlock:(nullable void (^)(id formData))block 244 | progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress 245 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 246 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; 247 | 248 | /** 249 | Creates and runs an `NSURLSessionDataTask` with a `PUT` request. 250 | 251 | @param URLString The URL string used to create the request URL. 252 | @param parameters The parameters to be encoded according to the client request serializer. 253 | @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. 254 | @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. 255 | 256 | @see -dataTaskWithRequest:completionHandler: 257 | */ 258 | - (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString 259 | parameters:(nullable id)parameters 260 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 261 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; 262 | 263 | /** 264 | Creates and runs an `NSURLSessionDataTask` with a `PATCH` request. 265 | 266 | @param URLString The URL string used to create the request URL. 267 | @param parameters The parameters to be encoded according to the client request serializer. 268 | @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. 269 | @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. 270 | 271 | @see -dataTaskWithRequest:completionHandler: 272 | */ 273 | - (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString 274 | parameters:(nullable id)parameters 275 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 276 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; 277 | 278 | /** 279 | Creates and runs an `NSURLSessionDataTask` with a `DELETE` request. 280 | 281 | @param URLString The URL string used to create the request URL. 282 | @param parameters The parameters to be encoded according to the client request serializer. 283 | @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. 284 | @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. 285 | 286 | @see -dataTaskWithRequest:completionHandler: 287 | */ 288 | - (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString 289 | parameters:(nullable id)parameters 290 | success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success 291 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; 292 | 293 | @end 294 | 295 | NS_ASSUME_NONNULL_END 296 | -------------------------------------------------------------------------------- /YWCLocalizeTool/AFNetworking/AFHTTPSessionManager.m: -------------------------------------------------------------------------------- 1 | // AFHTTPSessionManager.m 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFHTTPSessionManager.h" 23 | 24 | #import "AFURLRequestSerialization.h" 25 | #import "AFURLResponseSerialization.h" 26 | 27 | #import 28 | #import 29 | #import 30 | 31 | #import 32 | #import 33 | #import 34 | #import 35 | #import 36 | 37 | #if TARGET_OS_IOS || TARGET_OS_TV 38 | #import 39 | #elif TARGET_OS_WATCH 40 | #import 41 | #endif 42 | 43 | @interface AFHTTPSessionManager () 44 | @property (readwrite, nonatomic, strong) NSURL *baseURL; 45 | @end 46 | 47 | @implementation AFHTTPSessionManager 48 | @dynamic responseSerializer; 49 | 50 | + (instancetype)manager { 51 | return [[[self class] alloc] initWithBaseURL:nil]; 52 | } 53 | 54 | - (instancetype)init { 55 | return [self initWithBaseURL:nil]; 56 | } 57 | 58 | - (instancetype)initWithBaseURL:(NSURL *)url { 59 | return [self initWithBaseURL:url sessionConfiguration:nil]; 60 | } 61 | 62 | - (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { 63 | return [self initWithBaseURL:nil sessionConfiguration:configuration]; 64 | } 65 | 66 | - (instancetype)initWithBaseURL:(NSURL *)url 67 | sessionConfiguration:(NSURLSessionConfiguration *)configuration 68 | { 69 | self = [super initWithSessionConfiguration:configuration]; 70 | if (!self) { 71 | return nil; 72 | } 73 | 74 | // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected 75 | if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { 76 | url = [url URLByAppendingPathComponent:@""]; 77 | } 78 | 79 | self.baseURL = url; 80 | 81 | self.requestSerializer = [AFHTTPRequestSerializer serializer]; 82 | self.responseSerializer = [AFJSONResponseSerializer serializer]; 83 | 84 | return self; 85 | } 86 | 87 | #pragma mark - 88 | 89 | - (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { 90 | NSParameterAssert(requestSerializer); 91 | 92 | _requestSerializer = requestSerializer; 93 | } 94 | 95 | - (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { 96 | NSParameterAssert(responseSerializer); 97 | 98 | [super setResponseSerializer:responseSerializer]; 99 | } 100 | 101 | #pragma mark - 102 | 103 | - (NSURLSessionDataTask *)GET:(NSString *)URLString 104 | parameters:(id)parameters 105 | success:(void (^)(NSURLSessionDataTask *task, id responseObject))success 106 | failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure 107 | { 108 | 109 | return [self GET:URLString parameters:parameters progress:nil success:success failure:failure]; 110 | } 111 | 112 | - (NSURLSessionDataTask *)GET:(NSString *)URLString 113 | parameters:(id)parameters 114 | progress:(void (^)(NSProgress * _Nonnull))downloadProgress 115 | success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success 116 | failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure 117 | { 118 | 119 | NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" 120 | URLString:URLString 121 | parameters:parameters 122 | uploadProgress:nil 123 | downloadProgress:downloadProgress 124 | success:success 125 | failure:failure]; 126 | 127 | [dataTask resume]; 128 | 129 | return dataTask; 130 | } 131 | 132 | - (NSURLSessionDataTask *)HEAD:(NSString *)URLString 133 | parameters:(id)parameters 134 | success:(void (^)(NSURLSessionDataTask *task))success 135 | failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure 136 | { 137 | NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) { 138 | if (success) { 139 | success(task); 140 | } 141 | } failure:failure]; 142 | 143 | [dataTask resume]; 144 | 145 | return dataTask; 146 | } 147 | 148 | - (NSURLSessionDataTask *)POST:(NSString *)URLString 149 | parameters:(id)parameters 150 | success:(void (^)(NSURLSessionDataTask *task, id responseObject))success 151 | failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure 152 | { 153 | return [self POST:URLString parameters:parameters progress:nil success:success failure:failure]; 154 | } 155 | 156 | - (NSURLSessionDataTask *)POST:(NSString *)URLString 157 | parameters:(id)parameters 158 | progress:(void (^)(NSProgress * _Nonnull))uploadProgress 159 | success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success 160 | failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure 161 | { 162 | NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure]; 163 | 164 | [dataTask resume]; 165 | 166 | return dataTask; 167 | } 168 | 169 | - (NSURLSessionDataTask *)POST:(NSString *)URLString 170 | parameters:(nullable id)parameters 171 | constructingBodyWithBlock:(nullable void (^)(id _Nonnull))block 172 | success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success 173 | failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure 174 | { 175 | return [self POST:URLString parameters:parameters constructingBodyWithBlock:block progress:nil success:success failure:failure]; 176 | } 177 | 178 | - (NSURLSessionDataTask *)POST:(NSString *)URLString 179 | parameters:(id)parameters 180 | constructingBodyWithBlock:(void (^)(id formData))block 181 | progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress 182 | success:(void (^)(NSURLSessionDataTask *task, id responseObject))success 183 | failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure 184 | { 185 | NSError *serializationError = nil; 186 | NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError]; 187 | if (serializationError) { 188 | if (failure) { 189 | dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ 190 | failure(nil, serializationError); 191 | }); 192 | } 193 | 194 | return nil; 195 | } 196 | 197 | __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { 198 | if (error) { 199 | if (failure) { 200 | failure(task, error); 201 | } 202 | } else { 203 | if (success) { 204 | success(task, responseObject); 205 | } 206 | } 207 | }]; 208 | 209 | [task resume]; 210 | 211 | return task; 212 | } 213 | 214 | - (NSURLSessionDataTask *)PUT:(NSString *)URLString 215 | parameters:(id)parameters 216 | success:(void (^)(NSURLSessionDataTask *task, id responseObject))success 217 | failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure 218 | { 219 | NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; 220 | 221 | [dataTask resume]; 222 | 223 | return dataTask; 224 | } 225 | 226 | - (NSURLSessionDataTask *)PATCH:(NSString *)URLString 227 | parameters:(id)parameters 228 | success:(void (^)(NSURLSessionDataTask *task, id responseObject))success 229 | failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure 230 | { 231 | NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; 232 | 233 | [dataTask resume]; 234 | 235 | return dataTask; 236 | } 237 | 238 | - (NSURLSessionDataTask *)DELETE:(NSString *)URLString 239 | parameters:(id)parameters 240 | success:(void (^)(NSURLSessionDataTask *task, id responseObject))success 241 | failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure 242 | { 243 | NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; 244 | 245 | [dataTask resume]; 246 | 247 | return dataTask; 248 | } 249 | 250 | - (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method 251 | URLString:(NSString *)URLString 252 | parameters:(id)parameters 253 | uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress 254 | downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress 255 | success:(void (^)(NSURLSessionDataTask *, id))success 256 | failure:(void (^)(NSURLSessionDataTask *, NSError *))failure 257 | { 258 | NSError *serializationError = nil; 259 | NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError]; 260 | if (serializationError) { 261 | if (failure) { 262 | dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ 263 | failure(nil, serializationError); 264 | }); 265 | } 266 | 267 | return nil; 268 | } 269 | 270 | __block NSURLSessionDataTask *dataTask = nil; 271 | dataTask = [self dataTaskWithRequest:request 272 | uploadProgress:uploadProgress 273 | downloadProgress:downloadProgress 274 | completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { 275 | if (error) { 276 | if (failure) { 277 | failure(dataTask, error); 278 | } 279 | } else { 280 | if (success) { 281 | success(dataTask, responseObject); 282 | } 283 | } 284 | }]; 285 | 286 | return dataTask; 287 | } 288 | 289 | #pragma mark - NSObject 290 | 291 | - (NSString *)description { 292 | return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue]; 293 | } 294 | 295 | #pragma mark - NSSecureCoding 296 | 297 | + (BOOL)supportsSecureCoding { 298 | return YES; 299 | } 300 | 301 | - (instancetype)initWithCoder:(NSCoder *)decoder { 302 | NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))]; 303 | NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; 304 | if (!configuration) { 305 | NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"]; 306 | if (configurationIdentifier) { 307 | #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) 308 | configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier]; 309 | #else 310 | configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier]; 311 | #endif 312 | } 313 | } 314 | 315 | self = [self initWithBaseURL:baseURL sessionConfiguration:configuration]; 316 | if (!self) { 317 | return nil; 318 | } 319 | 320 | self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; 321 | self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; 322 | AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))]; 323 | if (decodedPolicy) { 324 | self.securityPolicy = decodedPolicy; 325 | } 326 | 327 | return self; 328 | } 329 | 330 | - (void)encodeWithCoder:(NSCoder *)coder { 331 | [super encodeWithCoder:coder]; 332 | 333 | [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))]; 334 | if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) { 335 | [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; 336 | } else { 337 | [coder encodeObject:self.session.configuration.identifier forKey:@"identifier"]; 338 | } 339 | [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; 340 | [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; 341 | [coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))]; 342 | } 343 | 344 | #pragma mark - NSCopying 345 | 346 | - (instancetype)copyWithZone:(NSZone *)zone { 347 | AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration]; 348 | 349 | HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; 350 | HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; 351 | HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone]; 352 | return HTTPClient; 353 | } 354 | 355 | @end 356 | -------------------------------------------------------------------------------- /YWCLocalizeTool/AFNetworking/AFNetworkReachabilityManager.h: -------------------------------------------------------------------------------- 1 | // AFNetworkReachabilityManager.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #if !TARGET_OS_WATCH 25 | #import 26 | 27 | typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { 28 | AFNetworkReachabilityStatusUnknown = -1, 29 | AFNetworkReachabilityStatusNotReachable = 0, 30 | AFNetworkReachabilityStatusReachableViaWWAN = 1, 31 | AFNetworkReachabilityStatusReachableViaWiFi = 2, 32 | }; 33 | 34 | NS_ASSUME_NONNULL_BEGIN 35 | 36 | /** 37 | `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. 38 | 39 | 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. 40 | 41 | See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ ) 42 | 43 | @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined. 44 | */ 45 | @interface AFNetworkReachabilityManager : NSObject 46 | 47 | /** 48 | The current network reachability status. 49 | */ 50 | @property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; 51 | 52 | /** 53 | Whether or not the network is currently reachable. 54 | */ 55 | @property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable; 56 | 57 | /** 58 | Whether or not the network is currently reachable via WWAN. 59 | */ 60 | @property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN; 61 | 62 | /** 63 | Whether or not the network is currently reachable via WiFi. 64 | */ 65 | @property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi; 66 | 67 | ///--------------------- 68 | /// @name Initialization 69 | ///--------------------- 70 | 71 | /** 72 | Returns the shared network reachability manager. 73 | */ 74 | + (instancetype)sharedManager; 75 | 76 | /** 77 | Creates and returns a network reachability manager with the default socket address. 78 | 79 | @return An initialized network reachability manager, actively monitoring the default socket address. 80 | */ 81 | + (instancetype)manager; 82 | 83 | /** 84 | Creates and returns a network reachability manager for the specified domain. 85 | 86 | @param domain The domain used to evaluate network reachability. 87 | 88 | @return An initialized network reachability manager, actively monitoring the specified domain. 89 | */ 90 | + (instancetype)managerForDomain:(NSString *)domain; 91 | 92 | /** 93 | Creates and returns a network reachability manager for the socket address. 94 | 95 | @param address The socket address (`sockaddr_in6`) used to evaluate network reachability. 96 | 97 | @return An initialized network reachability manager, actively monitoring the specified socket address. 98 | */ 99 | + (instancetype)managerForAddress:(const void *)address; 100 | 101 | /** 102 | Initializes an instance of a network reachability manager from the specified reachability object. 103 | 104 | @param reachability The reachability object to monitor. 105 | 106 | @return An initialized network reachability manager, actively monitoring the specified reachability. 107 | */ 108 | - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER; 109 | 110 | ///-------------------------------------------------- 111 | /// @name Starting & Stopping Reachability Monitoring 112 | ///-------------------------------------------------- 113 | 114 | /** 115 | Starts monitoring for changes in network reachability status. 116 | */ 117 | - (void)startMonitoring; 118 | 119 | /** 120 | Stops monitoring for changes in network reachability status. 121 | */ 122 | - (void)stopMonitoring; 123 | 124 | ///------------------------------------------------- 125 | /// @name Getting Localized Reachability Description 126 | ///------------------------------------------------- 127 | 128 | /** 129 | Returns a localized string representation of the current network reachability status. 130 | */ 131 | - (NSString *)localizedNetworkReachabilityStatusString; 132 | 133 | ///--------------------------------------------------- 134 | /// @name Setting Network Reachability Change Callback 135 | ///--------------------------------------------------- 136 | 137 | /** 138 | Sets a callback to be executed when the network availability of the `baseURL` host changes. 139 | 140 | @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`. 141 | */ 142 | - (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block; 143 | 144 | @end 145 | 146 | ///---------------- 147 | /// @name Constants 148 | ///---------------- 149 | 150 | /** 151 | ## Network Reachability 152 | 153 | The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses. 154 | 155 | enum { 156 | AFNetworkReachabilityStatusUnknown, 157 | AFNetworkReachabilityStatusNotReachable, 158 | AFNetworkReachabilityStatusReachableViaWWAN, 159 | AFNetworkReachabilityStatusReachableViaWiFi, 160 | } 161 | 162 | `AFNetworkReachabilityStatusUnknown` 163 | The `baseURL` host reachability is not known. 164 | 165 | `AFNetworkReachabilityStatusNotReachable` 166 | The `baseURL` host cannot be reached. 167 | 168 | `AFNetworkReachabilityStatusReachableViaWWAN` 169 | The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS. 170 | 171 | `AFNetworkReachabilityStatusReachableViaWiFi` 172 | The `baseURL` host can be reached via a Wi-Fi connection. 173 | 174 | ### Keys for Notification UserInfo Dictionary 175 | 176 | Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification. 177 | 178 | `AFNetworkingReachabilityNotificationStatusItem` 179 | A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification. 180 | The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status. 181 | */ 182 | 183 | ///-------------------- 184 | /// @name Notifications 185 | ///-------------------- 186 | 187 | /** 188 | Posted when network reachability changes. 189 | 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. 190 | 191 | @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`). 192 | */ 193 | FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification; 194 | FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem; 195 | 196 | ///-------------------- 197 | /// @name Functions 198 | ///-------------------- 199 | 200 | /** 201 | Returns a localized string representation of an `AFNetworkReachabilityStatus` value. 202 | */ 203 | FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); 204 | 205 | NS_ASSUME_NONNULL_END 206 | #endif 207 | -------------------------------------------------------------------------------- /YWCLocalizeTool/AFNetworking/AFNetworkReachabilityManager.m: -------------------------------------------------------------------------------- 1 | // AFNetworkReachabilityManager.m 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFNetworkReachabilityManager.h" 23 | #if !TARGET_OS_WATCH 24 | 25 | #import 26 | #import 27 | #import 28 | #import 29 | #import 30 | 31 | NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change"; 32 | NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem"; 33 | 34 | typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status); 35 | 36 | NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) { 37 | switch (status) { 38 | case AFNetworkReachabilityStatusNotReachable: 39 | return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil); 40 | case AFNetworkReachabilityStatusReachableViaWWAN: 41 | return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil); 42 | case AFNetworkReachabilityStatusReachableViaWiFi: 43 | return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil); 44 | case AFNetworkReachabilityStatusUnknown: 45 | default: 46 | return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil); 47 | } 48 | } 49 | 50 | static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) { 51 | BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0); 52 | BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0); 53 | BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)); 54 | BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0); 55 | BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction)); 56 | 57 | AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown; 58 | if (isNetworkReachable == NO) { 59 | status = AFNetworkReachabilityStatusNotReachable; 60 | } 61 | #if TARGET_OS_IPHONE 62 | else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) { 63 | status = AFNetworkReachabilityStatusReachableViaWWAN; 64 | } 65 | #endif 66 | else { 67 | status = AFNetworkReachabilityStatusReachableViaWiFi; 68 | } 69 | 70 | return status; 71 | } 72 | 73 | /** 74 | * Queue a status change notification for the main thread. 75 | * 76 | * This is done to ensure that the notifications are received in the same order 77 | * as they are sent. If notifications are sent directly, it is possible that 78 | * a queued notification (for an earlier status condition) is processed after 79 | * the later update, resulting in the listener being left in the wrong state. 80 | */ 81 | static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusBlock block) { 82 | AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); 83 | dispatch_async(dispatch_get_main_queue(), ^{ 84 | if (block) { 85 | block(status); 86 | } 87 | NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 88 | NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) }; 89 | [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo]; 90 | }); 91 | } 92 | 93 | static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { 94 | AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusBlock)info); 95 | } 96 | 97 | 98 | static const void * AFNetworkReachabilityRetainCallback(const void *info) { 99 | return Block_copy(info); 100 | } 101 | 102 | static void AFNetworkReachabilityReleaseCallback(const void *info) { 103 | if (info) { 104 | Block_release(info); 105 | } 106 | } 107 | 108 | @interface AFNetworkReachabilityManager () 109 | @property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability; 110 | @property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; 111 | @property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; 112 | @end 113 | 114 | @implementation AFNetworkReachabilityManager 115 | 116 | + (instancetype)sharedManager { 117 | static AFNetworkReachabilityManager *_sharedManager = nil; 118 | static dispatch_once_t onceToken; 119 | dispatch_once(&onceToken, ^{ 120 | _sharedManager = [self manager]; 121 | }); 122 | 123 | return _sharedManager; 124 | } 125 | 126 | + (instancetype)managerForDomain:(NSString *)domain { 127 | SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); 128 | 129 | AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; 130 | 131 | CFRelease(reachability); 132 | 133 | return manager; 134 | } 135 | 136 | + (instancetype)managerForAddress:(const void *)address { 137 | SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address); 138 | AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; 139 | 140 | CFRelease(reachability); 141 | 142 | return manager; 143 | } 144 | 145 | + (instancetype)manager 146 | { 147 | #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) 148 | struct sockaddr_in6 address; 149 | bzero(&address, sizeof(address)); 150 | address.sin6_len = sizeof(address); 151 | address.sin6_family = AF_INET6; 152 | #else 153 | struct sockaddr_in address; 154 | bzero(&address, sizeof(address)); 155 | address.sin_len = sizeof(address); 156 | address.sin_family = AF_INET; 157 | #endif 158 | return [self managerForAddress:&address]; 159 | } 160 | 161 | - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { 162 | self = [super init]; 163 | if (!self) { 164 | return nil; 165 | } 166 | 167 | _networkReachability = CFRetain(reachability); 168 | self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; 169 | 170 | return self; 171 | } 172 | 173 | - (instancetype)init NS_UNAVAILABLE 174 | { 175 | return nil; 176 | } 177 | 178 | - (void)dealloc { 179 | [self stopMonitoring]; 180 | 181 | if (_networkReachability != NULL) { 182 | CFRelease(_networkReachability); 183 | } 184 | } 185 | 186 | #pragma mark - 187 | 188 | - (BOOL)isReachable { 189 | return [self isReachableViaWWAN] || [self isReachableViaWiFi]; 190 | } 191 | 192 | - (BOOL)isReachableViaWWAN { 193 | return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN; 194 | } 195 | 196 | - (BOOL)isReachableViaWiFi { 197 | return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi; 198 | } 199 | 200 | #pragma mark - 201 | 202 | - (void)startMonitoring { 203 | [self stopMonitoring]; 204 | 205 | if (!self.networkReachability) { 206 | return; 207 | } 208 | 209 | __weak __typeof(self)weakSelf = self; 210 | AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) { 211 | __strong __typeof(weakSelf)strongSelf = weakSelf; 212 | 213 | strongSelf.networkReachabilityStatus = status; 214 | if (strongSelf.networkReachabilityStatusBlock) { 215 | strongSelf.networkReachabilityStatusBlock(status); 216 | } 217 | 218 | }; 219 | 220 | SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; 221 | SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); 222 | SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); 223 | 224 | dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ 225 | SCNetworkReachabilityFlags flags; 226 | if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) { 227 | AFPostReachabilityStatusChange(flags, callback); 228 | } 229 | }); 230 | } 231 | 232 | - (void)stopMonitoring { 233 | if (!self.networkReachability) { 234 | return; 235 | } 236 | 237 | SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); 238 | } 239 | 240 | #pragma mark - 241 | 242 | - (NSString *)localizedNetworkReachabilityStatusString { 243 | return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus); 244 | } 245 | 246 | #pragma mark - 247 | 248 | - (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block { 249 | self.networkReachabilityStatusBlock = block; 250 | } 251 | 252 | #pragma mark - NSKeyValueObserving 253 | 254 | + (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { 255 | if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) { 256 | return [NSSet setWithObject:@"networkReachabilityStatus"]; 257 | } 258 | 259 | return [super keyPathsForValuesAffectingValueForKey:key]; 260 | } 261 | 262 | @end 263 | #endif 264 | -------------------------------------------------------------------------------- /YWCLocalizeTool/AFNetworking/AFNetworking.h: -------------------------------------------------------------------------------- 1 | // AFNetworking.h 2 | // 3 | // Copyright (c) 2013 AFNetworking (http://afnetworking.com/) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | #import 25 | #import 26 | 27 | #ifndef _AFNETWORKING_ 28 | #define _AFNETWORKING_ 29 | 30 | #import "AFURLRequestSerialization.h" 31 | #import "AFURLResponseSerialization.h" 32 | #import "AFSecurityPolicy.h" 33 | 34 | #if !TARGET_OS_WATCH 35 | #import "AFNetworkReachabilityManager.h" 36 | #endif 37 | 38 | #import "AFURLSessionManager.h" 39 | #import "AFHTTPSessionManager.h" 40 | 41 | #endif /* _AFNETWORKING_ */ 42 | -------------------------------------------------------------------------------- /YWCLocalizeTool/AFNetworking/AFSecurityPolicy.h: -------------------------------------------------------------------------------- 1 | // AFSecurityPolicy.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | #import 24 | 25 | typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { 26 | AFSSLPinningModeNone, 27 | AFSSLPinningModePublicKey, 28 | AFSSLPinningModeCertificate, 29 | }; 30 | 31 | /** 32 | `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. 33 | 34 | 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. 35 | */ 36 | 37 | NS_ASSUME_NONNULL_BEGIN 38 | 39 | @interface AFSecurityPolicy : NSObject 40 | 41 | /** 42 | The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. 43 | */ 44 | @property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode; 45 | 46 | /** 47 | The certificates used to evaluate server trust according to the SSL pinning mode. 48 | 49 | 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`. 50 | 51 | Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches. 52 | */ 53 | @property (nonatomic, strong, nullable) NSSet *pinnedCertificates; 54 | 55 | /** 56 | Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. 57 | */ 58 | @property (nonatomic, assign) BOOL allowInvalidCertificates; 59 | 60 | /** 61 | Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`. 62 | */ 63 | @property (nonatomic, assign) BOOL validatesDomainName; 64 | 65 | ///----------------------------------------- 66 | /// @name Getting Certificates from the Bundle 67 | ///----------------------------------------- 68 | 69 | /** 70 | 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`. 71 | 72 | @return The certificates included in the given bundle. 73 | */ 74 | + (NSSet *)certificatesInBundle:(NSBundle *)bundle; 75 | 76 | ///----------------------------------------- 77 | /// @name Getting Specific Security Policies 78 | ///----------------------------------------- 79 | 80 | /** 81 | 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. 82 | 83 | @return The default security policy. 84 | */ 85 | + (instancetype)defaultPolicy; 86 | 87 | ///--------------------- 88 | /// @name Initialization 89 | ///--------------------- 90 | 91 | /** 92 | Creates and returns a security policy with the specified pinning mode. 93 | 94 | @param pinningMode The SSL pinning mode. 95 | 96 | @return A new security policy. 97 | */ 98 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; 99 | 100 | /** 101 | Creates and returns a security policy with the specified pinning mode. 102 | 103 | @param pinningMode The SSL pinning mode. 104 | @param pinnedCertificates The certificates to pin against. 105 | 106 | @return A new security policy. 107 | */ 108 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates; 109 | 110 | ///------------------------------ 111 | /// @name Evaluating Server Trust 112 | ///------------------------------ 113 | 114 | /** 115 | Whether or not the specified server trust should be accepted, based on the security policy. 116 | 117 | This method should be used when responding to an authentication challenge from a server. 118 | 119 | @param serverTrust The X.509 certificate trust of the server. 120 | @param domain The domain of serverTrust. If `nil`, the domain will not be validated. 121 | 122 | @return Whether or not to trust the server. 123 | */ 124 | - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust 125 | forDomain:(nullable NSString *)domain; 126 | 127 | @end 128 | 129 | NS_ASSUME_NONNULL_END 130 | 131 | ///---------------- 132 | /// @name Constants 133 | ///---------------- 134 | 135 | /** 136 | ## SSL Pinning Modes 137 | 138 | The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes. 139 | 140 | enum { 141 | AFSSLPinningModeNone, 142 | AFSSLPinningModePublicKey, 143 | AFSSLPinningModeCertificate, 144 | } 145 | 146 | `AFSSLPinningModeNone` 147 | Do not used pinned certificates to validate servers. 148 | 149 | `AFSSLPinningModePublicKey` 150 | Validate host certificates against public keys of pinned certificates. 151 | 152 | `AFSSLPinningModeCertificate` 153 | Validate host certificates against pinned certificates. 154 | */ 155 | -------------------------------------------------------------------------------- /YWCLocalizeTool/AFNetworking/AFSecurityPolicy.m: -------------------------------------------------------------------------------- 1 | // AFSecurityPolicy.m 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFSecurityPolicy.h" 23 | 24 | #import 25 | 26 | #if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV 27 | static NSData * AFSecKeyGetData(SecKeyRef key) { 28 | CFDataRef data = NULL; 29 | 30 | __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out); 31 | 32 | return (__bridge_transfer NSData *)data; 33 | 34 | _out: 35 | if (data) { 36 | CFRelease(data); 37 | } 38 | 39 | return nil; 40 | } 41 | #endif 42 | 43 | static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { 44 | #if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV 45 | return [(__bridge id)key1 isEqual:(__bridge id)key2]; 46 | #else 47 | return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)]; 48 | #endif 49 | } 50 | 51 | static id AFPublicKeyForCertificate(NSData *certificate) { 52 | id allowedPublicKey = nil; 53 | SecCertificateRef allowedCertificate; 54 | SecCertificateRef allowedCertificates[1]; 55 | CFArrayRef tempCertificates = nil; 56 | SecPolicyRef policy = nil; 57 | SecTrustRef allowedTrust = nil; 58 | SecTrustResultType result; 59 | 60 | allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); 61 | __Require_Quiet(allowedCertificate != NULL, _out); 62 | 63 | allowedCertificates[0] = allowedCertificate; 64 | tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); 65 | 66 | policy = SecPolicyCreateBasicX509(); 67 | __Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out); 68 | __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out); 69 | 70 | allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); 71 | 72 | _out: 73 | if (allowedTrust) { 74 | CFRelease(allowedTrust); 75 | } 76 | 77 | if (policy) { 78 | CFRelease(policy); 79 | } 80 | 81 | if (tempCertificates) { 82 | CFRelease(tempCertificates); 83 | } 84 | 85 | if (allowedCertificate) { 86 | CFRelease(allowedCertificate); 87 | } 88 | 89 | return allowedPublicKey; 90 | } 91 | 92 | static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { 93 | BOOL isValid = NO; 94 | SecTrustResultType result; 95 | __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out); 96 | 97 | isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed); 98 | 99 | _out: 100 | return isValid; 101 | } 102 | 103 | static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) { 104 | CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); 105 | NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; 106 | 107 | for (CFIndex i = 0; i < certificateCount; i++) { 108 | SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); 109 | [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; 110 | } 111 | 112 | return [NSArray arrayWithArray:trustChain]; 113 | } 114 | 115 | static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { 116 | SecPolicyRef policy = SecPolicyCreateBasicX509(); 117 | CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); 118 | NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; 119 | for (CFIndex i = 0; i < certificateCount; i++) { 120 | SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); 121 | 122 | SecCertificateRef someCertificates[] = {certificate}; 123 | CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); 124 | 125 | SecTrustRef trust; 126 | __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); 127 | 128 | SecTrustResultType result; 129 | __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out); 130 | 131 | [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; 132 | 133 | _out: 134 | if (trust) { 135 | CFRelease(trust); 136 | } 137 | 138 | if (certificates) { 139 | CFRelease(certificates); 140 | } 141 | 142 | continue; 143 | } 144 | CFRelease(policy); 145 | 146 | return [NSArray arrayWithArray:trustChain]; 147 | } 148 | 149 | #pragma mark - 150 | 151 | @interface AFSecurityPolicy() 152 | @property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode; 153 | @property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys; 154 | @end 155 | 156 | @implementation AFSecurityPolicy 157 | 158 | + (NSSet *)certificatesInBundle:(NSBundle *)bundle { 159 | NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; 160 | 161 | NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]]; 162 | for (NSString *path in paths) { 163 | NSData *certificateData = [NSData dataWithContentsOfFile:path]; 164 | [certificates addObject:certificateData]; 165 | } 166 | 167 | return [NSSet setWithSet:certificates]; 168 | } 169 | 170 | + (NSSet *)defaultPinnedCertificates { 171 | static NSSet *_defaultPinnedCertificates = nil; 172 | static dispatch_once_t onceToken; 173 | dispatch_once(&onceToken, ^{ 174 | NSBundle *bundle = [NSBundle bundleForClass:[self class]]; 175 | _defaultPinnedCertificates = [self certificatesInBundle:bundle]; 176 | }); 177 | 178 | return _defaultPinnedCertificates; 179 | } 180 | 181 | + (instancetype)defaultPolicy { 182 | AFSecurityPolicy *securityPolicy = [[self alloc] init]; 183 | securityPolicy.SSLPinningMode = AFSSLPinningModeNone; 184 | 185 | return securityPolicy; 186 | } 187 | 188 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { 189 | return [self policyWithPinningMode:pinningMode withPinnedCertificates:[self defaultPinnedCertificates]]; 190 | } 191 | 192 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates { 193 | AFSecurityPolicy *securityPolicy = [[self alloc] init]; 194 | securityPolicy.SSLPinningMode = pinningMode; 195 | 196 | [securityPolicy setPinnedCertificates:pinnedCertificates]; 197 | 198 | return securityPolicy; 199 | } 200 | 201 | - (instancetype)init { 202 | self = [super init]; 203 | if (!self) { 204 | return nil; 205 | } 206 | 207 | self.validatesDomainName = YES; 208 | 209 | return self; 210 | } 211 | 212 | - (void)setPinnedCertificates:(NSSet *)pinnedCertificates { 213 | _pinnedCertificates = pinnedCertificates; 214 | 215 | if (self.pinnedCertificates) { 216 | NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]]; 217 | for (NSData *certificate in self.pinnedCertificates) { 218 | id publicKey = AFPublicKeyForCertificate(certificate); 219 | if (!publicKey) { 220 | continue; 221 | } 222 | [mutablePinnedPublicKeys addObject:publicKey]; 223 | } 224 | self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys]; 225 | } else { 226 | self.pinnedPublicKeys = nil; 227 | } 228 | } 229 | 230 | #pragma mark - 231 | 232 | - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust 233 | forDomain:(NSString *)domain 234 | { 235 | if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) { 236 | // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html 237 | // According to the docs, you should only trust your provided certs for evaluation. 238 | // Pinned certificates are added to the trust. Without pinned certificates, 239 | // there is nothing to evaluate against. 240 | // 241 | // From Apple Docs: 242 | // "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors). 243 | // Instead, add your own (self-signed) CA certificate to the list of trusted anchors." 244 | NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning."); 245 | return NO; 246 | } 247 | 248 | NSMutableArray *policies = [NSMutableArray array]; 249 | if (self.validatesDomainName) { 250 | [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)]; 251 | } else { 252 | [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()]; 253 | } 254 | 255 | SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies); 256 | 257 | if (self.SSLPinningMode == AFSSLPinningModeNone) { 258 | return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust); 259 | } else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) { 260 | return NO; 261 | } 262 | 263 | switch (self.SSLPinningMode) { 264 | case AFSSLPinningModeNone: 265 | default: 266 | return NO; 267 | case AFSSLPinningModeCertificate: { 268 | NSMutableArray *pinnedCertificates = [NSMutableArray array]; 269 | for (NSData *certificateData in self.pinnedCertificates) { 270 | [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)]; 271 | } 272 | SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates); 273 | 274 | if (!AFServerTrustIsValid(serverTrust)) { 275 | return NO; 276 | } 277 | 278 | // obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA) 279 | NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); 280 | 281 | for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) { 282 | if ([self.pinnedCertificates containsObject:trustChainCertificate]) { 283 | return YES; 284 | } 285 | } 286 | 287 | return NO; 288 | } 289 | case AFSSLPinningModePublicKey: { 290 | NSUInteger trustedPublicKeyCount = 0; 291 | NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust); 292 | 293 | for (id trustChainPublicKey in publicKeys) { 294 | for (id pinnedPublicKey in self.pinnedPublicKeys) { 295 | if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) { 296 | trustedPublicKeyCount += 1; 297 | } 298 | } 299 | } 300 | return trustedPublicKeyCount > 0; 301 | } 302 | } 303 | 304 | return NO; 305 | } 306 | 307 | #pragma mark - NSKeyValueObserving 308 | 309 | + (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys { 310 | return [NSSet setWithObject:@"pinnedCertificates"]; 311 | } 312 | 313 | #pragma mark - NSSecureCoding 314 | 315 | + (BOOL)supportsSecureCoding { 316 | return YES; 317 | } 318 | 319 | - (instancetype)initWithCoder:(NSCoder *)decoder { 320 | 321 | self = [self init]; 322 | if (!self) { 323 | return nil; 324 | } 325 | 326 | self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue]; 327 | self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; 328 | self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))]; 329 | self.pinnedCertificates = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(pinnedCertificates))]; 330 | 331 | return self; 332 | } 333 | 334 | - (void)encodeWithCoder:(NSCoder *)coder { 335 | [coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))]; 336 | [coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; 337 | [coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))]; 338 | [coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))]; 339 | } 340 | 341 | #pragma mark - NSCopying 342 | 343 | - (instancetype)copyWithZone:(NSZone *)zone { 344 | AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init]; 345 | securityPolicy.SSLPinningMode = self.SSLPinningMode; 346 | securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates; 347 | securityPolicy.validatesDomainName = self.validatesDomainName; 348 | securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone]; 349 | 350 | return securityPolicy; 351 | } 352 | 353 | @end 354 | -------------------------------------------------------------------------------- /YWCLocalizeTool/AFNetworking/AFURLRequestSerialization.h: -------------------------------------------------------------------------------- 1 | // AFURLRequestSerialization.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | #import 24 | 25 | #if TARGET_OS_IOS || TARGET_OS_TV 26 | #import 27 | #elif TARGET_OS_WATCH 28 | #import 29 | #endif 30 | 31 | NS_ASSUME_NONNULL_BEGIN 32 | 33 | /** 34 | Returns a percent-escaped string following RFC 3986 for a query string key or value. 35 | RFC 3986 states that the following characters are "reserved" characters. 36 | - General Delimiters: ":", "#", "[", "]", "@", "?", "/" 37 | - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" 38 | 39 | In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow 40 | query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" 41 | should be percent-escaped in the query string. 42 | 43 | @param string The string to be percent-escaped. 44 | 45 | @return The percent-escaped string. 46 | */ 47 | FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string); 48 | 49 | /** 50 | A helper method to generate encoded url query parameters for appending to the end of a URL. 51 | 52 | @param parameters A dictionary of key/values to be encoded. 53 | 54 | @return A url encoded query string 55 | */ 56 | FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters); 57 | 58 | /** 59 | 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. 60 | 61 | 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`. 62 | */ 63 | @protocol AFURLRequestSerialization 64 | 65 | /** 66 | Returns a request with the specified parameters encoded into a copy of the original request. 67 | 68 | @param request The original request. 69 | @param parameters The parameters to be encoded. 70 | @param error The error that occurred while attempting to encode the request parameters. 71 | 72 | @return A serialized request. 73 | */ 74 | - (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request 75 | withParameters:(nullable id)parameters 76 | error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; 77 | 78 | @end 79 | 80 | #pragma mark - 81 | 82 | /** 83 | 84 | */ 85 | typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) { 86 | AFHTTPRequestQueryStringDefaultStyle = 0, 87 | }; 88 | 89 | @protocol AFMultipartFormData; 90 | 91 | /** 92 | `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. 93 | 94 | Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior. 95 | */ 96 | @interface AFHTTPRequestSerializer : NSObject 97 | 98 | /** 99 | The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default. 100 | */ 101 | @property (nonatomic, assign) NSStringEncoding stringEncoding; 102 | 103 | /** 104 | Whether created requests can use the device’s cellular radio (if present). `YES` by default. 105 | 106 | @see NSMutableURLRequest -setAllowsCellularAccess: 107 | */ 108 | @property (nonatomic, assign) BOOL allowsCellularAccess; 109 | 110 | /** 111 | The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default. 112 | 113 | @see NSMutableURLRequest -setCachePolicy: 114 | */ 115 | @property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy; 116 | 117 | /** 118 | Whether created requests should use the default cookie handling. `YES` by default. 119 | 120 | @see NSMutableURLRequest -setHTTPShouldHandleCookies: 121 | */ 122 | @property (nonatomic, assign) BOOL HTTPShouldHandleCookies; 123 | 124 | /** 125 | Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default 126 | 127 | @see NSMutableURLRequest -setHTTPShouldUsePipelining: 128 | */ 129 | @property (nonatomic, assign) BOOL HTTPShouldUsePipelining; 130 | 131 | /** 132 | The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default. 133 | 134 | @see NSMutableURLRequest -setNetworkServiceType: 135 | */ 136 | @property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType; 137 | 138 | /** 139 | The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds. 140 | 141 | @see NSMutableURLRequest -setTimeoutInterval: 142 | */ 143 | @property (nonatomic, assign) NSTimeInterval timeoutInterval; 144 | 145 | ///--------------------------------------- 146 | /// @name Configuring HTTP Request Headers 147 | ///--------------------------------------- 148 | 149 | /** 150 | Default HTTP header field values to be applied to serialized requests. By default, these include the following: 151 | 152 | - `Accept-Language` with the contents of `NSLocale +preferredLanguages` 153 | - `User-Agent` with the contents of various bundle identifiers and OS designations 154 | 155 | @discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`. 156 | */ 157 | @property (readonly, nonatomic, strong) NSDictionary *HTTPRequestHeaders; 158 | 159 | /** 160 | Creates and returns a serializer with default configuration. 161 | */ 162 | + (instancetype)serializer; 163 | 164 | /** 165 | 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. 166 | 167 | @param field The HTTP header to set a default value for 168 | @param value The value set as default for the specified header, or `nil` 169 | */ 170 | - (void)setValue:(nullable NSString *)value 171 | forHTTPHeaderField:(NSString *)field; 172 | 173 | /** 174 | Returns the value for the HTTP headers set in the request serializer. 175 | 176 | @param field The HTTP header to retrieve the default value for 177 | 178 | @return The value set as default for the specified header, or `nil` 179 | */ 180 | - (nullable NSString *)valueForHTTPHeaderField:(NSString *)field; 181 | 182 | /** 183 | 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. 184 | 185 | @param username The HTTP basic auth username 186 | @param password The HTTP basic auth password 187 | */ 188 | - (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username 189 | password:(NSString *)password; 190 | 191 | /** 192 | Clears any existing value for the "Authorization" HTTP header. 193 | */ 194 | - (void)clearAuthorizationHeader; 195 | 196 | ///------------------------------------------------------- 197 | /// @name Configuring Query String Parameter Serialization 198 | ///------------------------------------------------------- 199 | 200 | /** 201 | HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default. 202 | */ 203 | @property (nonatomic, strong) NSSet *HTTPMethodsEncodingParametersInURI; 204 | 205 | /** 206 | Set the method of query string serialization according to one of the pre-defined styles. 207 | 208 | @param style The serialization style. 209 | 210 | @see AFHTTPRequestQueryStringSerializationStyle 211 | */ 212 | - (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style; 213 | 214 | /** 215 | Set the a custom method of query string serialization according to the specified block. 216 | 217 | @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. 218 | */ 219 | - (void)setQueryStringSerializationWithBlock:(nullable NSString * (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block; 220 | 221 | ///------------------------------- 222 | /// @name Creating Request Objects 223 | ///------------------------------- 224 | 225 | /** 226 | Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string. 227 | 228 | 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. 229 | 230 | @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`. 231 | @param URLString The URL string used to create the request URL. 232 | @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body. 233 | @param error The error that occurred while constructing the request. 234 | 235 | @return An `NSMutableURLRequest` object. 236 | */ 237 | - (NSMutableURLRequest *)requestWithMethod:(NSString *)method 238 | URLString:(NSString *)URLString 239 | parameters:(nullable id)parameters 240 | error:(NSError * _Nullable __autoreleasing *)error; 241 | 242 | /** 243 | 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 244 | 245 | 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. 246 | 247 | @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`. 248 | @param URLString The URL string used to create the request URL. 249 | @param parameters The parameters to be encoded and set in the request HTTP body. 250 | @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. 251 | @param error The error that occurred while constructing the request. 252 | 253 | @return An `NSMutableURLRequest` object 254 | */ 255 | - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method 256 | URLString:(NSString *)URLString 257 | parameters:(nullable NSDictionary *)parameters 258 | constructingBodyWithBlock:(nullable void (^)(id formData))block 259 | error:(NSError * _Nullable __autoreleasing *)error; 260 | 261 | /** 262 | 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. 263 | 264 | @param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`. 265 | @param fileURL The file URL to write multipart form contents to. 266 | @param handler A handler block to execute. 267 | 268 | @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. 269 | 270 | @see https://github.com/AFNetworking/AFNetworking/issues/1398 271 | */ 272 | - (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request 273 | writingStreamContentsToFile:(NSURL *)fileURL 274 | completionHandler:(nullable void (^)(NSError * _Nullable error))handler; 275 | 276 | @end 277 | 278 | #pragma mark - 279 | 280 | /** 281 | The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`. 282 | */ 283 | @protocol AFMultipartFormData 284 | 285 | /** 286 | 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. 287 | 288 | 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. 289 | 290 | @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. 291 | @param name The name to be associated with the specified data. This parameter must not be `nil`. 292 | @param error If an error occurs, upon return contains an `NSError` object that describes the problem. 293 | 294 | @return `YES` if the file data was successfully appended, otherwise `NO`. 295 | */ 296 | - (BOOL)appendPartWithFileURL:(NSURL *)fileURL 297 | name:(NSString *)name 298 | error:(NSError * _Nullable __autoreleasing *)error; 299 | 300 | /** 301 | 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. 302 | 303 | @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. 304 | @param name The name to be associated with the specified data. This parameter must not be `nil`. 305 | @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`. 306 | @param mimeType The declared MIME type of the file data. This parameter must not be `nil`. 307 | @param error If an error occurs, upon return contains an `NSError` object that describes the problem. 308 | 309 | @return `YES` if the file data was successfully appended otherwise `NO`. 310 | */ 311 | - (BOOL)appendPartWithFileURL:(NSURL *)fileURL 312 | name:(NSString *)name 313 | fileName:(NSString *)fileName 314 | mimeType:(NSString *)mimeType 315 | error:(NSError * _Nullable __autoreleasing *)error; 316 | 317 | /** 318 | 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. 319 | 320 | @param inputStream The input stream to be appended to the form data 321 | @param name The name to be associated with the specified input stream. This parameter must not be `nil`. 322 | @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`. 323 | @param length The length of the specified input stream in bytes. 324 | @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`. 325 | */ 326 | - (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream 327 | name:(NSString *)name 328 | fileName:(NSString *)fileName 329 | length:(int64_t)length 330 | mimeType:(NSString *)mimeType; 331 | 332 | /** 333 | 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. 334 | 335 | @param data The data to be encoded and appended to the form data. 336 | @param name The name to be associated with the specified data. This parameter must not be `nil`. 337 | @param fileName The filename to be associated with the specified data. This parameter must not be `nil`. 338 | @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`. 339 | */ 340 | - (void)appendPartWithFileData:(NSData *)data 341 | name:(NSString *)name 342 | fileName:(NSString *)fileName 343 | mimeType:(NSString *)mimeType; 344 | 345 | /** 346 | Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary. 347 | 348 | @param data The data to be encoded and appended to the form data. 349 | @param name The name to be associated with the specified data. This parameter must not be `nil`. 350 | */ 351 | 352 | - (void)appendPartWithFormData:(NSData *)data 353 | name:(NSString *)name; 354 | 355 | 356 | /** 357 | Appends HTTP headers, followed by the encoded data and the multipart form boundary. 358 | 359 | @param headers The HTTP headers to be appended to the form data. 360 | @param body The data to be encoded and appended to the form data. This parameter must not be `nil`. 361 | */ 362 | - (void)appendPartWithHeaders:(nullable NSDictionary *)headers 363 | body:(NSData *)body; 364 | 365 | /** 366 | Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream. 367 | 368 | 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. 369 | 370 | @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb. 371 | @param delay Duration of delay each time a packet is read. By default, no delay is set. 372 | */ 373 | - (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes 374 | delay:(NSTimeInterval)delay; 375 | 376 | @end 377 | 378 | #pragma mark - 379 | 380 | /** 381 | `AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`. 382 | */ 383 | @interface AFJSONRequestSerializer : AFHTTPRequestSerializer 384 | 385 | /** 386 | Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default. 387 | */ 388 | @property (nonatomic, assign) NSJSONWritingOptions writingOptions; 389 | 390 | /** 391 | Creates and returns a JSON serializer with specified reading and writing options. 392 | 393 | @param writingOptions The specified JSON writing options. 394 | */ 395 | + (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions; 396 | 397 | @end 398 | 399 | #pragma mark - 400 | 401 | /** 402 | `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`. 403 | */ 404 | @interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer 405 | 406 | /** 407 | The property list format. Possible values are described in "NSPropertyListFormat". 408 | */ 409 | @property (nonatomic, assign) NSPropertyListFormat format; 410 | 411 | /** 412 | @warning The `writeOptions` property is currently unused. 413 | */ 414 | @property (nonatomic, assign) NSPropertyListWriteOptions writeOptions; 415 | 416 | /** 417 | Creates and returns a property list serializer with a specified format, read options, and write options. 418 | 419 | @param format The property list format. 420 | @param writeOptions The property list write options. 421 | 422 | @warning The `writeOptions` property is currently unused. 423 | */ 424 | + (instancetype)serializerWithFormat:(NSPropertyListFormat)format 425 | writeOptions:(NSPropertyListWriteOptions)writeOptions; 426 | 427 | @end 428 | 429 | #pragma mark - 430 | 431 | ///---------------- 432 | /// @name Constants 433 | ///---------------- 434 | 435 | /** 436 | ## Error Domains 437 | 438 | The following error domain is predefined. 439 | 440 | - `NSString * const AFURLRequestSerializationErrorDomain` 441 | 442 | ### Constants 443 | 444 | `AFURLRequestSerializationErrorDomain` 445 | AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. 446 | */ 447 | FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain; 448 | 449 | /** 450 | ## User info dictionary keys 451 | 452 | These keys may exist in the user info dictionary, in addition to those defined for NSError. 453 | 454 | - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey` 455 | 456 | ### Constants 457 | 458 | `AFNetworkingOperationFailingURLRequestErrorKey` 459 | The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`. 460 | */ 461 | FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey; 462 | 463 | /** 464 | ## Throttling Bandwidth for HTTP Request Input Streams 465 | 466 | @see -throttleBandwidthWithPacketSize:delay: 467 | 468 | ### Constants 469 | 470 | `kAFUploadStream3GSuggestedPacketSize` 471 | Maximum packet size, in number of bytes. Equal to 16kb. 472 | 473 | `kAFUploadStream3GSuggestedDelay` 474 | Duration of delay each time a packet is read. Equal to 0.2 seconds. 475 | */ 476 | FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize; 477 | FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay; 478 | 479 | NS_ASSUME_NONNULL_END 480 | -------------------------------------------------------------------------------- /YWCLocalizeTool/AFNetworking/AFURLResponseSerialization.h: -------------------------------------------------------------------------------- 1 | // AFURLResponseSerialization.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | #import 24 | 25 | NS_ASSUME_NONNULL_BEGIN 26 | 27 | /** 28 | 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. 29 | 30 | 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. 31 | */ 32 | @protocol AFURLResponseSerialization 33 | 34 | /** 35 | The response object decoded from the data associated with a specified response. 36 | 37 | @param response The response to be processed. 38 | @param data The response data to be decoded. 39 | @param error The error that occurred while attempting to decode the response data. 40 | 41 | @return The object decoded from the specified response data. 42 | */ 43 | - (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response 44 | data:(nullable NSData *)data 45 | error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; 46 | 47 | @end 48 | 49 | #pragma mark - 50 | 51 | /** 52 | `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. 53 | 54 | Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior. 55 | */ 56 | @interface AFHTTPResponseSerializer : NSObject 57 | 58 | - (instancetype)init; 59 | 60 | /** 61 | The string encoding used to serialize data received from the server, when no string encoding is specified by the response. `NSUTF8StringEncoding` by default. 62 | */ 63 | @property (nonatomic, assign) NSStringEncoding stringEncoding; 64 | 65 | /** 66 | Creates and returns a serializer with default configuration. 67 | */ 68 | + (instancetype)serializer; 69 | 70 | ///----------------------------------------- 71 | /// @name Configuring Response Serialization 72 | ///----------------------------------------- 73 | 74 | /** 75 | 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. 76 | 77 | See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html 78 | */ 79 | @property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes; 80 | 81 | /** 82 | 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. 83 | */ 84 | @property (nonatomic, copy, nullable) NSSet *acceptableContentTypes; 85 | 86 | /** 87 | Validates the specified response and data. 88 | 89 | In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks. 90 | 91 | @param response The response to be validated. 92 | @param data The data associated with the response. 93 | @param error The error that occurred while attempting to validate the response. 94 | 95 | @return `YES` if the response is valid, otherwise `NO`. 96 | */ 97 | - (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response 98 | data:(nullable NSData *)data 99 | error:(NSError * _Nullable __autoreleasing *)error; 100 | 101 | @end 102 | 103 | #pragma mark - 104 | 105 | 106 | /** 107 | `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses. 108 | 109 | By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types: 110 | 111 | - `application/json` 112 | - `text/json` 113 | - `text/javascript` 114 | */ 115 | @interface AFJSONResponseSerializer : AFHTTPResponseSerializer 116 | 117 | - (instancetype)init; 118 | 119 | /** 120 | Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. 121 | */ 122 | @property (nonatomic, assign) NSJSONReadingOptions readingOptions; 123 | 124 | /** 125 | Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`. 126 | */ 127 | @property (nonatomic, assign) BOOL removesKeysWithNullValues; 128 | 129 | /** 130 | Creates and returns a JSON serializer with specified reading and writing options. 131 | 132 | @param readingOptions The specified JSON reading options. 133 | */ 134 | + (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions; 135 | 136 | @end 137 | 138 | #pragma mark - 139 | 140 | /** 141 | `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects. 142 | 143 | By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: 144 | 145 | - `application/xml` 146 | - `text/xml` 147 | */ 148 | @interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer 149 | 150 | @end 151 | 152 | #pragma mark - 153 | 154 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 155 | 156 | /** 157 | `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. 158 | 159 | By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: 160 | 161 | - `application/xml` 162 | - `text/xml` 163 | */ 164 | @interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer 165 | 166 | - (instancetype)init; 167 | 168 | /** 169 | Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. 170 | */ 171 | @property (nonatomic, assign) NSUInteger options; 172 | 173 | /** 174 | Creates and returns an XML document serializer with the specified options. 175 | 176 | @param mask The XML document options. 177 | */ 178 | + (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask; 179 | 180 | @end 181 | 182 | #endif 183 | 184 | #pragma mark - 185 | 186 | /** 187 | `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. 188 | 189 | By default, `AFPropertyListResponseSerializer` accepts the following MIME types: 190 | 191 | - `application/x-plist` 192 | */ 193 | @interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer 194 | 195 | - (instancetype)init; 196 | 197 | /** 198 | The property list format. Possible values are described in "NSPropertyListFormat". 199 | */ 200 | @property (nonatomic, assign) NSPropertyListFormat format; 201 | 202 | /** 203 | The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions." 204 | */ 205 | @property (nonatomic, assign) NSPropertyListReadOptions readOptions; 206 | 207 | /** 208 | Creates and returns a property list serializer with a specified format, read options, and write options. 209 | 210 | @param format The property list format. 211 | @param readOptions The property list reading options. 212 | */ 213 | + (instancetype)serializerWithFormat:(NSPropertyListFormat)format 214 | readOptions:(NSPropertyListReadOptions)readOptions; 215 | 216 | @end 217 | 218 | #pragma mark - 219 | 220 | /** 221 | `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses. 222 | 223 | By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: 224 | 225 | - `image/tiff` 226 | - `image/jpeg` 227 | - `image/gif` 228 | - `image/png` 229 | - `image/ico` 230 | - `image/x-icon` 231 | - `image/bmp` 232 | - `image/x-bmp` 233 | - `image/x-xbitmap` 234 | - `image/x-win-bitmap` 235 | */ 236 | @interface AFImageResponseSerializer : AFHTTPResponseSerializer 237 | 238 | #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH 239 | /** 240 | 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. 241 | */ 242 | @property (nonatomic, assign) CGFloat imageScale; 243 | 244 | /** 245 | 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. 246 | */ 247 | @property (nonatomic, assign) BOOL automaticallyInflatesResponseImage; 248 | #endif 249 | 250 | @end 251 | 252 | #pragma mark - 253 | 254 | /** 255 | `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. 256 | */ 257 | @interface AFCompoundResponseSerializer : AFHTTPResponseSerializer 258 | 259 | /** 260 | The component response serializers. 261 | */ 262 | @property (readonly, nonatomic, copy) NSArray > *responseSerializers; 263 | 264 | /** 265 | Creates and returns a compound serializer comprised of the specified response serializers. 266 | 267 | @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`. 268 | */ 269 | + (instancetype)compoundSerializerWithResponseSerializers:(NSArray > *)responseSerializers; 270 | 271 | @end 272 | 273 | ///---------------- 274 | /// @name Constants 275 | ///---------------- 276 | 277 | /** 278 | ## Error Domains 279 | 280 | The following error domain is predefined. 281 | 282 | - `NSString * const AFURLResponseSerializationErrorDomain` 283 | 284 | ### Constants 285 | 286 | `AFURLResponseSerializationErrorDomain` 287 | AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. 288 | */ 289 | FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain; 290 | 291 | /** 292 | ## User info dictionary keys 293 | 294 | These keys may exist in the user info dictionary, in addition to those defined for NSError. 295 | 296 | - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` 297 | - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey` 298 | 299 | ### Constants 300 | 301 | `AFNetworkingOperationFailingURLResponseErrorKey` 302 | The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. 303 | 304 | `AFNetworkingOperationFailingURLResponseDataErrorKey` 305 | 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`. 306 | */ 307 | FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey; 308 | 309 | FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; 310 | 311 | NS_ASSUME_NONNULL_END 312 | -------------------------------------------------------------------------------- /YWCLocalizeTool/AFNetworking/AFURLResponseSerialization.m: -------------------------------------------------------------------------------- 1 | // AFURLResponseSerialization.m 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import "AFURLResponseSerialization.h" 23 | 24 | #import 25 | 26 | #if TARGET_OS_IOS 27 | #import 28 | #elif TARGET_OS_WATCH 29 | #import 30 | #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) 31 | #import 32 | #endif 33 | 34 | NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response"; 35 | NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response"; 36 | NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data"; 37 | 38 | static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) { 39 | if (!error) { 40 | return underlyingError; 41 | } 42 | 43 | if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) { 44 | return error; 45 | } 46 | 47 | NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy]; 48 | mutableUserInfo[NSUnderlyingErrorKey] = underlyingError; 49 | 50 | return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo]; 51 | } 52 | 53 | static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) { 54 | if ([error.domain isEqualToString:domain] && error.code == code) { 55 | return YES; 56 | } else if (error.userInfo[NSUnderlyingErrorKey]) { 57 | return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain); 58 | } 59 | 60 | return NO; 61 | } 62 | 63 | static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) { 64 | if ([JSONObject isKindOfClass:[NSArray class]]) { 65 | NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]]; 66 | for (id value in (NSArray *)JSONObject) { 67 | [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)]; 68 | } 69 | 70 | return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray]; 71 | } else if ([JSONObject isKindOfClass:[NSDictionary class]]) { 72 | NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject]; 73 | for (id key in [(NSDictionary *)JSONObject allKeys]) { 74 | id value = (NSDictionary *)JSONObject[key]; 75 | if (!value || [value isEqual:[NSNull null]]) { 76 | [mutableDictionary removeObjectForKey:key]; 77 | } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) { 78 | mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions); 79 | } 80 | } 81 | 82 | return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary]; 83 | } 84 | 85 | return JSONObject; 86 | } 87 | 88 | @implementation AFHTTPResponseSerializer 89 | 90 | + (instancetype)serializer { 91 | return [[self alloc] init]; 92 | } 93 | 94 | - (instancetype)init { 95 | self = [super init]; 96 | if (!self) { 97 | return nil; 98 | } 99 | 100 | self.stringEncoding = NSUTF8StringEncoding; 101 | 102 | self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; 103 | self.acceptableContentTypes = nil; 104 | 105 | return self; 106 | } 107 | 108 | #pragma mark - 109 | 110 | - (BOOL)validateResponse:(NSHTTPURLResponse *)response 111 | data:(NSData *)data 112 | error:(NSError * __autoreleasing *)error 113 | { 114 | BOOL responseIsValid = YES; 115 | NSError *validationError = nil; 116 | 117 | if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) { 118 | if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]] && 119 | !([response MIMEType] == nil && [data length] == 0)) { 120 | 121 | if ([data length] > 0 && [response URL]) { 122 | NSMutableDictionary *mutableUserInfo = [@{ 123 | NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]], 124 | NSURLErrorFailingURLErrorKey:[response URL], 125 | AFNetworkingOperationFailingURLResponseErrorKey: response, 126 | } mutableCopy]; 127 | if (data) { 128 | mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; 129 | } 130 | 131 | validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError); 132 | } 133 | 134 | responseIsValid = NO; 135 | } 136 | 137 | if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) { 138 | NSMutableDictionary *mutableUserInfo = [@{ 139 | NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode], 140 | NSURLErrorFailingURLErrorKey:[response URL], 141 | AFNetworkingOperationFailingURLResponseErrorKey: response, 142 | } mutableCopy]; 143 | 144 | if (data) { 145 | mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; 146 | } 147 | 148 | validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError); 149 | 150 | responseIsValid = NO; 151 | } 152 | } 153 | 154 | if (error && !responseIsValid) { 155 | *error = validationError; 156 | } 157 | 158 | return responseIsValid; 159 | } 160 | 161 | #pragma mark - AFURLResponseSerialization 162 | 163 | - (id)responseObjectForResponse:(NSURLResponse *)response 164 | data:(NSData *)data 165 | error:(NSError *__autoreleasing *)error 166 | { 167 | [self validateResponse:(NSHTTPURLResponse *)response data:data error:error]; 168 | 169 | return data; 170 | } 171 | 172 | #pragma mark - NSSecureCoding 173 | 174 | + (BOOL)supportsSecureCoding { 175 | return YES; 176 | } 177 | 178 | - (instancetype)initWithCoder:(NSCoder *)decoder { 179 | self = [self init]; 180 | if (!self) { 181 | return nil; 182 | } 183 | 184 | self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; 185 | self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; 186 | 187 | return self; 188 | } 189 | 190 | - (void)encodeWithCoder:(NSCoder *)coder { 191 | [coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; 192 | [coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; 193 | } 194 | 195 | #pragma mark - NSCopying 196 | 197 | - (instancetype)copyWithZone:(NSZone *)zone { 198 | AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; 199 | serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone]; 200 | serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone]; 201 | 202 | return serializer; 203 | } 204 | 205 | @end 206 | 207 | #pragma mark - 208 | 209 | @implementation AFJSONResponseSerializer 210 | 211 | + (instancetype)serializer { 212 | return [self serializerWithReadingOptions:(NSJSONReadingOptions)0]; 213 | } 214 | 215 | + (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions { 216 | AFJSONResponseSerializer *serializer = [[self alloc] init]; 217 | serializer.readingOptions = readingOptions; 218 | 219 | return serializer; 220 | } 221 | 222 | - (instancetype)init { 223 | self = [super init]; 224 | if (!self) { 225 | return nil; 226 | } 227 | 228 | self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]; 229 | 230 | return self; 231 | } 232 | 233 | #pragma mark - AFURLResponseSerialization 234 | 235 | - (id)responseObjectForResponse:(NSURLResponse *)response 236 | data:(NSData *)data 237 | error:(NSError *__autoreleasing *)error 238 | { 239 | if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { 240 | if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { 241 | return nil; 242 | } 243 | } 244 | 245 | id responseObject = nil; 246 | NSError *serializationError = nil; 247 | // 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. 248 | // See https://github.com/rails/rails/issues/1742 249 | BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]]; 250 | if (data.length > 0 && !isSpace) { 251 | responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError]; 252 | } else { 253 | return nil; 254 | } 255 | 256 | if (self.removesKeysWithNullValues && responseObject) { 257 | responseObject = AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions); 258 | } 259 | 260 | if (error) { 261 | *error = AFErrorWithUnderlyingError(serializationError, *error); 262 | } 263 | 264 | return responseObject; 265 | } 266 | 267 | #pragma mark - NSSecureCoding 268 | 269 | - (instancetype)initWithCoder:(NSCoder *)decoder { 270 | self = [super initWithCoder:decoder]; 271 | if (!self) { 272 | return nil; 273 | } 274 | 275 | self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue]; 276 | self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue]; 277 | 278 | return self; 279 | } 280 | 281 | - (void)encodeWithCoder:(NSCoder *)coder { 282 | [super encodeWithCoder:coder]; 283 | 284 | [coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))]; 285 | [coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))]; 286 | } 287 | 288 | #pragma mark - NSCopying 289 | 290 | - (instancetype)copyWithZone:(NSZone *)zone { 291 | AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; 292 | serializer.readingOptions = self.readingOptions; 293 | serializer.removesKeysWithNullValues = self.removesKeysWithNullValues; 294 | 295 | return serializer; 296 | } 297 | 298 | @end 299 | 300 | #pragma mark - 301 | 302 | @implementation AFXMLParserResponseSerializer 303 | 304 | + (instancetype)serializer { 305 | AFXMLParserResponseSerializer *serializer = [[self alloc] init]; 306 | 307 | return serializer; 308 | } 309 | 310 | - (instancetype)init { 311 | self = [super init]; 312 | if (!self) { 313 | return nil; 314 | } 315 | 316 | self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; 317 | 318 | return self; 319 | } 320 | 321 | #pragma mark - AFURLResponseSerialization 322 | 323 | - (id)responseObjectForResponse:(NSHTTPURLResponse *)response 324 | data:(NSData *)data 325 | error:(NSError *__autoreleasing *)error 326 | { 327 | if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { 328 | if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { 329 | return nil; 330 | } 331 | } 332 | 333 | return [[NSXMLParser alloc] initWithData:data]; 334 | } 335 | 336 | @end 337 | 338 | #pragma mark - 339 | 340 | #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED 341 | 342 | @implementation AFXMLDocumentResponseSerializer 343 | 344 | + (instancetype)serializer { 345 | return [self serializerWithXMLDocumentOptions:0]; 346 | } 347 | 348 | + (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask { 349 | AFXMLDocumentResponseSerializer *serializer = [[self alloc] init]; 350 | serializer.options = mask; 351 | 352 | return serializer; 353 | } 354 | 355 | - (instancetype)init { 356 | self = [super init]; 357 | if (!self) { 358 | return nil; 359 | } 360 | 361 | self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; 362 | 363 | return self; 364 | } 365 | 366 | #pragma mark - AFURLResponseSerialization 367 | 368 | - (id)responseObjectForResponse:(NSURLResponse *)response 369 | data:(NSData *)data 370 | error:(NSError *__autoreleasing *)error 371 | { 372 | if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { 373 | if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { 374 | return nil; 375 | } 376 | } 377 | 378 | NSError *serializationError = nil; 379 | NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError]; 380 | 381 | if (error) { 382 | *error = AFErrorWithUnderlyingError(serializationError, *error); 383 | } 384 | 385 | return document; 386 | } 387 | 388 | #pragma mark - NSSecureCoding 389 | 390 | - (instancetype)initWithCoder:(NSCoder *)decoder { 391 | self = [super initWithCoder:decoder]; 392 | if (!self) { 393 | return nil; 394 | } 395 | 396 | self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue]; 397 | 398 | return self; 399 | } 400 | 401 | - (void)encodeWithCoder:(NSCoder *)coder { 402 | [super encodeWithCoder:coder]; 403 | 404 | [coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))]; 405 | } 406 | 407 | #pragma mark - NSCopying 408 | 409 | - (instancetype)copyWithZone:(NSZone *)zone { 410 | AFXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; 411 | serializer.options = self.options; 412 | 413 | return serializer; 414 | } 415 | 416 | @end 417 | 418 | #endif 419 | 420 | #pragma mark - 421 | 422 | @implementation AFPropertyListResponseSerializer 423 | 424 | + (instancetype)serializer { 425 | return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0]; 426 | } 427 | 428 | + (instancetype)serializerWithFormat:(NSPropertyListFormat)format 429 | readOptions:(NSPropertyListReadOptions)readOptions 430 | { 431 | AFPropertyListResponseSerializer *serializer = [[self alloc] init]; 432 | serializer.format = format; 433 | serializer.readOptions = readOptions; 434 | 435 | return serializer; 436 | } 437 | 438 | - (instancetype)init { 439 | self = [super init]; 440 | if (!self) { 441 | return nil; 442 | } 443 | 444 | self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil]; 445 | 446 | return self; 447 | } 448 | 449 | #pragma mark - AFURLResponseSerialization 450 | 451 | - (id)responseObjectForResponse:(NSURLResponse *)response 452 | data:(NSData *)data 453 | error:(NSError *__autoreleasing *)error 454 | { 455 | if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { 456 | if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { 457 | return nil; 458 | } 459 | } 460 | 461 | id responseObject; 462 | NSError *serializationError = nil; 463 | 464 | if (data) { 465 | responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError]; 466 | } 467 | 468 | if (error) { 469 | *error = AFErrorWithUnderlyingError(serializationError, *error); 470 | } 471 | 472 | return responseObject; 473 | } 474 | 475 | #pragma mark - NSSecureCoding 476 | 477 | - (instancetype)initWithCoder:(NSCoder *)decoder { 478 | self = [super initWithCoder:decoder]; 479 | if (!self) { 480 | return nil; 481 | } 482 | 483 | self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; 484 | self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue]; 485 | 486 | return self; 487 | } 488 | 489 | - (void)encodeWithCoder:(NSCoder *)coder { 490 | [super encodeWithCoder:coder]; 491 | 492 | [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))]; 493 | [coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))]; 494 | } 495 | 496 | #pragma mark - NSCopying 497 | 498 | - (instancetype)copyWithZone:(NSZone *)zone { 499 | AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; 500 | serializer.format = self.format; 501 | serializer.readOptions = self.readOptions; 502 | 503 | return serializer; 504 | } 505 | 506 | @end 507 | 508 | #pragma mark - 509 | 510 | #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH 511 | #import 512 | #import 513 | 514 | @interface UIImage (AFNetworkingSafeImageLoading) 515 | + (UIImage *)af_safeImageWithData:(NSData *)data; 516 | @end 517 | 518 | static NSLock* imageLock = nil; 519 | 520 | @implementation UIImage (AFNetworkingSafeImageLoading) 521 | 522 | + (UIImage *)af_safeImageWithData:(NSData *)data { 523 | UIImage* image = nil; 524 | static dispatch_once_t onceToken; 525 | dispatch_once(&onceToken, ^{ 526 | imageLock = [[NSLock alloc] init]; 527 | }); 528 | 529 | [imageLock lock]; 530 | image = [UIImage imageWithData:data]; 531 | [imageLock unlock]; 532 | return image; 533 | } 534 | 535 | @end 536 | 537 | static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) { 538 | UIImage *image = [UIImage af_safeImageWithData:data]; 539 | if (image.images) { 540 | return image; 541 | } 542 | 543 | return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation]; 544 | } 545 | 546 | static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) { 547 | if (!data || [data length] == 0) { 548 | return nil; 549 | } 550 | 551 | CGImageRef imageRef = NULL; 552 | CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data); 553 | 554 | if ([response.MIMEType isEqualToString:@"image/png"]) { 555 | imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); 556 | } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) { 557 | imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); 558 | 559 | if (imageRef) { 560 | CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef); 561 | CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace); 562 | 563 | // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale 564 | if (imageColorSpaceModel == kCGColorSpaceModelCMYK) { 565 | CGImageRelease(imageRef); 566 | imageRef = NULL; 567 | } 568 | } 569 | } 570 | 571 | CGDataProviderRelease(dataProvider); 572 | 573 | UIImage *image = AFImageWithDataAtScale(data, scale); 574 | if (!imageRef) { 575 | if (image.images || !image) { 576 | return image; 577 | } 578 | 579 | imageRef = CGImageCreateCopy([image CGImage]); 580 | if (!imageRef) { 581 | return nil; 582 | } 583 | } 584 | 585 | size_t width = CGImageGetWidth(imageRef); 586 | size_t height = CGImageGetHeight(imageRef); 587 | size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef); 588 | 589 | if (width * height > 1024 * 1024 || bitsPerComponent > 8) { 590 | CGImageRelease(imageRef); 591 | 592 | return image; 593 | } 594 | 595 | // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate 596 | size_t bytesPerRow = 0; 597 | CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 598 | CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace); 599 | CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); 600 | 601 | if (colorSpaceModel == kCGColorSpaceModelRGB) { 602 | uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask); 603 | #pragma clang diagnostic push 604 | #pragma clang diagnostic ignored "-Wassign-enum" 605 | if (alpha == kCGImageAlphaNone) { 606 | bitmapInfo &= ~kCGBitmapAlphaInfoMask; 607 | bitmapInfo |= kCGImageAlphaNoneSkipFirst; 608 | } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) { 609 | bitmapInfo &= ~kCGBitmapAlphaInfoMask; 610 | bitmapInfo |= kCGImageAlphaPremultipliedFirst; 611 | } 612 | #pragma clang diagnostic pop 613 | } 614 | 615 | CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo); 616 | 617 | CGColorSpaceRelease(colorSpace); 618 | 619 | if (!context) { 620 | CGImageRelease(imageRef); 621 | 622 | return image; 623 | } 624 | 625 | CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef); 626 | CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context); 627 | 628 | CGContextRelease(context); 629 | 630 | UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation]; 631 | 632 | CGImageRelease(inflatedImageRef); 633 | CGImageRelease(imageRef); 634 | 635 | return inflatedImage; 636 | } 637 | #endif 638 | 639 | 640 | @implementation AFImageResponseSerializer 641 | 642 | - (instancetype)init { 643 | self = [super init]; 644 | if (!self) { 645 | return nil; 646 | } 647 | 648 | 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]; 649 | 650 | #if TARGET_OS_IOS || TARGET_OS_TV 651 | self.imageScale = [[UIScreen mainScreen] scale]; 652 | self.automaticallyInflatesResponseImage = YES; 653 | #elif TARGET_OS_WATCH 654 | self.imageScale = [[WKInterfaceDevice currentDevice] screenScale]; 655 | self.automaticallyInflatesResponseImage = YES; 656 | #endif 657 | 658 | return self; 659 | } 660 | 661 | #pragma mark - AFURLResponseSerializer 662 | 663 | - (id)responseObjectForResponse:(NSURLResponse *)response 664 | data:(NSData *)data 665 | error:(NSError *__autoreleasing *)error 666 | { 667 | if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { 668 | if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { 669 | return nil; 670 | } 671 | } 672 | 673 | #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH 674 | if (self.automaticallyInflatesResponseImage) { 675 | return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale); 676 | } else { 677 | return AFImageWithDataAtScale(data, self.imageScale); 678 | } 679 | #else 680 | // Ensure that the image is set to it's correct pixel width and height 681 | NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data]; 682 | NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])]; 683 | [image addRepresentation:bitimage]; 684 | 685 | return image; 686 | #endif 687 | 688 | return nil; 689 | } 690 | 691 | #pragma mark - NSSecureCoding 692 | 693 | - (instancetype)initWithCoder:(NSCoder *)decoder { 694 | self = [super initWithCoder:decoder]; 695 | if (!self) { 696 | return nil; 697 | } 698 | 699 | #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH 700 | NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))]; 701 | #if CGFLOAT_IS_DOUBLE 702 | self.imageScale = [imageScale doubleValue]; 703 | #else 704 | self.imageScale = [imageScale floatValue]; 705 | #endif 706 | 707 | self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; 708 | #endif 709 | 710 | return self; 711 | } 712 | 713 | - (void)encodeWithCoder:(NSCoder *)coder { 714 | [super encodeWithCoder:coder]; 715 | 716 | #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH 717 | [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))]; 718 | [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; 719 | #endif 720 | } 721 | 722 | #pragma mark - NSCopying 723 | 724 | - (instancetype)copyWithZone:(NSZone *)zone { 725 | AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; 726 | 727 | #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH 728 | serializer.imageScale = self.imageScale; 729 | serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage; 730 | #endif 731 | 732 | return serializer; 733 | } 734 | 735 | @end 736 | 737 | #pragma mark - 738 | 739 | @interface AFCompoundResponseSerializer () 740 | @property (readwrite, nonatomic, copy) NSArray *responseSerializers; 741 | @end 742 | 743 | @implementation AFCompoundResponseSerializer 744 | 745 | + (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers { 746 | AFCompoundResponseSerializer *serializer = [[self alloc] init]; 747 | serializer.responseSerializers = responseSerializers; 748 | 749 | return serializer; 750 | } 751 | 752 | #pragma mark - AFURLResponseSerialization 753 | 754 | - (id)responseObjectForResponse:(NSURLResponse *)response 755 | data:(NSData *)data 756 | error:(NSError *__autoreleasing *)error 757 | { 758 | for (id serializer in self.responseSerializers) { 759 | if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) { 760 | continue; 761 | } 762 | 763 | NSError *serializerError = nil; 764 | id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError]; 765 | if (responseObject) { 766 | if (error) { 767 | *error = AFErrorWithUnderlyingError(serializerError, *error); 768 | } 769 | 770 | return responseObject; 771 | } 772 | } 773 | 774 | return [super responseObjectForResponse:response data:data error:error]; 775 | } 776 | 777 | #pragma mark - NSSecureCoding 778 | 779 | - (instancetype)initWithCoder:(NSCoder *)decoder { 780 | self = [super initWithCoder:decoder]; 781 | if (!self) { 782 | return nil; 783 | } 784 | 785 | self.responseSerializers = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(responseSerializers))]; 786 | 787 | return self; 788 | } 789 | 790 | - (void)encodeWithCoder:(NSCoder *)coder { 791 | [super encodeWithCoder:coder]; 792 | 793 | [coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))]; 794 | } 795 | 796 | #pragma mark - NSCopying 797 | 798 | - (instancetype)copyWithZone:(NSZone *)zone { 799 | AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; 800 | serializer.responseSerializers = self.responseSerializers; 801 | 802 | return serializer; 803 | } 804 | 805 | @end 806 | -------------------------------------------------------------------------------- /YWCLocalizeTool/AFNetworking/AFURLSessionManager.h: -------------------------------------------------------------------------------- 1 | // AFURLSessionManager.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | 23 | #import 24 | 25 | #import "AFURLResponseSerialization.h" 26 | #import "AFURLRequestSerialization.h" 27 | #import "AFSecurityPolicy.h" 28 | #if !TARGET_OS_WATCH 29 | #import "AFNetworkReachabilityManager.h" 30 | #endif 31 | 32 | /** 33 | `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. 34 | 35 | ## Subclassing Notes 36 | 37 | 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. 38 | 39 | ## NSURLSession & NSURLSessionTask Delegate Methods 40 | 41 | `AFURLSessionManager` implements the following delegate methods: 42 | 43 | ### `NSURLSessionDelegate` 44 | 45 | - `URLSession:didBecomeInvalidWithError:` 46 | - `URLSession:didReceiveChallenge:completionHandler:` 47 | - `URLSessionDidFinishEventsForBackgroundURLSession:` 48 | 49 | ### `NSURLSessionTaskDelegate` 50 | 51 | - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:` 52 | - `URLSession:task:didReceiveChallenge:completionHandler:` 53 | - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:` 54 | - `URLSession:task:needNewBodyStream:` 55 | - `URLSession:task:didCompleteWithError:` 56 | 57 | ### `NSURLSessionDataDelegate` 58 | 59 | - `URLSession:dataTask:didReceiveResponse:completionHandler:` 60 | - `URLSession:dataTask:didBecomeDownloadTask:` 61 | - `URLSession:dataTask:didReceiveData:` 62 | - `URLSession:dataTask:willCacheResponse:completionHandler:` 63 | 64 | ### `NSURLSessionDownloadDelegate` 65 | 66 | - `URLSession:downloadTask:didFinishDownloadingToURL:` 67 | - `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:` 68 | - `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:` 69 | 70 | If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. 71 | 72 | ## Network Reachability Monitoring 73 | 74 | 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. 75 | 76 | ## NSCoding Caveats 77 | 78 | - Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`. 79 | 80 | ## NSCopying Caveats 81 | 82 | - `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original. 83 | - 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. 84 | 85 | @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. 86 | */ 87 | 88 | NS_ASSUME_NONNULL_BEGIN 89 | 90 | @interface AFURLSessionManager : NSObject 91 | 92 | /** 93 | The managed session. 94 | */ 95 | @property (readonly, nonatomic, strong) NSURLSession *session; 96 | 97 | /** 98 | The operation queue on which delegate callbacks are run. 99 | */ 100 | @property (readonly, nonatomic, strong) NSOperationQueue *operationQueue; 101 | 102 | /** 103 | 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`. 104 | 105 | @warning `responseSerializer` must not be `nil`. 106 | */ 107 | @property (nonatomic, strong) id responseSerializer; 108 | 109 | ///------------------------------- 110 | /// @name Managing Security Policy 111 | ///------------------------------- 112 | 113 | /** 114 | The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. 115 | */ 116 | @property (nonatomic, strong) AFSecurityPolicy *securityPolicy; 117 | 118 | #if !TARGET_OS_WATCH 119 | ///-------------------------------------- 120 | /// @name Monitoring Network Reachability 121 | ///-------------------------------------- 122 | 123 | /** 124 | The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default. 125 | */ 126 | @property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; 127 | #endif 128 | 129 | ///---------------------------- 130 | /// @name Getting Session Tasks 131 | ///---------------------------- 132 | 133 | /** 134 | The data, upload, and download tasks currently run by the managed session. 135 | */ 136 | @property (readonly, nonatomic, strong) NSArray *tasks; 137 | 138 | /** 139 | The data tasks currently run by the managed session. 140 | */ 141 | @property (readonly, nonatomic, strong) NSArray *dataTasks; 142 | 143 | /** 144 | The upload tasks currently run by the managed session. 145 | */ 146 | @property (readonly, nonatomic, strong) NSArray *uploadTasks; 147 | 148 | /** 149 | The download tasks currently run by the managed session. 150 | */ 151 | @property (readonly, nonatomic, strong) NSArray *downloadTasks; 152 | 153 | ///------------------------------- 154 | /// @name Managing Callback Queues 155 | ///------------------------------- 156 | 157 | /** 158 | The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. 159 | */ 160 | @property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; 161 | 162 | /** 163 | The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. 164 | */ 165 | @property (nonatomic, strong, nullable) dispatch_group_t completionGroup; 166 | 167 | ///--------------------------------- 168 | /// @name Working Around System Bugs 169 | ///--------------------------------- 170 | 171 | /** 172 | Whether to attempt to retry creation of upload tasks for background sessions when initial call returns `nil`. `NO` by default. 173 | 174 | @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. 175 | 176 | @see https://github.com/AFNetworking/AFNetworking/issues/1675 177 | */ 178 | @property (nonatomic, assign) BOOL attemptsToRecreateUploadTasksForBackgroundSessions; 179 | 180 | ///--------------------- 181 | /// @name Initialization 182 | ///--------------------- 183 | 184 | /** 185 | Creates and returns a manager for a session created with the specified configuration. This is the designated initializer. 186 | 187 | @param configuration The configuration used to create the managed session. 188 | 189 | @return A manager for a newly-created session. 190 | */ 191 | - (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; 192 | 193 | /** 194 | Invalidates the managed session, optionally canceling pending tasks. 195 | 196 | @param cancelPendingTasks Whether or not to cancel pending tasks. 197 | */ 198 | - (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks; 199 | 200 | ///------------------------- 201 | /// @name Running Data Tasks 202 | ///------------------------- 203 | 204 | /** 205 | Creates an `NSURLSessionDataTask` with the specified request. 206 | 207 | @param request The HTTP request for the request. 208 | @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. 209 | */ 210 | - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request 211 | completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler DEPRECATED_ATTRIBUTE; 212 | 213 | /** 214 | Creates an `NSURLSessionDataTask` with the specified request. 215 | 216 | @param request The HTTP request for the request. 217 | @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. 218 | @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. 219 | @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. 220 | */ 221 | - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request 222 | uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock 223 | downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock 224 | completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; 225 | 226 | ///--------------------------- 227 | /// @name Running Upload Tasks 228 | ///--------------------------- 229 | 230 | /** 231 | Creates an `NSURLSessionUploadTask` with the specified request for a local file. 232 | 233 | @param request The HTTP request for the request. 234 | @param fileURL A URL to the local file to be uploaded. 235 | @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. 236 | @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. 237 | 238 | @see `attemptsToRecreateUploadTasksForBackgroundSessions` 239 | */ 240 | - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request 241 | fromFile:(NSURL *)fileURL 242 | progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock 243 | completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; 244 | 245 | /** 246 | Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body. 247 | 248 | @param request The HTTP request for the request. 249 | @param bodyData A data object containing the HTTP body to be uploaded. 250 | @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. 251 | @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. 252 | */ 253 | - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request 254 | fromData:(nullable NSData *)bodyData 255 | progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock 256 | completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; 257 | 258 | /** 259 | Creates an `NSURLSessionUploadTask` with the specified streaming request. 260 | 261 | @param request The HTTP request for the request. 262 | @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. 263 | @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. 264 | */ 265 | - (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request 266 | progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock 267 | completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; 268 | 269 | ///----------------------------- 270 | /// @name Running Download Tasks 271 | ///----------------------------- 272 | 273 | /** 274 | Creates an `NSURLSessionDownloadTask` with the specified request. 275 | 276 | @param request The HTTP request for the request. 277 | @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. 278 | @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. 279 | @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. 280 | 281 | @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. 282 | */ 283 | - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request 284 | progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock 285 | destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination 286 | completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; 287 | 288 | /** 289 | Creates an `NSURLSessionDownloadTask` with the specified resume data. 290 | 291 | @param resumeData The data used to resume downloading. 292 | @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. 293 | @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. 294 | @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. 295 | */ 296 | - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData 297 | progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock 298 | destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination 299 | completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; 300 | 301 | ///--------------------------------- 302 | /// @name Getting Progress for Tasks 303 | ///--------------------------------- 304 | 305 | /** 306 | Returns the upload progress of the specified task. 307 | 308 | @param task The session task. Must not be `nil`. 309 | 310 | @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable. 311 | */ 312 | - (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task; 313 | 314 | /** 315 | Returns the download progress of the specified task. 316 | 317 | @param task The session task. Must not be `nil`. 318 | 319 | @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable. 320 | */ 321 | - (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task; 322 | 323 | ///----------------------------------------- 324 | /// @name Setting Session Delegate Callbacks 325 | ///----------------------------------------- 326 | 327 | /** 328 | Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`. 329 | 330 | @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. 331 | */ 332 | - (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block; 333 | 334 | /** 335 | Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`. 336 | 337 | @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. 338 | */ 339 | - (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; 340 | 341 | ///-------------------------------------- 342 | /// @name Setting Task Delegate Callbacks 343 | ///-------------------------------------- 344 | 345 | /** 346 | 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:`. 347 | 348 | @param block A block object to be executed when a task requires a new request body stream. 349 | */ 350 | - (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block; 351 | 352 | /** 353 | 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:`. 354 | 355 | @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. 356 | */ 357 | - (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block; 358 | 359 | /** 360 | 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:`. 361 | 362 | @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. 363 | */ 364 | - (void)setTaskDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; 365 | 366 | /** 367 | Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. 368 | 369 | @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. 370 | */ 371 | - (void)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block; 372 | 373 | /** 374 | Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`. 375 | 376 | @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. 377 | */ 378 | - (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block; 379 | 380 | ///------------------------------------------- 381 | /// @name Setting Data Task Delegate Callbacks 382 | ///------------------------------------------- 383 | 384 | /** 385 | Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`. 386 | 387 | @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. 388 | */ 389 | - (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block; 390 | 391 | /** 392 | Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`. 393 | 394 | @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. 395 | */ 396 | - (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block; 397 | 398 | /** 399 | Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`. 400 | 401 | @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. 402 | */ 403 | - (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block; 404 | 405 | /** 406 | 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:`. 407 | 408 | @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. 409 | */ 410 | - (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block; 411 | 412 | /** 413 | Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`. 414 | 415 | @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. 416 | */ 417 | - (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block; 418 | 419 | ///----------------------------------------------- 420 | /// @name Setting Download Task Delegate Callbacks 421 | ///----------------------------------------------- 422 | 423 | /** 424 | Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`. 425 | 426 | @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. 427 | */ 428 | - (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block; 429 | 430 | /** 431 | Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`. 432 | 433 | @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. 434 | */ 435 | - (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block; 436 | 437 | /** 438 | Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. 439 | 440 | @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. 441 | */ 442 | - (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block; 443 | 444 | @end 445 | 446 | ///-------------------- 447 | /// @name Notifications 448 | ///-------------------- 449 | 450 | /** 451 | Posted when a task resumes. 452 | */ 453 | FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification; 454 | 455 | /** 456 | Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. 457 | */ 458 | FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification; 459 | 460 | /** 461 | Posted when a task suspends its execution. 462 | */ 463 | FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification; 464 | 465 | /** 466 | Posted when a session is invalidated. 467 | */ 468 | FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification; 469 | 470 | /** 471 | Posted when a session download task encountered an error when moving the temporary download file to a specified destination. 472 | */ 473 | FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification; 474 | 475 | /** 476 | The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task. 477 | */ 478 | FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey; 479 | 480 | /** 481 | The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized. 482 | */ 483 | FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey; 484 | 485 | /** 486 | The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer. 487 | */ 488 | FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey; 489 | 490 | /** 491 | 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. 492 | */ 493 | FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey; 494 | 495 | /** 496 | Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists. 497 | */ 498 | FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey; 499 | 500 | NS_ASSUME_NONNULL_END 501 | -------------------------------------------------------------------------------- /YWCLocalizeTool/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // YWCLocalizeTool 4 | // 5 | // Created by YangWeicheng on 8/29/16. 6 | // Copyright © 2016 YangWeicheng. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface AppDelegate : NSObject 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /YWCLocalizeTool/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // YWCLocalizeTool 4 | // 5 | // Created by YangWeicheng on 8/29/16. 6 | // Copyright © 2016 YangWeicheng. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | 11 | @interface AppDelegate () 12 | 13 | @end 14 | 15 | @implementation AppDelegate 16 | 17 | - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { 18 | // Insert code here to initialize your application 19 | } 20 | 21 | - (void)applicationWillTerminate:(NSNotification *)aNotification { 22 | // Insert code here to tear down your application 23 | } 24 | 25 | @end 26 | -------------------------------------------------------------------------------- /YWCLocalizeTool/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "mac", 5 | "size" : "16x16", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "mac", 10 | "size" : "16x16", 11 | "scale" : "2x" 12 | }, 13 | { 14 | "idiom" : "mac", 15 | "size" : "32x32", 16 | "scale" : "1x" 17 | }, 18 | { 19 | "idiom" : "mac", 20 | "size" : "32x32", 21 | "scale" : "2x" 22 | }, 23 | { 24 | "idiom" : "mac", 25 | "size" : "128x128", 26 | "scale" : "1x" 27 | }, 28 | { 29 | "idiom" : "mac", 30 | "size" : "128x128", 31 | "scale" : "2x" 32 | }, 33 | { 34 | "idiom" : "mac", 35 | "size" : "256x256", 36 | "scale" : "1x" 37 | }, 38 | { 39 | "idiom" : "mac", 40 | "size" : "256x256", 41 | "scale" : "2x" 42 | }, 43 | { 44 | "idiom" : "mac", 45 | "size" : "512x512", 46 | "scale" : "1x" 47 | }, 48 | { 49 | "idiom" : "mac", 50 | "size" : "512x512", 51 | "scale" : "2x" 52 | } 53 | ], 54 | "info" : { 55 | "version" : 1, 56 | "author" : "xcode" 57 | } 58 | } -------------------------------------------------------------------------------- /YWCLocalizeTool/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | NSAppTransportSecurity 6 | 7 | NSAllowsArbitraryLoads 8 | 9 | 10 | CFBundleDevelopmentRegion 11 | en 12 | CFBundleExecutable 13 | $(EXECUTABLE_NAME) 14 | CFBundleIconFile 15 | 16 | CFBundleIdentifier 17 | $(PRODUCT_BUNDLE_IDENTIFIER) 18 | CFBundleInfoDictionaryVersion 19 | 6.0 20 | CFBundleName 21 | $(PRODUCT_NAME) 22 | CFBundlePackageType 23 | APPL 24 | CFBundleShortVersionString 25 | 1.0 26 | CFBundleSignature 27 | ???? 28 | CFBundleVersion 29 | 1 30 | LSMinimumSystemVersion 31 | $(MACOSX_DEPLOYMENT_TARGET) 32 | NSHumanReadableCopyright 33 | Copyright © 2016 YangWeicheng. All rights reserved. 34 | NSMainStoryboardFile 35 | Main 36 | NSPrincipalClass 37 | NSApplication 38 | 39 | 40 | -------------------------------------------------------------------------------- /YWCLocalizeTool/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // YWCLocalizeTool 4 | // 5 | // Created by YangWeicheng on 8/29/16. 6 | // Copyright © 2016 YangWeicheng. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : NSViewController 12 | @property (unsafe_unretained) IBOutlet NSTextView *inputTextView; 13 | @property (unsafe_unretained) IBOutlet NSTextView *outputTextView; 14 | @property (weak) IBOutlet NSButton *translateButton; 15 | @property (weak) IBOutlet NSTextField *sourceLanguage; 16 | @property (weak) IBOutlet NSTextField *destinationLanguage; 17 | 18 | @end 19 | 20 | -------------------------------------------------------------------------------- /YWCLocalizeTool/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // YWCLocalizeTool 4 | // 5 | // Created by YangWeicheng on 8/29/16. 6 | // Copyright © 2016 YangWeicheng. All rights reserved. 7 | // 8 | 9 | #import "ViewController.h" 10 | #import "AFNetworking.h" 11 | #import 12 | 13 | @implementation ViewController 14 | 15 | - (IBAction)translate:(id)sender { 16 | self.outputTextView.string = @""; 17 | NSMutableString *mutableContent = [NSMutableString stringWithString:self.inputTextView.textStorage.string]; 18 | 19 | NSUInteger startLocation = 0; 20 | NSMutableArray *needTranslateStringArray = [NSMutableArray array]; 21 | while (1) { 22 | NSRange backRange = [mutableContent rangeOfString:@"\";" options:0 range:NSMakeRange(startLocation, mutableContent.length - startLocation)]; 23 | if (backRange.location == NSNotFound) { 24 | break; 25 | } 26 | startLocation += (backRange.location - startLocation); 27 | startLocation += 2; 28 | 29 | NSRange frontRange = [mutableContent rangeOfString:@"\"" options:NSBackwardsSearch range:NSMakeRange(0, backRange.location-1)]; 30 | NSRange needTranslationRange = NSMakeRange(frontRange.location+1, backRange.location - (frontRange.location + 1)); 31 | NSString *needTranlationString = [mutableContent substringWithRange:needTranslationRange]; 32 | [needTranslateStringArray addObject:needTranlationString]; 33 | } 34 | 35 | NSMutableArray *responses = [NSMutableArray array]; 36 | for (int i = 0; i < needTranslateStringArray.count; i++) { 37 | [responses addObject:@{}]; 38 | } 39 | __block int factualResponsesCount = 0; 40 | __block int tag = 0; 41 | 42 | NSString *from = self.sourceLanguage.stringValue; 43 | NSString *to = self.destinationLanguage.stringValue; 44 | 45 | dispatch_semaphore_t semaphore= dispatch_semaphore_create(0); // 创建信号量 46 | dispatch_queue_t queque = dispatch_queue_create("", DISPATCH_QUEUE_CONCURRENT); 47 | dispatch_async(queque, ^{ 48 | 49 | for (NSString *needTranslate in needTranslateStringArray) { 50 | NSNumber *appID = @20160825000027431; 51 | NSString *secret = @"Mi_MQ_2JaIDO4MpX37YU"; 52 | NSNumber *salt = [NSNumber numberWithInteger:arc4random()%10000]; 53 | NSString *q = needTranslate; 54 | NSString *signBeforeMD5 = [NSString stringWithFormat:@"%@%@%@%@",appID,q,salt,secret]; 55 | ; 56 | NSString *sign = [self getmd5WithString:signBeforeMD5]; 57 | NSDictionary *parameters = @{ 58 | @"q":q, 59 | @"from":from, 60 | @"to":to, 61 | @"appid":appID, 62 | @"salt":salt, 63 | @"sign":sign 64 | }; 65 | 66 | AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 67 | [manager GET:@"https://fanyi-api.baidu.com/api/trans/vip/translate" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * _Nullable responseObject) { 68 | dispatch_semaphore_signal(semaphore); 69 | if (responseObject[@"error_code"]) { 70 | NSLog(@"error -> %@", responseObject); 71 | return; 72 | } 73 | [responses replaceObjectAtIndex:tag withObject:responseObject]; 74 | factualResponsesCount++; 75 | NSLog(@"%@", responseObject); 76 | if (factualResponsesCount == needTranslateStringArray.count) { 77 | dispatch_async(dispatch_get_main_queue(), ^{ 78 | [self replaceOriginalString:mutableContent withResponses:responses]; 79 | }); 80 | } 81 | } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { 82 | NSLog(@"error-> %@",error); 83 | dispatch_semaphore_signal(semaphore); 84 | }]; 85 | 86 | dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);//当前信号量为0,一直等待阻塞线程 87 | [NSThread sleepForTimeInterval:1]; // 保险起见可以改为1 88 | tag++; 89 | NSLog(@"%zd", tag); 90 | } 91 | }); 92 | 93 | } 94 | 95 | - (void)replaceOriginalString:(NSMutableString *)string withResponses:(NSMutableArray *)responses 96 | { 97 | NSUInteger startLocation = 0; 98 | NSMutableString *mutableContent = string; 99 | int i = 0; 100 | while (1) { 101 | NSRange backRange = [mutableContent rangeOfString:@"\";" options:0 range:NSMakeRange(startLocation, mutableContent.length - startLocation)]; 102 | if (backRange.location == NSNotFound) { 103 | break; 104 | } 105 | startLocation += (backRange.location - startLocation); 106 | startLocation += 2; 107 | NSRange frontRange = [mutableContent rangeOfString:@"\"" options:NSBackwardsSearch range:NSMakeRange(0, backRange.location-1)]; 108 | NSRange needTranslationRange = NSMakeRange(frontRange.location+1, backRange.location - (frontRange.location + 1)); 109 | NSString *afterTranslationString = responses[i][@"trans_result"][0][@"dst"]; 110 | [mutableContent replaceCharactersInRange:needTranslationRange withString:afterTranslationString]; 111 | startLocation = (startLocation - needTranslationRange.length + afterTranslationString.length); 112 | i++; 113 | } 114 | [self.outputTextView setString:mutableContent]; 115 | } 116 | 117 | - (NSString*)getmd5WithString:(NSString *)string 118 | { 119 | const char* original_str=[string UTF8String]; 120 | unsigned char digist[CC_MD5_DIGEST_LENGTH]; //CC_MD5_DIGEST_LENGTH = 16 121 | CC_MD5(original_str, (uint)strlen(original_str), digist); 122 | NSMutableString* outPutStr = [NSMutableString stringWithCapacity:10]; 123 | for(int i =0; i 10 | 11 | int main(int argc, const char * argv[]) { 12 | return NSApplicationMain(argc, argv); 13 | } 14 | --------------------------------------------------------------------------------