├── .travis.yml ├── LICENCE.md ├── README.md ├── RequestUtils.podspec.json ├── RequestUtils ├── RequestUtils.h └── RequestUtils.m └── Tests ├── RequestUtilsTests.xcodeproj ├── project.pbxproj └── xcshareddata │ └── xcschemes │ └── RequestUtilsTests.xcscheme └── RequestUtilsTests ├── RequestTests.m ├── RequestUtilsTests-Info.plist ├── StringTests.m └── URLTests.m /.travis.yml: -------------------------------------------------------------------------------- 1 | language: objective-c 2 | before_script: 3 | - brew update 4 | - brew upgrade xctool || true 5 | osx_image: xcode7 6 | script: xctool test -project Tests/RequestUtilsTests.xcodeproj -scheme RequestUtilsTests -sdk iphonesimulator -------------------------------------------------------------------------------- /LICENCE.md: -------------------------------------------------------------------------------- 1 | RequestUtils 2 | 3 | Version 1.1.2, January 25th, 2016 4 | 5 | Copyright (C) 2012 Charcoal Design 6 | 7 | This software is provided 'as-is', without any express or implied 8 | warranty. In no event will the authors be held liable for any damages 9 | arising from the use of this software. 10 | 11 | Permission is granted to anyone to use this software for any purpose, 12 | including commercial applications, and to alter it and redistribute it 13 | freely, subject to the following restrictions: 14 | 15 | 1. The origin of this software must not be misrepresented; you must not 16 | claim that you wrote the original software. If you use this software 17 | in a product, an acknowledgment in the product documentation would be 18 | appreciated but is not required. 19 | 20 | 2. Altered source versions must be plainly marked as such, and must not be 21 | misrepresented as being the original software. 22 | 23 | 3. This notice may not be removed or altered from any source distribution. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/nicklockwood/RequestUtils.svg)](https://travis-ci.org/nicklockwood/RequestUtils) 2 | 3 | 4 | Purpose 5 | -------------- 6 | 7 | RequestUtils is a collection of category methods designed to simplify the process of HTTP request construction and manipulation in Cocoa. It extends NSString, NSURL and NSURLRequest with some additional utility methods that were left out of the standard API. 8 | 9 | 10 | Supported OS & SDK Versions 11 | ----------------------------- 12 | 13 | * Supported build target - iOS 9.2 / Mac OS 10.11 (Xcode 7.2, Apple LLVM compiler 7.1) 14 | * Earliest supported deployment target - iOS 7.1 / Mac OS 10.10 15 | * Earliest compatible deployment target - iOS 4.3 / Mac OS 10.6.8 16 | 17 | NOTE: 'Supported' means that the library has been tested with this version. 'Compatible' means that the library should work on this iOS version (i.e. it doesn't rely on any unavailable SDK features) but is no longer being tested for compatibility and may require tweaking or bug fixes to run correctly. 18 | 19 | 20 | ARC Compatibility 21 | ------------------ 22 | 23 | As of version 1.1, RequestUtils requires ARC. If you wish to use RequestUtils in a non-ARC project, just add the -fobjc-arc compiler flag to the RequestUtils.m class file. To do this, go to the Build Phases tab in your target settings, open the Compile Sources group, double-click RequestUtils.m in the list and type -fobjc-arc into the popover. 24 | 25 | If you wish to convert your whole project to ARC, comment out the #error line in RequestUtils.m, then run the Edit > Refactor > Convert to Objective-C ARC... tool in Xcode and make sure all files that you wish to use ARC for (including RequestUtils.m) are checked. 26 | 27 | 28 | Thread Safety 29 | -------------- 30 | 31 | All the RequestUtils methods should be safe to use concurrently on multiple threads. 32 | 33 | 34 | Installation 35 | -------------- 36 | 37 | To use the RequestUtils categories in an app, just drag the RequestUtils.h and .m files (demo files and assets are not needed) into your project and import the header file into any class where you wish to make use of the RequestUtils functionality, or include it in your prefix.pch file to make it available globally within your project. 38 | 39 | 40 | NSString Extensions 41 | ---------------------- 42 | 43 | RequestUtils extends NSString with the following methods: 44 | 45 | @property(nonatomic, readonly) NSString *URLEncodedString; 46 | 47 | This is a method to URL-encode a string so that it may be safely used within a URL path or query parameter. This method is different from the standard `stringByAddingPercentEscapesUsingEncoding:` method because that only ensures that the string does not contain characters that are invalid for use in a string, but it doesn't encode characters that are valid to use in a url (e.g. "?", "&") but which cannot be used inside a query string parameter or path component without affecting the URL structure. 48 | 49 | - (NSString *)URLDecodedString:(BOOL)decodePlusAsSpace; 50 | 51 | This reverses the effects of `URLEncodedString` by replacing all percent escape sequences with their original characters. Internally this method uses to `stringByReplacingPercentEscapesUsingEncoding:` with NSUTF8StringEncoding. The parameter `decodePlusAsSpace` will cause "+" characters to be converted to spaces, which is useful if the parameters were generated by a web form. 52 | 53 | - (NSString *)stringByAppendingURLPathExtension:(NSString *)extension; 54 | 55 | NSString has a useful method `stringByAppendingPathExtension:` which can be used to add a path extension to the end of the string, correctly separated by a dot. Unfortunately the `stringByAppendingPathExtension:` method is not URL-aware, and incorrectly strips the double `//` from URLs when a path is appended. `stringByAppendingURLPathExtension:` is much smarter, and not only avoids stripping the `//` from the URL schema, but will also correctly insert the path extension *before* the URL query or fragment string. 56 | 57 | @property(nonatomic, readonly) NSString *stringByDeletingURLPathExtension; 58 | 59 | This is a URL-aware version of the `stringByDeletingURLPathExtension` method. It will remove the last component of the path without disrupting the query or fragment strings, or mangling `//` (if present). 60 | 61 | @property(nonatomic, readonly) NSString *URLPathExtension; 62 | 63 | This is a URL-aware version of the `pathExtension` method. It will return the path file extension without including the query or fragment strings (if present). 64 | 65 | - (NSString *)stringByAppendingURLPathComponent:(NSString *)str; 66 | 67 | NSString has a useful method `stringByAppendingPathComponent:` which can be used to add path components to the end of the string whilst correctly adding a dividing `/` and avoiding double `/` if one or both path components already include it. Unfortunately the `stringByAppendingPathComponent:` method is not URL-aware, and incorrectly strips the double `//` from URLs when a path is appended. `stringByAppendingURLPathComponent:` is much smarter, and not only avoids stripping the `//` from the URL schema, but will also correctly insert the path component *before* the URL query or fragment string. 68 | 69 | @property(nonatomic, readonly) NSString *stringByDeletingLastURLPathComponent; 70 | 71 | This is a URL-aware version of the `stringByDeletingLastPathComponent` method. It will remove the last component of the path without disrupting the query or fragment strings, or mangling `//` (if present). 72 | 73 | @property(nonatomic, readonly) NSString *lastURLPathComponent; 74 | 75 | This is a URL-aware version of the `lastPathComponent` method. It will return the last component of the path without including the query or fragment strings (if present). 76 | 77 | + (NSString *)URLQueryWithParameters:(NSDictionary *)parameters; 78 | 79 | This method generates a URL query string from a dictionary of keys and values. The values in the dictionary can either be individual values such as strings or numbers, or arrays of values, in which case the last value in the array will be used by default. All key and values in the dictionary will be automatically URL-encoded. See below for more options around how parameter arrays are handled. 80 | 81 | + (NSString *)URLQueryWithParameters:(NSDictionary *)parameters options:(URLQueryOptions)options; 82 | 83 | This method generates a URL query string from a dictionary of keys and values, but provides an additional `options` argument to control how parameter arrays are handled. All keys and values in the dictionary will be automatically URL encoded. See `URLQueryOptions` below for discussion of the options. 84 | 85 | @property(nonatomic, readonly) NSString *URLQuery; 86 | 87 | This method attempts to find and return a URL query string within the string. It is similar to the `query` method of NSURL, but works better with partial URLs/URIs or URLs with non-standard structures, e.g. bespoke schemas. 88 | 89 | @property(nonatomic, readonly) NSString *stringByDeletingURLQuery; 90 | 91 | This method finds and removes the URL query from the string. It is URL fragment/hash aware and will leave the URL fragment untouched if present. 92 | 93 | - (NSString *)stringByReplacingURLQueryWithQuery:(NSString *)query 94 | 95 | Replaces the current query string (if present) with the specified query string. Passing nil or an empty string as the query parameter is equivalent to calling `stringByDeletingURLQuery`; 96 | 97 | - (NSString *)stringByAppendingURLQuery:(NSString *)query; 98 | 99 | This method will append a URL query to the string. It is URL fragment/hash aware and will insert the query string before the # if present. It will also correctly join the string to an existing query string if present. If there is already a query string present, the two strings will be concatenated with no regard for duplicate parameters, however a joining `&` will be inserted if needed. For more options around merging query strings, see below: 100 | 101 | - (NSString *)stringByMergingURLQuery:(NSString *)query; 102 | 103 | This method will append a URL query to the string, merging any duplicate values. Duplicate query parameter keys will be replaced by the last value encountered for that key. For more merging options, see below: 104 | 105 | - (NSString *)stringByMergingURLQuery:(NSString *)query options:(URLQueryOptions)options; 106 | 107 | This method will append a URL query to the string, merging any duplicate values. By default, duplicate query parameters will be replaced by the last value encountered for that key, but you can override that behaviour using the `options` argument. See `URLQueryOptions` below for discussion of the options. 108 | 109 | @property(nonatomic, readonly) NSDictionary *URLQueryParameters; 110 | 111 | This method attempts to locate a query string within the string and then splits it into a dictionary of key/value pairs. Each key and value will be URL decoded. If duplicate parameter keys are encountered, the last value encountered for that key is used. To override this behaviour, use `URLQueryParametersWithOptions:` instead. 112 | 113 | - (NSDictionary *)URLQueryParametersWithOptions:(URLQueryOptions)options; 114 | 115 | This method attempts to locate a query string within the string and then splits it into a dictionary of key/value pairs. Each key and value will be URL decoded. The `options` argument controls how duplicate parameters should be handled. See `URLQueryOptions` below for discussion of the options. 116 | 117 | @property(nonatomic, readonly) NSString *URLFragment; 118 | 119 | This method returns the URL fragment identifier or hash part of the string. It is similar to the `fragment` method of NSURL, but works better with partial URLs/URIs or URLs with non-standard structures, e.g. bespoke schemas. 120 | 121 | @property(nonatomic, readonly) NSString *stringByDeletingURLFragment; 122 | 123 | This method finds and removes the URL fragment identifier from the string (if present). 124 | 125 | - (NSString *)stringByAppendingURLFragment:(NSString *)fragment; 126 | 127 | This method will append a URL fragment identifier to the string. It will also correctly concatenate the string to an existing fragment identifier if present. No attempt is made to analyse the structure of the fragment, or handle path concatenation correctly within the fragment string. If you need to do that, generate the fragment separately and then set it in one go. 128 | 129 | @property(nonatomic, readonly) NSURL *URLValue; 130 | 131 | This method converts the string to a URL. It is similar to using `[NSURL URLWithString:]`, but with a couple of benefits: 1) It doesn't throw an exception if the string is nil, and 2) It automatically detects if the string is a file path and uses `[NSURL fileURLWithString:]` instead of `[NSURL URLWithString:]`, thereby eliminating a common source of bugs. 132 | 133 | - (NSURL *)URLValueRelativeToURL:(NSURL *)baseURL; 134 | 135 | This method converts the string to a URL. It is similar to using `[NSURL URLWithString:relativeToURL]`, but won't throw an exception if the string is nil. 136 | 137 | @property(nonatomic, readonly) NSString *base64EncodedString; 138 | 139 | Encodes the string as UTF8 data and then encodes that as a base-64-encoded string without any wrapping (line breaks). For more advanced base 64 encoding options, check out my Base64 library (https://github.com/nicklockwood/Base64). 140 | 141 | @property(nonatomic, readonly) NSString *base64DecodedString; 142 | 143 | Treats the string as a base-64-encoded string and returns an autoreleased NSString object containing the decoded data, interpreted using UTF8 encoding. Any non-base-64 characters in the string are ignored, so it is safe to use a string containing line breaks or other delimiters. For more advanced base 64 decoding options, check out my Base64 library (https://github.com/nicklockwood/Base64). 144 | 145 | 146 | NSURL Extensions 147 | ---------------------- 148 | 149 | RequestUtils extends NSURL with the following methods: 150 | 151 | + (NSURL *)URLWithComponents:(NSDictionary *)components; 152 | 153 | This builds a URL from the supplied dictionary of components. The dictionary may contain any or all of the following: scheme, host, port, user, password, path, parameterString, query, fragment (there are a set of constants defined for all of these values). All values are optional and the method will attempt to build as much of the URL as possible given the values supplied. All values supplied should be NSStrings, with the exception of the URLQueryComponent, which can be either an NSString or an NSDictionary of query parameters. 154 | 155 | @property(nonatomic, readonly) NSDictionary *components; 156 | 157 | Returns a dictionary of URL components containing any or all of the following: scheme, host, port, user, password, path, parameterString, query, fragment. 158 | 159 | - (NSURL *)URLWithScheme:(NSString *)scheme; 160 | 161 | Sets or replaces the current URL scheme with the supplied value. 162 | 163 | - (NSURL *)URLWithHost:(NSString *)host; 164 | 165 | Sets or replaces the current URL host with the supplied value. 166 | 167 | - (NSURL *)URLWithPort:(NSString *)port; 168 | 169 | Sets or replaces the current URL port with the supplied value. 170 | 171 | - (NSURL *)URLWithUser:(NSString *)user; 172 | 173 | Sets or replaces the current URL user with the supplied value. 174 | 175 | - (NSURL *)URLWithPassword:(NSString *)password; 176 | 177 | Sets or replaces the current URL password with the supplied value. 178 | 179 | - (NSURL *)URLWithPath:(NSString *)path; 180 | 181 | Sets or replaces the current URL path with the supplied value. 182 | 183 | - (NSURL *)URLWithParameterString:(NSString *)parameterString; 184 | 185 | Sets or replaces the current URL parameterString with the supplied value. 186 | 187 | - (NSURL *)URLWithQuery:(NSString *)query; 188 | 189 | Sets or replaces the current URL query with the supplied value. 190 | 191 | - (NSURL *)URLWithFragment:(NSString *)fragment; 192 | 193 | Sets or replaces the current URL fragment with the supplied value. 194 | 195 | 196 | NSURLRequest Extensions 197 | ---------------------- 198 | 199 | RequestUtils extends NSURLRequest with the following methods: 200 | 201 | + (id)HTTPRequestWithURL:(NSURL *)URL method:(NSString *)method parameters:(NSDictionary *)parameters; 202 | 203 | Creates a new, autoreleased NSURLRequest using the specified URL, HTTP method and parameters. For GET request, the parameters are encoded in the query string. For all other methods the parameters are encoded in the POST body. 204 | 205 | + (id)GETRequestWithURL:(NSURL *)URL parameters:(NSDictionary *)parameters; 206 | 207 | Creates a new, autoreleased NSURLRequest using the GET method and the specified URL and parameters. The Parameters are URL encoded and set as the query string of the request URL. If the URL already includes a query string, the passed parameters will be appended to the existing query according to the rules used for the NSString `stringByMergingURLQuery:` extension method. 208 | 209 | + (id)POSTRequestWithURL:(NSURL *)URL parameters:(NSDictionary *)parameters; 210 | 211 | Creates a new, autoreleased NSURLRequest using the POST method and the specified URL and parameters. The parameters are URL encoded and set as the body of the request. 212 | 213 | @property(nonatomic, readonly) NSDictionary *GETParameters; 214 | 215 | Returns the GET (query string) parameters of the request as a dictionary. 216 | 217 | @property(nonatomic, readonly) NSDictionary *POSTParameters; 218 | 219 | Returns the POST (request body) parameters of the request as a dictionary. 220 | 221 | @property(nonatomic, readonly) NSString *HTTPBasicAuthUser; 222 | 223 | Returns the HTTP basic auth user. If the request has an `Authorization` header then that will be used to get the user, otherwise if there is a user specified in the URL itself, that will be used instead. 224 | 225 | @property(nonatomic, readonly) NSString *HTTPBasicAuthPassword; 226 | 227 | Returns the HTTP basic auth password. If the request has an `Authorization` header then that will be used to get the password, otherwise if there is a password specified in the URL itself, that will be used instead. 228 | 229 | 230 | NSMutableURLRequest Extensions 231 | ---------------------- 232 | 233 | RequestUtils extends NSMutableURLRequest with the following methods: 234 | 235 | @property(nonatomic, copy) NSDictionary *GETParameters; 236 | 237 | - (void)setGETParameters:(NSDictionary *)parameters options:(URLQueryOptions)options 238 | 239 | This method sets the GET parameters of the request using a dictionary. The Parameters are URL encoded and set as the query string of the request URL. Any existing query string parameters will be replaced by the new values. The optional options argument allows you to control how the query parameters are serialised (see the URLQueryOptions section below for details). 240 | 241 | - (void)addGETParameters:(NSDictionary *)parameters options:(URLQueryOptions)options 242 | 243 | This method works like the `setGETParameters:` method except that the parameters are merged with the existing request parameters instead of replacing them. The rules by which the merging occurs are controlled by the options argument (see the URLQueryOptions section below for details). 244 | 245 | @property(nonatomic, copy) NSDictionary *POSTParameters; 246 | 247 | - (void)setPOSTParameters:(NSDictionary *)parameters options:(URLQueryOptions)options 248 | 249 | This method sets the POST parameters of the request using a dictionary. The parameters are URL encoded and set as the body of the request. Any existing request body contents will be replaced. The optional options argument allows you to control how the POST parameters are serialised (see the URLQueryOptions section below for details). 250 | 251 | - (void)addPOSTParameters:(NSDictionary *)parameters options:(URLQueryOptions)options 252 | 253 | This method works like the `setPOSTParameters:` method except that the parameters are merged with the existing POST parameters instead of replacing them. The rules by which the merging occurs are controlled by the options argument (see the URLQueryOptions section below for details). 254 | 255 | - (void)setHTTPBasicAuthUser:(NSString *)user password:(NSString *)password; 256 | 257 | This method sets the HTTP basic auth username and password for the request. The username and password are set using the `Authorization` header of the request. 258 | 259 | 260 | URLQueryOptions 261 | --------------------- 262 | 263 | The query string manipulation methods offer some options for how query strings should be generated or interpreted. The options can be combined using the | (pipe) or + (plus) operators. Some of these options are mutually exclusive however, and should not be combined. 264 | 265 | URLQueryOptionDefault 266 | 267 | The default option if no alternative is specified. When generating query strings from dictionaries using `URLQueryWithParameters:`, this maps to `URLQueryOptionUseArrays` meaning that any arrays of values will be expanded into multiple parameters. 268 | 269 | When parsing query strings into parameter dictionaries using `URLQueryParameters` this maps to `URLQueryOptionKeepLastValue` meaning that if duplicate parameter keys are encountered, the value of the last duplicate will be used. 270 | 271 | URLQueryOptionKeepLastValue 272 | 273 | This is the default option when parsing query strings into parameter dictionaries using `URLQueryParameters`. When this option is used and duplicate parameter keys are encountered, the value of the last duplicate will be used. 274 | 275 | If this option is used when generating a query string from a dictionary using `URLQueryWithParameters:options:` and an array of values is provided for a given parameter, only the last value will be used to construct the query string. 276 | 277 | URLQueryOptionKeepFirstValue 278 | 279 | If this option is used when parsing query strings into parameter dictionaries using `URLQueryParametersWithOptions:` and duplicate parameter keys are encountered, the first encountered value with a given key will be used. 280 | 281 | If this option is used when generating a query string from a dictionary using `URLQueryWithParameters:options:` and an array of values is provided for a given parameter, only the first value will be used to construct the query string. 282 | 283 | URLQueryOptionUseArrays 284 | 285 | If this option is used when parsing query strings into parameter dictionaries using `URLQueryParametersWithOptions:` and duplicate parameter keys are encountered, or the key has a "[]" array suffix, the values will be gathered into an array. The resultant parameter array will therefore contain a mix of array and string values, and you will need to add code to check the type of each dictionary entry when processing. 286 | 287 | If this option is used when generating a query string from a dictionary using `URLQueryWithParameters:options:` and an array of values is provided for a given parameter, duplicate parameters will be added to the query string with that key. 288 | 289 | URLQueryOptionAlwaysUseArrays 290 | 291 | If this option is used when parsing query strings into parameter dictionaries using `URLQueryParametersWithOptions:`, each dictionary entry will be created as an array, even if there is only one parameter with a given key (in which case the array will contain one item). The advantage of this is that you can guarantee that every dictionary entry will be an array, avoiding the need to add code to check the type of each dictionary entry when processing. 292 | 293 | When generating a query string from a dictionary using `URLQueryWithParameters:options:`, this option is equivalent to `URLQueryOptionUseArrays` unless `URLQueryOptionUseArraySyntax` is also enabled. If `URLQueryOptionUseArraySyntax` is enabled, using `URLQueryOptionUseArrays` means that every key in the resultant query string will be suffixed with "[]", even if there is only one value associated with it. This may then impact how those parameters are interpreted later (i.e. as single-item arrays rather than strings). See `URLQueryOptionUseArraySyntax` for more discussion. 294 | 295 | URLQueryOptionUseArraySyntax 296 | 297 | Unlike the previous options, which are mutually exclusive, `URLQueryOptionUseArraySyntax` can be combined with `URLQueryOptionUseArrays` or `URLQueryOptionAlwaysUseArrays` to affect output. When generating a query string from a dictionary using `URLQueryWithParameters:options:`, setting this option means that any key with multiple value (or any key *period* if `URLQueryOptionAlwaysUseArrays` is used) will be suffixed with the "[]" syntax to indicate that it is part of a parameter array. 298 | 299 | Use of the "[]" key suffix is not an official part of the RFC 1808 URL specification, but it is an ad-hoc standard used by a number of popular web server platforms including PHP, and so it can be useful to be able to interpret and/or generate query strings in this format. By default, this option is disabled. 300 | 301 | `URLQueryOptionUseArraySyntax` has no effect when parsing query strings using the `URLQueryParameters:` method. 302 | 303 | URLQueryOptionSortKeys 304 | 305 | The URLQueryOptionSortKeys option can be combined with any of the previous options. It is used when generating a query string to ensure that the keys in the resultant string will be outputted in a consistent order (alphabetical). This can be useful when performing unit tests, or cryptographic hashes on the resultant string, where you need to be able to depend on the order remaining consistent. 306 | 307 | Release Notes 308 | --------------- 309 | 310 | Version 1.1.2 311 | 312 | - Added nullability annotations 313 | - Added lightweight generics annotations 314 | - Converted getters to readonly properties 315 | - Fixed deprecation warnings in iOS9 316 | - Added watchOS and tvOS to Podspec 317 | 318 | Version 1.1.1 319 | 320 | - Fixed warnings on Xcode 6.3 and 7.0 321 | - Removed redundant `[self description]` calls 322 | 323 | Version 1.1 324 | 325 | - Added URLQueryOptionSortKeys option 326 | - Now requires ARC 327 | 328 | Version 1.0.4 329 | 330 | - Fixed bug in -[NSURL URLWithPath:] 331 | 332 | Version 1.0.3 333 | 334 | - Fixed crash when request parameter dictionary keys or values are not strings 335 | - Improved test coverage 336 | 337 | Version 1.0.2 338 | 339 | - Fixed bug in stringByAppendingURLQuery: method 340 | - Updated to use native base64 support 341 | - Now conforms to -Weverything warning level 342 | 343 | Version 1.0.1 344 | 345 | - Updated for Xcode 4.6 346 | - URLEncoding now copes gracefully with non-string values (e.g NSNumber) 347 | - Fixed bug in stringByMergingURLQuery:options: method 348 | 349 | Version 1.0 350 | 351 | - Initial release. -------------------------------------------------------------------------------- /RequestUtils.podspec.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "RequestUtils", 3 | "version": "1.1.2", 4 | "license": "zlib", 5 | "summary": "RequestUtils is a collection of category methods designed to simplify the process of HTTP request construction and manipulation in Cocoa.", 6 | "homepage": "https://github.com/nicklockwood/RequestUtils", 7 | "authors": "Nick Lockwood", 8 | "source": { 9 | "git": "https://github.com/nicklockwood/RequestUtils.git", 10 | "tag": "1.1.2" 11 | }, 12 | "source_files": "RequestUtils/RequestUtils.{h,m}", 13 | "requires_arc": true, 14 | "platforms": { 15 | "osx": "10.6", 16 | "ios": "4.3", 17 | "tvos": "9.0", 18 | "watchos": "2.0" 19 | } 20 | } -------------------------------------------------------------------------------- /RequestUtils/RequestUtils.h: -------------------------------------------------------------------------------- 1 | // 2 | // RequestUtils.h 3 | // 4 | // Version 1.1.2 5 | // 6 | // Created by Nick Lockwood on 11/01/2012. 7 | // Copyright (C) 2012 Charcoal Design 8 | // 9 | // Distributed under the permissive zlib License 10 | // Get the latest version from here: 11 | // 12 | // https://github.com/nicklockwood/RequestUtils 13 | // 14 | // This software is provided 'as-is', without any express or implied 15 | // warranty. In no event will the authors be held liable for any damages 16 | // arising from the use of this software. 17 | // 18 | // Permission is granted to anyone to use this software for any purpose, 19 | // including commercial applications, and to alter it and redistribute it 20 | // freely, subject to the following restrictions: 21 | // 22 | // 1. The origin of this software must not be misrepresented; you must not 23 | // claim that you wrote the original software. If you use this software 24 | // in a product, an acknowledgment in the product documentation would be 25 | // appreciated but is not required. 26 | // 27 | // 2. Altered source versions must be plainly marked as such, and must not be 28 | // misrepresented as being the original software. 29 | // 30 | // 3. This notice may not be removed or altered from any source distribution. 31 | // 32 | 33 | #import 34 | 35 | 36 | NS_ASSUME_NONNULL_BEGIN 37 | 38 | 39 | #ifndef REQUEST_UTILS 40 | #define REQUEST UTILS 41 | 42 | static NSString *const URLSchemeComponent = @"scheme"; 43 | static NSString *const URLHostComponent = @"host"; 44 | static NSString *const URLPortComponent = @"port"; 45 | static NSString *const URLUserComponent = @"user"; 46 | static NSString *const URLPasswordComponent = @"password"; 47 | static NSString *const URLPathComponent = @"path"; 48 | static NSString *const URLParameterStringComponent = @"parameterString"; 49 | static NSString *const URLQueryComponent = @"query"; 50 | static NSString *const URLFragmentComponent = @"fragment"; 51 | 52 | #endif 53 | 54 | 55 | typedef NS_ENUM(NSUInteger, URLQueryOptions) 56 | { 57 | //mutually exclusive 58 | URLQueryOptionDefault = 0, 59 | URLQueryOptionKeepLastValue, 60 | URLQueryOptionKeepFirstValue, 61 | URLQueryOptionUseArrays, 62 | URLQueryOptionAlwaysUseArrays, 63 | 64 | //can be |ed with other values 65 | URLQueryOptionUseArraySyntax = 8, 66 | URLQueryOptionSortKeys = 16 67 | }; 68 | 69 | 70 | @interface NSString (RequestUtils) 71 | 72 | #pragma mark URLEncoding 73 | 74 | @property (nonatomic, readonly) NSString *URLEncodedString; 75 | @property (nonatomic, readonly) NSString *URLDecodedString; 76 | 77 | - (NSString *)URLDecodedString:(BOOL)decodePlusAsSpace; 78 | 79 | #pragma mark URL path extension 80 | 81 | @property (nonatomic, readonly) NSString *stringByDeletingURLPathExtension; 82 | @property (nonatomic, readonly) NSString *URLPathExtension; 83 | 84 | - (NSString *)stringByAppendingURLPathExtension:(NSString *)extension; 85 | 86 | #pragma mark URL paths 87 | 88 | @property (nonatomic, readonly) NSString *stringByDeletingLastURLPathComponent; 89 | @property (nonatomic, readonly) NSString *lastURLPathComponent; 90 | 91 | - (NSString *)stringByAppendingURLPathComponent:(NSString *)str; 92 | 93 | #pragma mark URL query 94 | 95 | + (NSString *)URLQueryWithParameters:(NSDictionary *)parameters; 96 | + (NSString *)URLQueryWithParameters:(NSDictionary *)parameters options:(URLQueryOptions)options; 97 | 98 | @property (nonatomic, readonly) NSString *URLQuery; 99 | @property (nonatomic, readonly) NSString *stringByDeletingURLQuery; 100 | 101 | - (NSString *)stringByReplacingURLQueryWithQuery:(NSString *)query; 102 | - (NSString *)stringByAppendingURLQuery:(NSString *)query; 103 | - (NSString *)stringByMergingURLQuery:(NSString *)query; 104 | - (NSString *)stringByMergingURLQuery:(NSString *)query options:(URLQueryOptions)options; 105 | - (NSDictionary *)URLQueryParameters; 106 | - (NSDictionary *)URLQueryParametersWithOptions:(URLQueryOptions)options; 107 | 108 | #pragma mark URL fragment ID 109 | 110 | @property (nonatomic, readonly) NSString *URLFragment; 111 | @property (nonatomic, readonly) NSString *stringByDeletingURLFragment; 112 | 113 | - (NSString *)stringByAppendingURLFragment:(NSString *)fragment; 114 | 115 | #pragma mark URL conversion 116 | 117 | @property (nonatomic, readonly, nullable) NSURL *URLValue; 118 | 119 | - (nullable NSURL *)URLValueRelativeToURL:(nullable NSURL *)baseURL; 120 | 121 | #pragma mark base 64 122 | 123 | @property (nonatomic, readonly) NSString *base64EncodedString; 124 | @property (nonatomic, readonly) NSString *base64DecodedString; 125 | 126 | @end 127 | 128 | 129 | @interface NSURL (RequestUtils) 130 | 131 | + (instancetype)URLWithComponents:(NSDictionary *)components; 132 | 133 | @property (nonatomic, readonly) NSDictionary *components; 134 | 135 | - (NSURL *)URLWithScheme:(NSString *)scheme; 136 | - (NSURL *)URLWithHost:(NSString *)host; 137 | - (NSURL *)URLWithPort:(NSString *)port; 138 | - (NSURL *)URLWithUser:(NSString *)user; 139 | - (NSURL *)URLWithPassword:(NSString *)password; 140 | - (NSURL *)URLWithPath:(NSString *)path; 141 | - (NSURL *)URLWithParameterString:(NSString *)parameterString; 142 | - (NSURL *)URLWithQuery:(NSString *)query; 143 | - (NSURL *)URLWithFragment:(NSString *)fragment; 144 | 145 | @end 146 | 147 | 148 | @interface NSURLRequest (RequestUtils) 149 | 150 | + (instancetype)HTTPRequestWithURL:(NSURL *)URL method:(NSString *)method parameters:(NSDictionary *)parameters; 151 | + (instancetype)GETRequestWithURL:(NSURL *)URL parameters:(NSDictionary *)parameters; 152 | + (instancetype)POSTRequestWithURL:(NSURL *)URL parameters:(NSDictionary *)parameters; 153 | 154 | @property (nonatomic, readonly, nullable) NSDictionary *GETParameters; 155 | @property (nonatomic, readonly, nullable) NSDictionary *POSTParameters; 156 | @property (nonatomic, readonly, nullable) NSString *HTTPBasicAuthUser; 157 | @property (nonatomic, readonly, nullable) NSString *HTTPBasicAuthPassword; 158 | 159 | @end 160 | 161 | 162 | @interface NSMutableURLRequest (RequestUtils) 163 | 164 | @property (nonatomic, copy, nullable) NSDictionary *GETParameters; 165 | @property (nonatomic, copy, nullable) NSDictionary *POSTParameters; 166 | 167 | - (void)setGETParameters:(NSDictionary *)parameters options:(URLQueryOptions)options; 168 | - (void)addGETParameters:(NSDictionary *)parameters options:(URLQueryOptions)options; 169 | - (void)setPOSTParameters:(NSDictionary *)parameters options:(URLQueryOptions)options; 170 | - (void)addPOSTParameters:(NSDictionary *)parameters options:(URLQueryOptions)options; 171 | - (void)setHTTPBasicAuthUser:(NSString *)user password:(nullable NSString *)password; 172 | 173 | @end 174 | 175 | 176 | NS_ASSUME_NONNULL_END 177 | -------------------------------------------------------------------------------- /RequestUtils/RequestUtils.m: -------------------------------------------------------------------------------- 1 | // 2 | // RequestUtils.m 3 | // 4 | // Version 1.1.2 5 | // 6 | // Created by Nick Lockwood on 11/01/2012. 7 | // Copyright (C) 2012 Charcoal Design 8 | // 9 | // Distributed under the permissive zlib License 10 | // Get the latest version from here: 11 | // 12 | // https://github.com/nicklockwood/RequestUtils 13 | // 14 | // This software is provided 'as-is', without any express or implied 15 | // warranty. In no event will the authors be held liable for any damages 16 | // arising from the use of this software. 17 | // 18 | // Permission is granted to anyone to use this software for any purpose, 19 | // including commercial applications, and to alter it and redistribute it 20 | // freely, subject to the following restrictions: 21 | // 22 | // 1. The origin of this software must not be misrepresented; you must not 23 | // claim that you wrote the original software. If you use this software 24 | // in a product, an acknowledgment in the product documentation would be 25 | // appreciated but is not required. 26 | // 27 | // 2. Altered source versions must be plainly marked as such, and must not be 28 | // misrepresented as being the original software. 29 | // 30 | // 3. This notice may not be removed or altered from any source distribution. 31 | // 32 | 33 | #import "RequestUtils.h" 34 | 35 | 36 | #import 37 | #if !__has_feature(objc_arc) 38 | #error This class requires automatic reference counting 39 | #endif 40 | 41 | 42 | #pragma GCC diagnostic ignored "-Wgnu" 43 | #pragma GCC diagnostic ignored "-Wundef" 44 | #pragma GCC diagnostic ignored "-Wselector" 45 | 46 | 47 | @implementation NSData (RequestUtils) 48 | 49 | - (NSString *)RequestUtils_UTF8String 50 | { 51 | return [[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding]; 52 | } 53 | 54 | @end 55 | 56 | 57 | @implementation NSString (RequestUtils) 58 | 59 | #pragma mark URLEncoding 60 | 61 | - (NSString *)URLEncodedString 62 | { 63 | static NSString *const unsafeChars = @"!*'\"();:@&=+$,/?%#[]% "; 64 | 65 | #if !(__MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_9) && !(__IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0) 66 | 67 | if (![self respondsToSelector:@selector(stringByAddingPercentEncodingWithAllowedCharacters:)]) 68 | { 69 | CFStringRef encoded = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, 70 | (__bridge CFStringRef)self, 71 | NULL, 72 | (__bridge CFStringRef)unsafeChars, 73 | kCFStringEncodingUTF8); 74 | return (__bridge_transfer NSString *)encoded; 75 | } 76 | 77 | #endif 78 | 79 | static NSCharacterSet *allowedChars; 80 | static dispatch_once_t onceToken; 81 | dispatch_once(&onceToken, ^{ 82 | NSCharacterSet *disallowedChars = [NSCharacterSet characterSetWithCharactersInString:unsafeChars]; 83 | allowedChars = [disallowedChars invertedSet]; 84 | }); 85 | 86 | return (NSString *)[self stringByAddingPercentEncodingWithAllowedCharacters:allowedChars]; 87 | } 88 | 89 | - (NSString *)URLDecodedString 90 | { 91 | return [self URLDecodedString:NO]; 92 | } 93 | 94 | - (NSString *)URLDecodedString:(BOOL)decodePlusAsSpace 95 | { 96 | NSString *string = self; 97 | if (decodePlusAsSpace) 98 | { 99 | string = [string stringByReplacingOccurrencesOfString:@"+" withString:@" "]; 100 | } 101 | 102 | #if !(__MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_9) && !(__IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0) 103 | 104 | if (![self respondsToSelector:@selector(stringByRemovingPercentEncoding)]) 105 | { 106 | return (NSString *)[string stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 107 | } 108 | 109 | #endif 110 | 111 | return (NSString *)[string stringByRemovingPercentEncoding]; 112 | } 113 | 114 | #pragma mark URL path extension 115 | 116 | - (NSString *)stringByAppendingURLPathExtension:(NSString *)extension 117 | { 118 | NSString *lastPathComponent = [self.lastURLPathComponent stringByAppendingPathExtension:extension]; 119 | return [self.stringByDeletingLastURLPathComponent stringByAppendingURLPathComponent:lastPathComponent]; 120 | } 121 | 122 | - (NSString *)stringByDeletingURLPathExtension 123 | { 124 | NSString *lastPathComponent = [self.lastURLPathComponent stringByDeletingPathExtension]; 125 | return [self.stringByDeletingLastURLPathComponent stringByAppendingURLPathComponent:lastPathComponent]; 126 | } 127 | 128 | - (NSString *)URLPathExtension 129 | { 130 | return self.lastURLPathComponent.pathExtension; 131 | } 132 | 133 | #pragma mark URL paths 134 | 135 | - (NSString *)stringByAppendingURLPathComponent:(NSString *)str 136 | { 137 | NSString *url = self; 138 | 139 | //remove fragment 140 | NSString *fragment = url.URLFragment; 141 | url = url.stringByDeletingURLFragment; 142 | 143 | //remove query 144 | NSString *query = url.URLQuery; 145 | url = url.stringByDeletingURLQuery; 146 | 147 | //strip leading slash on path 148 | if ([str hasPrefix:@"/"]) 149 | { 150 | str = [str substringFromIndex:1]; 151 | } 152 | 153 | //add trailing slash 154 | if (url.length && ![url hasSuffix:@"/"]) 155 | { 156 | url = [url stringByAppendingString:@"/"]; 157 | } 158 | 159 | //reassemble url 160 | url = [url stringByAppendingString:str]; 161 | url = [url stringByAppendingURLQuery:query]; 162 | url = [url stringByAppendingURLFragment:fragment]; 163 | 164 | return url; 165 | } 166 | 167 | - (NSString *)stringByDeletingLastURLPathComponent 168 | { 169 | NSString *url = self; 170 | 171 | //remove fragment 172 | NSString *fragment = url.URLFragment; 173 | url = url.stringByDeletingURLFragment; 174 | 175 | //remove query 176 | NSString *query = url.URLQuery; 177 | url = url.stringByDeletingURLQuery; 178 | 179 | //trim path 180 | NSRange range = [url rangeOfString:@"/" options:NSBackwardsSearch]; 181 | if (range.location != NSNotFound) url = [url substringToIndex:range.location + 1]; 182 | 183 | //reassemble url 184 | url = [url stringByAppendingURLQuery:query]; 185 | url = [url stringByAppendingURLFragment:fragment]; 186 | 187 | return url; 188 | } 189 | 190 | - (NSString *)lastURLPathComponent 191 | { 192 | NSString *url = self; 193 | 194 | //remove fragment 195 | url = url.stringByDeletingURLFragment; 196 | 197 | //remove query 198 | url = url.stringByDeletingURLQuery; 199 | 200 | //get last path component 201 | NSRange range = [url rangeOfString:@"/" options:NSBackwardsSearch]; 202 | if (range.location != NSNotFound) url = [url substringFromIndex:range.location + 1]; 203 | 204 | return url; 205 | } 206 | 207 | #pragma mark Query strings 208 | 209 | + (NSString *)URLQueryWithParameters:(NSDictionary *)parameters 210 | { 211 | return [self URLQueryWithParameters:parameters options:URLQueryOptionDefault]; 212 | } 213 | 214 | + (NSString *)URLQueryWithParameters:(NSDictionary *)parameters options:(URLQueryOptions)options 215 | { 216 | options = options ?: URLQueryOptionUseArrays; 217 | 218 | BOOL sortKeys = !!(options & URLQueryOptionSortKeys); 219 | if (sortKeys) 220 | { 221 | options -= URLQueryOptionSortKeys; 222 | } 223 | 224 | BOOL useArraySyntax = !!(options & URLQueryOptionUseArraySyntax); 225 | if (useArraySyntax) 226 | { 227 | options -= URLQueryOptionUseArraySyntax; 228 | NSAssert(options == URLQueryOptionUseArrays || options == URLQueryOptionAlwaysUseArrays, 229 | @"URLQueryOptionUseArraySyntax has no effect unless combined with URLQueryOptionUseArrays or URLQueryOptionAlwaysUseArrays option"); 230 | } 231 | 232 | NSMutableString *result = [NSMutableString string]; 233 | NSArray *keys = parameters.allKeys; 234 | if (sortKeys) keys = [keys sortedArrayUsingSelector:@selector(compare:)]; 235 | for (NSString *key in keys) 236 | { 237 | id value = parameters[key]; 238 | NSString *encodedKey = key.description.URLEncodedString; 239 | if ([value isKindOfClass:[NSArray class]]) 240 | { 241 | if (options == URLQueryOptionKeepFirstValue && [value count]) 242 | { 243 | if (result.length) 244 | { 245 | [result appendString:@"&"]; 246 | } 247 | [result appendFormat:@"%@=%@", encodedKey, [[value firstObject] description].URLEncodedString]; 248 | } 249 | else if (options == URLQueryOptionKeepLastValue && [value count]) 250 | { 251 | if (result.length) 252 | { 253 | [result appendString:@"&"]; 254 | } 255 | [result appendFormat:@"%@=%@", encodedKey, [[value lastObject] description].URLEncodedString]; 256 | } 257 | else 258 | { 259 | for (NSString *element in value) 260 | { 261 | if (result.length) 262 | { 263 | [result appendString:@"&"]; 264 | } 265 | if (useArraySyntax) 266 | { 267 | [result appendFormat:@"%@[]=%@", encodedKey, element.description.URLEncodedString]; 268 | } 269 | else 270 | { 271 | [result appendFormat:@"%@=%@", encodedKey, element.description.URLEncodedString]; 272 | } 273 | } 274 | } 275 | } 276 | else 277 | { 278 | if (result.length) 279 | { 280 | [result appendString:@"&"]; 281 | } 282 | if (useArraySyntax && options == URLQueryOptionAlwaysUseArrays) 283 | { 284 | [result appendFormat:@"%@[]=%@", encodedKey, [value description].URLEncodedString]; 285 | } 286 | else 287 | { 288 | [result appendFormat:@"%@=%@", encodedKey, [value description].URLEncodedString]; 289 | } 290 | } 291 | } 292 | 293 | return result; 294 | } 295 | 296 | - (NSRange)rangeOfURLQuery 297 | { 298 | NSRange queryRange = NSMakeRange(0, self.length); 299 | NSRange fragmentStart = [self rangeOfString:@"#"]; 300 | if (fragmentStart.length) 301 | { 302 | queryRange.length -= (queryRange.length - fragmentStart.location); 303 | } 304 | NSRange queryStart = [self rangeOfString:@"?"]; 305 | if (queryStart.length) 306 | { 307 | queryRange.location = queryStart.location; 308 | queryRange.length -= queryRange.location; 309 | } 310 | NSString *queryString = [self substringWithRange:queryRange]; 311 | if (queryStart.length || [queryString rangeOfString:@"="].length) 312 | { 313 | return queryRange; 314 | } 315 | return NSMakeRange(NSNotFound, 0); 316 | } 317 | 318 | - (NSString *)URLQuery 319 | { 320 | NSRange queryRange = [self rangeOfURLQuery]; 321 | if (queryRange.location == NSNotFound) 322 | { 323 | return nil; 324 | } 325 | NSString *queryString = [self substringWithRange:queryRange]; 326 | if ([queryString hasPrefix:@"?"]) 327 | { 328 | queryString = [queryString substringFromIndex:1]; 329 | } 330 | return queryString; 331 | } 332 | 333 | - (NSString *)stringByDeletingURLQuery 334 | { 335 | NSRange queryRange = [self rangeOfURLQuery]; 336 | if (queryRange.location != NSNotFound) 337 | { 338 | NSString *prefix = [self substringToIndex:queryRange.location]; 339 | NSString *suffix = [self substringFromIndex:queryRange.location + queryRange.length]; 340 | return [prefix stringByAppendingString:suffix]; 341 | } 342 | return self; 343 | } 344 | 345 | - (NSString *)stringByReplacingURLQueryWithQuery:(NSString *)query 346 | { 347 | return [self.stringByDeletingURLQuery stringByAppendingURLQuery:query]; 348 | } 349 | 350 | - (NSString *)stringByAppendingURLQuery:(NSString *)query 351 | { 352 | //check for empty input 353 | query = query.URLQuery; 354 | if ([query length] == 0) 355 | { 356 | return self; 357 | } 358 | 359 | NSString *result = self; 360 | NSString *fragment = result.URLFragment; 361 | result = self.stringByDeletingURLFragment; 362 | NSString *existingQuery = result.URLQuery; 363 | if (existingQuery.length) 364 | { 365 | result = [result stringByAppendingFormat:@"&%@", query]; 366 | } 367 | else 368 | { 369 | result = [result.stringByDeletingURLQuery stringByAppendingFormat:@"?%@", query]; 370 | } 371 | if (fragment.length) 372 | { 373 | result = [result stringByAppendingFormat:@"#%@", fragment]; 374 | } 375 | return result; 376 | } 377 | 378 | - (NSString *)stringByMergingURLQuery:(NSString *)query 379 | { 380 | return [self stringByMergingURLQuery:query options:URLQueryOptionDefault]; 381 | } 382 | 383 | - (NSString *)stringByMergingURLQuery:(NSString *)query options:(URLQueryOptions)options 384 | { 385 | NSParameterAssert(options <= URLQueryOptionAlwaysUseArrays); 386 | options = options ?: URLQueryOptionKeepLastValue; 387 | 388 | //check for empty input 389 | query = query.URLQuery; 390 | if (query.length == 0) 391 | { 392 | return self; 393 | } 394 | 395 | //check for nil query string 396 | NSString *queryString = self.URLQuery; 397 | if (queryString.length == 0) 398 | { 399 | return [self stringByAppendingURLQuery:query]; 400 | } 401 | 402 | NSMutableDictionary *parameters = (NSMutableDictionary *)[queryString URLQueryParametersWithOptions:options]; 403 | NSDictionary *newParameters = [query URLQueryParametersWithOptions:options]; 404 | for (NSString *key in newParameters) 405 | { 406 | id value = newParameters[key]; 407 | id oldValue = parameters[key]; 408 | if ([oldValue isKindOfClass:[NSArray class]]) 409 | { 410 | if ([value isKindOfClass:[NSArray class]]) 411 | { 412 | value = [oldValue arrayByAddingObjectsFromArray:value]; 413 | } 414 | else 415 | { 416 | value = [oldValue arrayByAddingObject:value]; 417 | } 418 | } 419 | else if (oldValue) 420 | { 421 | if ([value isKindOfClass:[NSArray class]]) 422 | { 423 | value = [@[oldValue] arrayByAddingObjectsFromArray:value]; 424 | } 425 | else if (options == URLQueryOptionKeepFirstValue) 426 | { 427 | value = oldValue; 428 | } 429 | else if (options == URLQueryOptionUseArrays || 430 | options == URLQueryOptionAlwaysUseArrays) 431 | { 432 | value = @[oldValue, value]; 433 | } 434 | } 435 | else if (options == URLQueryOptionAlwaysUseArrays) 436 | { 437 | value = @[value]; 438 | } 439 | parameters[key] = value; 440 | } 441 | 442 | return [self stringByReplacingURLQueryWithQuery:[NSString URLQueryWithParameters:parameters options:options]]; 443 | } 444 | 445 | - (NSDictionary *)URLQueryParameters 446 | { 447 | return [self URLQueryParametersWithOptions:URLQueryOptionDefault]; 448 | } 449 | 450 | - (NSDictionary *)URLQueryParametersWithOptions:(URLQueryOptions)options 451 | { 452 | NSParameterAssert(options <= URLQueryOptionAlwaysUseArrays); 453 | options = options ?: URLQueryOptionKeepLastValue; 454 | 455 | NSString *queryString = self.URLQuery; 456 | 457 | NSMutableDictionary *result = [NSMutableDictionary dictionary]; 458 | NSArray *parameters = [queryString componentsSeparatedByString:@"&"]; 459 | for (NSString *parameter in parameters) 460 | { 461 | NSArray *parts = [parameter componentsSeparatedByString:@"="]; 462 | NSString *key = [parts[0] URLDecodedString:YES]; 463 | if (parts.count > 1) 464 | { 465 | id value = [parts[1] URLDecodedString:YES]; 466 | BOOL arrayValue = [key hasSuffix:@"[]"]; 467 | if (arrayValue) 468 | { 469 | key = [key substringToIndex:[key length] - 2]; 470 | } 471 | id existingValue = result[key]; 472 | if ([existingValue isKindOfClass:[NSArray class]]) 473 | { 474 | value = [existingValue arrayByAddingObject:value]; 475 | } 476 | else if (existingValue) 477 | { 478 | if (options == URLQueryOptionKeepFirstValue) 479 | { 480 | value = existingValue; 481 | } 482 | else if (options != URLQueryOptionKeepLastValue) 483 | { 484 | value = @[existingValue, value]; 485 | } 486 | } 487 | else if ((arrayValue && options == URLQueryOptionUseArrays) || options == URLQueryOptionAlwaysUseArrays) 488 | { 489 | value = @[value]; 490 | } 491 | result[key] = value; 492 | } 493 | } 494 | return result; 495 | } 496 | 497 | #pragma mark URL fragment ID 498 | 499 | - (NSString *)URLFragment 500 | { 501 | NSRange fragmentStart = [self rangeOfString:@"#"]; 502 | if (fragmentStart.location != NSNotFound) 503 | { 504 | return [self substringFromIndex:fragmentStart.location + 1]; 505 | } 506 | return nil; 507 | } 508 | 509 | - (NSString *)stringByDeletingURLFragment 510 | { 511 | NSRange fragmentStart = [self rangeOfString:@"#"]; 512 | if (fragmentStart.location != NSNotFound) 513 | { 514 | return [self substringToIndex:fragmentStart.location]; 515 | } 516 | return self; 517 | } 518 | 519 | - (NSString *)stringByAppendingURLFragment:(NSString *)fragment 520 | { 521 | if (fragment) 522 | { 523 | NSRange fragmentStart = [self rangeOfString:@"#"]; 524 | if (fragmentStart.location != NSNotFound) 525 | { 526 | return [self stringByAppendingString:fragment]; 527 | } 528 | return [self stringByAppendingFormat:@"#%@", fragment]; 529 | } 530 | return self; 531 | } 532 | 533 | #pragma mark URL conversion 534 | 535 | - (nullable NSURL *)URLValue 536 | { 537 | if (self.absolutePath) 538 | { 539 | return [NSURL fileURLWithPath:self]; 540 | } 541 | return [NSURL URLWithString:self]; 542 | } 543 | 544 | - (nullable NSURL *)URLValueRelativeToURL:(nullable NSURL *)baseURL 545 | { 546 | return [NSURL URLWithString:self relativeToURL:baseURL]; 547 | } 548 | 549 | #pragma mark base 64 550 | 551 | - (NSString *)base64EncodedString 552 | { 553 | NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding]; 554 | 555 | #if !(__MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_9) && !(__IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0) 556 | 557 | if (![self respondsToSelector:@selector(base64EncodedStringWithOptions:)]) 558 | { 559 | return data.base64Encoding; 560 | } 561 | 562 | #endif 563 | 564 | return [data base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0]; 565 | } 566 | 567 | - (NSString *)base64DecodedString 568 | { 569 | NSData *data; 570 | 571 | #if !(__MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_9) && !(__IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0) 572 | 573 | if (![NSData instancesRespondToSelector:@selector(initWithBase64EncodedString:options:)]) 574 | { 575 | data = [[NSData alloc] initWithBase64Encoding:self]; 576 | } 577 | else 578 | 579 | #endif 580 | 581 | { 582 | data = [[NSData alloc] initWithBase64EncodedString:self options:(NSDataBase64DecodingOptions)0]; 583 | } 584 | 585 | return [data RequestUtils_UTF8String]; 586 | } 587 | 588 | @end 589 | 590 | 591 | @implementation NSURL (RequestUtils) 592 | 593 | + (NSURL *)URLWithComponents:(NSDictionary *)components 594 | { 595 | NSString *URL = @""; 596 | NSString *fragment = components[URLFragmentComponent]; 597 | if ([fragment hasPrefix:@"#"]) 598 | { 599 | fragment = [fragment substringFromIndex:1]; 600 | } 601 | if (fragment) 602 | { 603 | URL = [NSString stringWithFormat:@"#%@", fragment]; 604 | } 605 | NSString *query = components[URLQueryComponent]; 606 | if (query) 607 | { 608 | if ([query isKindOfClass:[NSDictionary class]]) 609 | { 610 | query = [NSString URLQueryWithParameters:(NSDictionary *)query]; 611 | } 612 | if ([query hasPrefix:@"?"] || [query hasPrefix:@"&"]) 613 | { 614 | query = [query substringFromIndex:1]; 615 | } 616 | URL = [NSString stringWithFormat:@"?%@%@", query, URL]; 617 | } 618 | NSString *parameterString = components[URLParameterStringComponent]; 619 | if (parameterString) 620 | { 621 | URL = [NSString stringWithFormat:@";%@%@", parameterString, URL]; 622 | } 623 | NSString *path = components[URLPathComponent]; 624 | if (path) 625 | { 626 | URL = [path stringByAppendingString:URL]; 627 | } 628 | NSString *port = components[URLPortComponent]; 629 | if (port) 630 | { 631 | URL = [NSString stringWithFormat:@":%@%@", port, URL]; 632 | } 633 | NSString *host = components[URLHostComponent]; 634 | if (host) 635 | { 636 | URL = [host stringByAppendingString:URL]; 637 | } 638 | NSString *user = components[URLUserComponent]; 639 | if (user) 640 | { 641 | NSString *password = components[URLPasswordComponent]; 642 | if (password) 643 | { 644 | user = [user stringByAppendingFormat:@":%@", password]; 645 | } 646 | URL = [user stringByAppendingFormat:@"@%@", URL]; 647 | } 648 | NSString *scheme = components[URLSchemeComponent]; 649 | if (scheme) 650 | { 651 | URL = [scheme stringByAppendingFormat:@"://%@", URL]; 652 | } 653 | return [NSURL URLWithString:URL]; 654 | } 655 | 656 | - (NSDictionary *)components 657 | { 658 | NSMutableDictionary *result = [NSMutableDictionary dictionary]; 659 | for (NSString *key in @[URLSchemeComponent, URLHostComponent, 660 | URLPortComponent, URLUserComponent, 661 | URLPasswordComponent, URLPortComponent, 662 | URLPathComponent, URLParameterStringComponent, 663 | URLQueryComponent, URLFragmentComponent]) 664 | { 665 | id value = [self valueForKey:key]; 666 | if (value) 667 | { 668 | result[key] = value; 669 | } 670 | } 671 | return result; 672 | } 673 | 674 | - (NSURL *)URLWithValue:(NSString *)value forComponent:(NSString *)component 675 | { 676 | NSMutableDictionary *components = (NSMutableDictionary *)self.components; 677 | if (value) 678 | { 679 | components[component] = value; 680 | } 681 | else 682 | { 683 | [components removeObjectForKey:component]; 684 | } 685 | return [NSURL URLWithComponents:components]; 686 | } 687 | 688 | - (NSURL *)URLWithScheme:(NSString *)scheme 689 | { 690 | NSString *URLString = self.absoluteString; 691 | URLString = [URLString substringFromIndex:self.scheme.length]; 692 | return (NSURL *)[NSURL URLWithString:[scheme stringByAppendingString:URLString]]; 693 | } 694 | 695 | - (NSURL *)URLWithHost:(NSString *)host 696 | { 697 | return [self URLWithValue:host forComponent:URLHostComponent]; 698 | } 699 | 700 | - (NSURL *)URLWithPort:(NSString *)port 701 | { 702 | return [self URLWithValue:port forComponent:URLPortComponent]; 703 | } 704 | 705 | - (NSURL *)URLWithUser:(NSString *)user 706 | { 707 | return [self URLWithValue:user forComponent:URLUserComponent]; 708 | } 709 | 710 | - (NSURL *)URLWithPassword:(NSString *)password 711 | { 712 | return [self URLWithValue:password forComponent:URLPasswordComponent]; 713 | } 714 | 715 | - (NSURL *)URLWithPath:(NSString *)path 716 | { 717 | return [self URLWithValue:path forComponent:URLPathComponent]; 718 | } 719 | 720 | - (NSURL *)URLWithParameterString:(NSString *)parameterString 721 | { 722 | return [self URLWithValue:parameterString forComponent:URLParameterStringComponent]; 723 | } 724 | 725 | - (NSURL *)URLWithQuery:(NSString *)query 726 | { 727 | return [self URLWithValue:query forComponent:URLQueryComponent]; 728 | } 729 | 730 | - (NSURL *)URLWithFragment:(NSString *)fragment 731 | { 732 | return [self URLWithValue:fragment forComponent:URLFragmentComponent]; 733 | } 734 | 735 | @end 736 | 737 | 738 | @implementation NSURLRequest (RequestUtils) 739 | 740 | + (instancetype)HTTPRequestWithURL:(NSURL *)URL method:(NSString *)method parameters:(NSDictionary *)parameters 741 | { 742 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; 743 | method = method.uppercaseString; 744 | request.HTTPMethod = method; 745 | 746 | //set method and parameters 747 | if ([method isEqualToString:@"GET"]) 748 | { 749 | [request addGETParameters:parameters options:URLQueryOptionDefault]; 750 | } 751 | else 752 | { 753 | [request setPOSTParameters:parameters options:URLQueryOptionDefault]; 754 | } 755 | 756 | //accept gzip encoded data by default 757 | [request addValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"]; 758 | 759 | return request; 760 | } 761 | 762 | + (instancetype)GETRequestWithURL:(NSURL *)URL parameters:(NSDictionary *)parameters 763 | { 764 | return [self HTTPRequestWithURL:URL method:@"GET" parameters:parameters]; 765 | } 766 | 767 | + (instancetype)POSTRequestWithURL:(NSURL *)URL parameters:(NSDictionary *)parameters 768 | { 769 | return [self HTTPRequestWithURL:URL method:@"POST" parameters:parameters]; 770 | } 771 | 772 | - (nullable NSDictionary *)GETParameters 773 | { 774 | return self.URL.query.URLQueryParameters; 775 | } 776 | 777 | - (nullable NSDictionary *)POSTParameters 778 | { 779 | return [self.HTTPBody RequestUtils_UTF8String].URLQueryParameters; 780 | } 781 | 782 | - (nullable NSArray *)HTTPBasicAuthComponents 783 | { 784 | NSString *authHeader = [self valueForHTTPHeaderField:@"Authorization"]; 785 | return [[authHeader stringByReplacingOccurrencesOfString:@"Basic " withString:@""].base64DecodedString componentsSeparatedByString:@":"]; 786 | } 787 | 788 | - (nullable NSString *)HTTPBasicAuthUser 789 | { 790 | NSString *user = [self HTTPBasicAuthComponents].firstObject; 791 | return user.length? user: self.URL.user; 792 | } 793 | 794 | - (nullable NSString *)HTTPBasicAuthPassword 795 | { 796 | NSArray *components = [self HTTPBasicAuthComponents]; 797 | return components.count == 2? components.lastObject: self.URL.password; 798 | } 799 | 800 | @end 801 | 802 | 803 | @implementation NSMutableURLRequest (RequestUtils) 804 | 805 | - (void)setGETParameters:(NSDictionary *)parameters 806 | { 807 | [self setGETParameters:parameters options:URLQueryOptionDefault]; 808 | } 809 | 810 | - (void)setGETParameters:(NSDictionary *)parameters options:(URLQueryOptions)options 811 | { 812 | self.URL = [self.URL URLWithQuery:[NSString URLQueryWithParameters:parameters options:options]]; 813 | } 814 | 815 | - (void)addGETParameters:(NSDictionary *)parameters options:(URLQueryOptions)options 816 | { 817 | NSString *query = [NSString URLQueryWithParameters:parameters options:options]; 818 | NSString *existingQuery = self.URL.query; 819 | if (existingQuery.length) 820 | { 821 | query = [existingQuery stringByMergingURLQuery:query options:options]; 822 | } 823 | self.URL = [self.URL URLWithQuery:query]; 824 | } 825 | 826 | - (void)setPOSTParameters:(NSDictionary *)parameters 827 | { 828 | [self setPOSTParameters:parameters options:URLQueryOptionDefault]; 829 | } 830 | 831 | - (void)setPOSTParameterString:(NSString *)parameterString 832 | { 833 | NSData *data = [parameterString dataUsingEncoding:NSUTF8StringEncoding]; 834 | [self addValue:@"8bit" forHTTPHeaderField:@"Content-Transfer-Encoding"]; 835 | [self addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 836 | [self addValue:[NSString stringWithFormat:@"%tu", data.length] forHTTPHeaderField:@"Content-Length"]; 837 | [self setHTTPBody:data]; 838 | } 839 | 840 | - (void)setPOSTParameters:(NSDictionary *)parameters options:(URLQueryOptions)options 841 | { 842 | NSString *content = [NSString URLQueryWithParameters:parameters options:options]; 843 | [self setPOSTParameterString:content]; 844 | } 845 | 846 | - (void)addPOSTParameters:(NSDictionary *)parameters options:(URLQueryOptions)options 847 | { 848 | NSString *query = [NSString URLQueryWithParameters:parameters options:options]; 849 | NSString *content = [[self.HTTPBody RequestUtils_UTF8String] ?: @"" stringByMergingURLQuery:query options:options]; 850 | [self setPOSTParameterString:content]; 851 | } 852 | 853 | - (void)setHTTPBasicAuthUser:(NSString *)user password:(nullable NSString *)password 854 | { 855 | NSString *authHeader = [NSString stringWithFormat:@"%@:%@", user ?: @"", password ?: @""]; 856 | authHeader = [NSString stringWithFormat:@"Basic %@", authHeader.base64EncodedString]; 857 | [self addValue:authHeader forHTTPHeaderField:@"Authorization"]; 858 | } 859 | 860 | @end 861 | -------------------------------------------------------------------------------- /Tests/RequestUtilsTests.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 01244B071932950F000BF3CD /* RequestTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 01244B041932950F000BF3CD /* RequestTests.m */; }; 11 | 01244B081932950F000BF3CD /* StringTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 01244B061932950F000BF3CD /* StringTests.m */; }; 12 | 01244B0C1932953A000BF3CD /* RequestUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = 01244B0B1932953A000BF3CD /* RequestUtils.m */; }; 13 | 01D28C891907BFC80021C719 /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 01D28C881907BFC80021C719 /* XCTest.framework */; }; 14 | 01D28C8A1907BFC80021C719 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 01D28C6F1907BFC80021C719 /* Foundation.framework */; }; 15 | 01D28C8B1907BFC80021C719 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 01D28C731907BFC80021C719 /* UIKit.framework */; }; 16 | 5D2BE8EE1985DE4000C4A333 /* URLTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 5D2BE8ED1985DE4000C4A333 /* URLTests.m */; }; 17 | /* End PBXBuildFile section */ 18 | 19 | /* Begin PBXFileReference section */ 20 | 01244B041932950F000BF3CD /* RequestTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RequestTests.m; sourceTree = ""; }; 21 | 01244B061932950F000BF3CD /* StringTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = StringTests.m; sourceTree = ""; }; 22 | 01244B0A1932953A000BF3CD /* RequestUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RequestUtils.h; sourceTree = ""; }; 23 | 01244B0B1932953A000BF3CD /* RequestUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RequestUtils.m; sourceTree = ""; }; 24 | 01D28C6F1907BFC80021C719 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; 25 | 01D28C711907BFC80021C719 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; 26 | 01D28C731907BFC80021C719 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; 27 | 01D28C871907BFC80021C719 /* RequestUtilsTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RequestUtilsTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 28 | 01D28C881907BFC80021C719 /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = XCTest.framework; path = Library/Frameworks/XCTest.framework; sourceTree = DEVELOPER_DIR; }; 29 | 01D28C901907BFC80021C719 /* RequestUtilsTests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "RequestUtilsTests-Info.plist"; sourceTree = ""; }; 30 | 5D2BE8ED1985DE4000C4A333 /* URLTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = URLTests.m; sourceTree = ""; }; 31 | /* End PBXFileReference section */ 32 | 33 | /* Begin PBXFrameworksBuildPhase section */ 34 | 01D28C841907BFC80021C719 /* Frameworks */ = { 35 | isa = PBXFrameworksBuildPhase; 36 | buildActionMask = 2147483647; 37 | files = ( 38 | 01D28C891907BFC80021C719 /* XCTest.framework in Frameworks */, 39 | 01D28C8B1907BFC80021C719 /* UIKit.framework in Frameworks */, 40 | 01D28C8A1907BFC80021C719 /* Foundation.framework in Frameworks */, 41 | ); 42 | runOnlyForDeploymentPostprocessing = 0; 43 | }; 44 | /* End PBXFrameworksBuildPhase section */ 45 | 46 | /* Begin PBXGroup section */ 47 | 01244B091932953A000BF3CD /* RequestUtils */ = { 48 | isa = PBXGroup; 49 | children = ( 50 | 01244B0A1932953A000BF3CD /* RequestUtils.h */, 51 | 01244B0B1932953A000BF3CD /* RequestUtils.m */, 52 | ); 53 | name = RequestUtils; 54 | path = ../RequestUtils; 55 | sourceTree = ""; 56 | }; 57 | 01D28C631907BFC80021C719 = { 58 | isa = PBXGroup; 59 | children = ( 60 | 01244B091932953A000BF3CD /* RequestUtils */, 61 | 01D28C8E1907BFC80021C719 /* RequestUtilsTests */, 62 | 01D28C6E1907BFC80021C719 /* Frameworks */, 63 | 01D28C6D1907BFC80021C719 /* Products */, 64 | ); 65 | indentWidth = 4; 66 | sourceTree = ""; 67 | tabWidth = 4; 68 | usesTabs = 0; 69 | }; 70 | 01D28C6D1907BFC80021C719 /* Products */ = { 71 | isa = PBXGroup; 72 | children = ( 73 | 01D28C871907BFC80021C719 /* RequestUtilsTests.xctest */, 74 | ); 75 | name = Products; 76 | sourceTree = ""; 77 | }; 78 | 01D28C6E1907BFC80021C719 /* Frameworks */ = { 79 | isa = PBXGroup; 80 | children = ( 81 | 01D28C6F1907BFC80021C719 /* Foundation.framework */, 82 | 01D28C711907BFC80021C719 /* CoreGraphics.framework */, 83 | 01D28C731907BFC80021C719 /* UIKit.framework */, 84 | 01D28C881907BFC80021C719 /* XCTest.framework */, 85 | ); 86 | name = Frameworks; 87 | sourceTree = ""; 88 | }; 89 | 01D28C8E1907BFC80021C719 /* RequestUtilsTests */ = { 90 | isa = PBXGroup; 91 | children = ( 92 | 01244B041932950F000BF3CD /* RequestTests.m */, 93 | 01244B061932950F000BF3CD /* StringTests.m */, 94 | 5D2BE8ED1985DE4000C4A333 /* URLTests.m */, 95 | 01D28C8F1907BFC80021C719 /* Supporting Files */, 96 | ); 97 | path = RequestUtilsTests; 98 | sourceTree = ""; 99 | }; 100 | 01D28C8F1907BFC80021C719 /* Supporting Files */ = { 101 | isa = PBXGroup; 102 | children = ( 103 | 01D28C901907BFC80021C719 /* RequestUtilsTests-Info.plist */, 104 | ); 105 | name = "Supporting Files"; 106 | sourceTree = ""; 107 | }; 108 | /* End PBXGroup section */ 109 | 110 | /* Begin PBXNativeTarget section */ 111 | 01D28C861907BFC80021C719 /* RequestUtilsTests */ = { 112 | isa = PBXNativeTarget; 113 | buildConfigurationList = 01D28C9B1907BFC80021C719 /* Build configuration list for PBXNativeTarget "RequestUtilsTests" */; 114 | buildPhases = ( 115 | 01D28C831907BFC80021C719 /* Sources */, 116 | 01D28C841907BFC80021C719 /* Frameworks */, 117 | 01D28C851907BFC80021C719 /* Resources */, 118 | ); 119 | buildRules = ( 120 | ); 121 | dependencies = ( 122 | ); 123 | name = RequestUtilsTests; 124 | productName = OSCacheTests; 125 | productReference = 01D28C871907BFC80021C719 /* RequestUtilsTests.xctest */; 126 | productType = "com.apple.product-type.bundle.unit-test"; 127 | }; 128 | /* End PBXNativeTarget section */ 129 | 130 | /* Begin PBXProject section */ 131 | 01D28C641907BFC80021C719 /* Project object */ = { 132 | isa = PBXProject; 133 | attributes = { 134 | LastUpgradeCheck = 0720; 135 | ORGANIZATIONNAME = "Charcoal Design"; 136 | TargetAttributes = { 137 | 01D28C861907BFC80021C719 = { 138 | TestTargetID = 01D28C6B1907BFC80021C719; 139 | }; 140 | }; 141 | }; 142 | buildConfigurationList = 01D28C671907BFC80021C719 /* Build configuration list for PBXProject "RequestUtilsTests" */; 143 | compatibilityVersion = "Xcode 3.2"; 144 | developmentRegion = English; 145 | hasScannedForEncodings = 0; 146 | knownRegions = ( 147 | en, 148 | ); 149 | mainGroup = 01D28C631907BFC80021C719; 150 | productRefGroup = 01D28C6D1907BFC80021C719 /* Products */; 151 | projectDirPath = ""; 152 | projectRoot = ""; 153 | targets = ( 154 | 01D28C861907BFC80021C719 /* RequestUtilsTests */, 155 | ); 156 | }; 157 | /* End PBXProject section */ 158 | 159 | /* Begin PBXResourcesBuildPhase section */ 160 | 01D28C851907BFC80021C719 /* Resources */ = { 161 | isa = PBXResourcesBuildPhase; 162 | buildActionMask = 2147483647; 163 | files = ( 164 | ); 165 | runOnlyForDeploymentPostprocessing = 0; 166 | }; 167 | /* End PBXResourcesBuildPhase section */ 168 | 169 | /* Begin PBXSourcesBuildPhase section */ 170 | 01D28C831907BFC80021C719 /* Sources */ = { 171 | isa = PBXSourcesBuildPhase; 172 | buildActionMask = 2147483647; 173 | files = ( 174 | 01244B081932950F000BF3CD /* StringTests.m in Sources */, 175 | 01244B071932950F000BF3CD /* RequestTests.m in Sources */, 176 | 01244B0C1932953A000BF3CD /* RequestUtils.m in Sources */, 177 | 5D2BE8EE1985DE4000C4A333 /* URLTests.m in Sources */, 178 | ); 179 | runOnlyForDeploymentPostprocessing = 0; 180 | }; 181 | /* End PBXSourcesBuildPhase section */ 182 | 183 | /* Begin XCBuildConfiguration section */ 184 | 01D28C961907BFC80021C719 /* Debug */ = { 185 | isa = XCBuildConfiguration; 186 | buildSettings = { 187 | ALWAYS_SEARCH_USER_PATHS = NO; 188 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 189 | CLANG_CXX_LIBRARY = "libc++"; 190 | CLANG_ENABLE_MODULES = NO; 191 | CLANG_ENABLE_OBJC_ARC = YES; 192 | CLANG_WARN_ASSIGN_ENUM = YES; 193 | CLANG_WARN_BOOL_CONVERSION = YES; 194 | CLANG_WARN_CONSTANT_CONVERSION = YES; 195 | CLANG_WARN_CXX0X_EXTENSIONS = YES; 196 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 197 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 198 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 199 | CLANG_WARN_EMPTY_BODY = YES; 200 | CLANG_WARN_ENUM_CONVERSION = YES; 201 | CLANG_WARN_IMPLICIT_SIGN_CONVERSION = YES; 202 | CLANG_WARN_INT_CONVERSION = YES; 203 | CLANG_WARN_OBJC_EXPLICIT_OWNERSHIP_TYPE = YES; 204 | CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES; 205 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 206 | CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES; 207 | CLANG_WARN_OBJC_RECEIVER_WEAK = YES; 208 | CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES; 209 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 210 | CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES; 211 | CLANG_WARN_UNREACHABLE_CODE = YES; 212 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 213 | CLANG_WARN__EXIT_TIME_DESTRUCTORS = YES; 214 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 215 | COPY_PHASE_STRIP = NO; 216 | ENABLE_TESTABILITY = YES; 217 | GCC_C_LANGUAGE_STANDARD = gnu99; 218 | GCC_DYNAMIC_NO_PIC = NO; 219 | GCC_OPTIMIZATION_LEVEL = 0; 220 | GCC_PREPROCESSOR_DEFINITIONS = ( 221 | "DEBUG=1", 222 | "$(inherited)", 223 | ); 224 | GCC_SHORT_ENUMS = YES; 225 | GCC_SYMBOLS_PRIVATE_EXTERN = NO; 226 | GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES; 227 | GCC_TREAT_INCOMPATIBLE_POINTER_TYPE_WARNINGS_AS_ERRORS = YES; 228 | GCC_TREAT_WARNINGS_AS_ERRORS = YES; 229 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 230 | GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES; 231 | GCC_WARN_ABOUT_MISSING_NEWLINE = YES; 232 | GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; 233 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 234 | GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES; 235 | GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES; 236 | GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES; 237 | GCC_WARN_MULTIPLE_DEFINITION_TYPES_FOR_SELECTOR = YES; 238 | GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES; 239 | GCC_WARN_PEDANTIC = YES; 240 | GCC_WARN_SHADOW = YES; 241 | GCC_WARN_SIGN_COMPARE = YES; 242 | GCC_WARN_STRICT_SELECTOR_MATCH = YES; 243 | GCC_WARN_UNDECLARED_SELECTOR = YES; 244 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 245 | GCC_WARN_UNKNOWN_PRAGMAS = YES; 246 | GCC_WARN_UNUSED_FUNCTION = YES; 247 | GCC_WARN_UNUSED_LABEL = YES; 248 | GCC_WARN_UNUSED_PARAMETER = YES; 249 | GCC_WARN_UNUSED_VARIABLE = YES; 250 | IPHONEOS_DEPLOYMENT_TARGET = 9.2; 251 | ONLY_ACTIVE_ARCH = YES; 252 | SDKROOT = iphoneos; 253 | WARNING_CFLAGS = ( 254 | "-Weverything", 255 | "-Wno-variadic-macros", 256 | "-Wno-gnu-zero-variadic-macro-arguments", 257 | "-Wno-gnu-statement-expression", 258 | "-Wno-objc-missing-property-synthesis", 259 | "-Wno-sign-compare", 260 | "-Wno-documentation-unknown-command", 261 | "-Wno-cstring-format-directive", 262 | "-Wno-undef", 263 | "-Wno-reserved-id-macro", 264 | "-Wno-unknown-warning-option", 265 | ); 266 | }; 267 | name = Debug; 268 | }; 269 | 01D28C971907BFC80021C719 /* Release */ = { 270 | isa = XCBuildConfiguration; 271 | buildSettings = { 272 | ALWAYS_SEARCH_USER_PATHS = NO; 273 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 274 | CLANG_CXX_LIBRARY = "libc++"; 275 | CLANG_ENABLE_MODULES = NO; 276 | CLANG_ENABLE_OBJC_ARC = YES; 277 | CLANG_WARN_ASSIGN_ENUM = YES; 278 | CLANG_WARN_BOOL_CONVERSION = YES; 279 | CLANG_WARN_CONSTANT_CONVERSION = YES; 280 | CLANG_WARN_CXX0X_EXTENSIONS = YES; 281 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 282 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 283 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 284 | CLANG_WARN_EMPTY_BODY = YES; 285 | CLANG_WARN_ENUM_CONVERSION = YES; 286 | CLANG_WARN_IMPLICIT_SIGN_CONVERSION = YES; 287 | CLANG_WARN_INT_CONVERSION = YES; 288 | CLANG_WARN_OBJC_EXPLICIT_OWNERSHIP_TYPE = YES; 289 | CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES; 290 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 291 | CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS = YES; 292 | CLANG_WARN_OBJC_RECEIVER_WEAK = YES; 293 | CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES; 294 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 295 | CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION = YES; 296 | CLANG_WARN_UNREACHABLE_CODE = YES; 297 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 298 | CLANG_WARN__EXIT_TIME_DESTRUCTORS = YES; 299 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 300 | COPY_PHASE_STRIP = YES; 301 | ENABLE_NS_ASSERTIONS = NO; 302 | GCC_C_LANGUAGE_STANDARD = gnu99; 303 | GCC_SHORT_ENUMS = YES; 304 | GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES; 305 | GCC_TREAT_INCOMPATIBLE_POINTER_TYPE_WARNINGS_AS_ERRORS = YES; 306 | GCC_TREAT_WARNINGS_AS_ERRORS = YES; 307 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 308 | GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES; 309 | GCC_WARN_ABOUT_MISSING_NEWLINE = YES; 310 | GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; 311 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 312 | GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES; 313 | GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES; 314 | GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES; 315 | GCC_WARN_MULTIPLE_DEFINITION_TYPES_FOR_SELECTOR = YES; 316 | GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES; 317 | GCC_WARN_PEDANTIC = YES; 318 | GCC_WARN_SHADOW = YES; 319 | GCC_WARN_SIGN_COMPARE = YES; 320 | GCC_WARN_STRICT_SELECTOR_MATCH = YES; 321 | GCC_WARN_UNDECLARED_SELECTOR = YES; 322 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 323 | GCC_WARN_UNKNOWN_PRAGMAS = YES; 324 | GCC_WARN_UNUSED_FUNCTION = YES; 325 | GCC_WARN_UNUSED_LABEL = YES; 326 | GCC_WARN_UNUSED_PARAMETER = YES; 327 | GCC_WARN_UNUSED_VARIABLE = YES; 328 | IPHONEOS_DEPLOYMENT_TARGET = 9.2; 329 | SDKROOT = iphoneos; 330 | VALIDATE_PRODUCT = YES; 331 | WARNING_CFLAGS = ( 332 | "-Weverything", 333 | "-Wno-variadic-macros", 334 | "-Wno-gnu-zero-variadic-macro-arguments", 335 | "-Wno-gnu-statement-expression", 336 | "-Wno-objc-missing-property-synthesis", 337 | "-Wno-sign-compare", 338 | "-Wno-documentation-unknown-command", 339 | "-Wno-cstring-format-directive", 340 | "-Wno-undef", 341 | "-Wno-reserved-id-macro", 342 | "-Wno-unknown-warning-option", 343 | ); 344 | }; 345 | name = Release; 346 | }; 347 | 01D28C9C1907BFC80021C719 /* Debug */ = { 348 | isa = XCBuildConfiguration; 349 | buildSettings = { 350 | FRAMEWORK_SEARCH_PATHS = ( 351 | "$(SDKROOT)/Developer/Library/Frameworks", 352 | "$(inherited)", 353 | "$(DEVELOPER_FRAMEWORKS_DIR)", 354 | ); 355 | GCC_PRECOMPILE_PREFIX_HEADER = YES; 356 | GCC_PREPROCESSOR_DEFINITIONS = ( 357 | "DEBUG=1", 358 | "$(inherited)", 359 | ); 360 | INFOPLIST_FILE = "RequestUtilsTests/RequestUtilsTests-Info.plist"; 361 | PRODUCT_BUNDLE_IDENTIFIER = "com.charcoaldesign.${PRODUCT_NAME:rfc1034identifier}"; 362 | PRODUCT_NAME = RequestUtilsTests; 363 | TEST_HOST = "$(BUNDLE_LOADER)"; 364 | WRAPPER_EXTENSION = xctest; 365 | }; 366 | name = Debug; 367 | }; 368 | 01D28C9D1907BFC80021C719 /* Release */ = { 369 | isa = XCBuildConfiguration; 370 | buildSettings = { 371 | FRAMEWORK_SEARCH_PATHS = ( 372 | "$(SDKROOT)/Developer/Library/Frameworks", 373 | "$(inherited)", 374 | "$(DEVELOPER_FRAMEWORKS_DIR)", 375 | ); 376 | GCC_PRECOMPILE_PREFIX_HEADER = YES; 377 | INFOPLIST_FILE = "RequestUtilsTests/RequestUtilsTests-Info.plist"; 378 | PRODUCT_BUNDLE_IDENTIFIER = "com.charcoaldesign.${PRODUCT_NAME:rfc1034identifier}"; 379 | PRODUCT_NAME = RequestUtilsTests; 380 | TEST_HOST = "$(BUNDLE_LOADER)"; 381 | WRAPPER_EXTENSION = xctest; 382 | }; 383 | name = Release; 384 | }; 385 | /* End XCBuildConfiguration section */ 386 | 387 | /* Begin XCConfigurationList section */ 388 | 01D28C671907BFC80021C719 /* Build configuration list for PBXProject "RequestUtilsTests" */ = { 389 | isa = XCConfigurationList; 390 | buildConfigurations = ( 391 | 01D28C961907BFC80021C719 /* Debug */, 392 | 01D28C971907BFC80021C719 /* Release */, 393 | ); 394 | defaultConfigurationIsVisible = 0; 395 | defaultConfigurationName = Release; 396 | }; 397 | 01D28C9B1907BFC80021C719 /* Build configuration list for PBXNativeTarget "RequestUtilsTests" */ = { 398 | isa = XCConfigurationList; 399 | buildConfigurations = ( 400 | 01D28C9C1907BFC80021C719 /* Debug */, 401 | 01D28C9D1907BFC80021C719 /* Release */, 402 | ); 403 | defaultConfigurationIsVisible = 0; 404 | defaultConfigurationName = Release; 405 | }; 406 | /* End XCConfigurationList section */ 407 | }; 408 | rootObject = 01D28C641907BFC80021C719 /* Project object */; 409 | } 410 | -------------------------------------------------------------------------------- /Tests/RequestUtilsTests.xcodeproj/xcshareddata/xcschemes/RequestUtilsTests.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 14 | 15 | 17 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 39 | 40 | 41 | 42 | 48 | 49 | 51 | 52 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /Tests/RequestUtilsTests/RequestTests.m: -------------------------------------------------------------------------------- 1 | // 2 | // RequestTests.m 3 | // RequestUtilsTests 4 | // 5 | // Created by Nick Lockwood on 11/09/2012. 6 | // 7 | // 8 | 9 | #import 10 | #import "RequestUtils.h" 11 | 12 | 13 | @interface RequestTests : XCTestCase 14 | 15 | @end 16 | 17 | 18 | @implementation RequestTests 19 | 20 | #pragma mark Request generation 21 | 22 | - (void)testGETRequest 23 | { 24 | NSURL *URL = [NSURL URLWithString:@"http://example.com"]; 25 | NSDictionary *parameters = [@"foo=bar&bar=foo" URLQueryParameters]; 26 | NSURLRequest *request = [NSURLRequest GETRequestWithURL:URL parameters:parameters]; 27 | XCTAssertEqualObjects([request GETParameters], parameters, @"GETRequest test failed"); 28 | } 29 | 30 | - (void)testGETRequest2 31 | { 32 | NSURL *URL = [NSURL URLWithString:@"http://example.com?foo=bar"]; 33 | NSDictionary *parameters = [@"bar=foo" URLQueryParameters]; 34 | NSDictionary *result = [@"foo=bar&bar=foo" URLQueryParameters]; 35 | NSURLRequest *request = [NSURLRequest GETRequestWithURL:URL parameters:parameters]; 36 | XCTAssertEqualObjects([request GETParameters], result, @"GETRequest2 test failed"); 37 | } 38 | 39 | - (void)testGETRequest3 40 | { 41 | NSURL *URL = [NSURL URLWithString:@"http://example.com?"]; 42 | NSDictionary *parameters = [@"foo=bar&bar=foo" URLQueryParameters]; 43 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL]; 44 | [request addGETParameters:parameters options:0]; 45 | NSURL *result = [NSURL URLWithString:@"http://example.com?foo=bar&bar=foo"]; 46 | XCTAssertEqualObjects([request URL], result, @"GETRequest3 test failed"); 47 | } 48 | 49 | - (void)testPOSTRequest 50 | { 51 | NSURL *URL = [NSURL URLWithString:@"http://example.com"]; 52 | NSDictionary *parameters = [@"foo=bar&bar=foo" URLQueryParameters]; 53 | NSURLRequest *request = [NSURLRequest POSTRequestWithURL:URL parameters:parameters]; 54 | XCTAssertEqualObjects([request POSTParameters], parameters, @"POSTRequest test failed"); 55 | } 56 | 57 | - (void)testNonStringPOSTParams 58 | { 59 | NSURL *URL = [NSURL URLWithString:@"http://example.com"]; 60 | NSDictionary *parameters = @{@"foo": @1, @"bar": [NSValue valueWithRange:NSMakeRange(1, 10)]}; 61 | NSURLRequest *request = [NSURLRequest POSTRequestWithURL:URL parameters:parameters]; 62 | NSDictionary *result = @{@"foo": [parameters[@"foo"] description], @"bar": [parameters[@"bar"] description]}; 63 | XCTAssertEqualObjects([request POSTParameters], result, @"POSTRequest non-strings test failed"); 64 | } 65 | 66 | @end 67 | -------------------------------------------------------------------------------- /Tests/RequestUtilsTests/RequestUtilsTests-Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundlePackageType 14 | BNDL 15 | CFBundleShortVersionString 16 | 1.0 17 | CFBundleSignature 18 | ???? 19 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /Tests/RequestUtilsTests/StringTests.m: -------------------------------------------------------------------------------- 1 | // 2 | // StringTests.m 3 | // RequestUtilsTests 4 | // 5 | // Created by Nick Lockwood on 12/01/2012. 6 | // Copyright (c) 2012 __MyCompanyName__. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "RequestUtils.h" 11 | 12 | 13 | @interface StringTests : XCTestCase 14 | 15 | @end 16 | 17 | 18 | @implementation StringTests 19 | 20 | #pragma mark URL parsing 21 | 22 | - (void)testInvalidURL 23 | { 24 | NSString *invalidURLString = @"foo\\bar"; 25 | XCTAssertNil([invalidURLString URLValue]); 26 | } 27 | 28 | - (void)testURLFragment 29 | { 30 | NSString *validURLString = @"?foo=bar"; 31 | XCTAssertNotNil([validURLString URLValue]); 32 | XCTAssertEqualObjects([[validURLString URLValue] query], @"foo=bar"); 33 | } 34 | 35 | #pragma mark Paths 36 | 37 | - (void)textURLEncoding 38 | { 39 | NSString *input = @"foo bar"; 40 | XCTAssertEqualObjects([input URLEncodedString], @"foo%20bar"); 41 | } 42 | 43 | #pragma mark Paths 44 | 45 | - (void)testAppendPath 46 | { 47 | NSString *URLString = @"http://hello"; 48 | URLString = [URLString stringByAppendingURLPathComponent:@"world"]; 49 | XCTAssertEqualObjects(URLString, @"http://hello/world"); 50 | } 51 | 52 | - (void)testAppendPath2 53 | { 54 | NSString *URLString = @"http://hello?foo=bar"; 55 | URLString = [URLString stringByAppendingURLPathComponent:@"world"]; 56 | XCTAssertEqualObjects(URLString, @"http://hello/world?foo=bar"); 57 | } 58 | 59 | - (void)testAppendPath3 60 | { 61 | NSString *URLString = @"hello#world"; 62 | URLString = [URLString stringByAppendingURLPathComponent:@"world"]; 63 | XCTAssertEqualObjects(URLString, @"hello/world#world"); 64 | } 65 | 66 | #pragma mark Path extension 67 | 68 | - (void)testAppendPathExtension 69 | { 70 | NSString *URLString = @"http://hello"; 71 | URLString = [URLString stringByAppendingURLPathExtension:@"world"]; 72 | XCTAssertEqualObjects(URLString, @"http://hello.world"); 73 | } 74 | 75 | #pragma mark Query strings 76 | 77 | - (void)testSimpleQueryString 78 | { 79 | NSString *query = @"?foo=bar&bar=foo"; 80 | NSDictionary *result = @{@"foo": @"bar", @"bar": @"foo"}; 81 | XCTAssertEqualObjects([query URLQueryParametersWithOptions:0], result); 82 | } 83 | 84 | - (void)testArrayQueryString 85 | { 86 | NSString *query = @"?foo=bar&bar=foo&bar=bar"; 87 | NSDictionary *result1 = @{@"foo": @"bar", @"bar": @[@"foo", @"bar"]}; 88 | NSDictionary *result2 = @{@"foo": @"bar", @"bar": @"bar"}; 89 | NSDictionary *result3 = @{@"foo": @[@"bar"], @"bar": @[@"foo", @"bar"]}; 90 | XCTAssertEqualObjects([query URLQueryParametersWithOptions:URLQueryOptionUseArrays], result1); 91 | XCTAssertEqualObjects([query URLQueryParametersWithOptions:URLQueryOptionKeepLastValue], result2); 92 | XCTAssertEqualObjects([query URLQueryParametersWithOptions:URLQueryOptionAlwaysUseArrays], result3); 93 | } 94 | 95 | - (void)testArrayQueryString2 96 | { 97 | NSString *query = @"?foo[]=bar&bar[]=foo&bar[]=bar"; 98 | NSDictionary *result1 = @{@"foo": @[@"bar"], @"bar": @[@"foo", @"bar"]}; 99 | NSDictionary *result2 = @{@"foo": @"bar", @"bar": @"bar"}; 100 | XCTAssertEqualObjects([query URLQueryParametersWithOptions:URLQueryOptionUseArrays], result1); 101 | XCTAssertEqualObjects([query URLQueryParametersWithOptions:URLQueryOptionKeepLastValue], result2); 102 | } 103 | 104 | - (void)testUseArraySyntax 105 | { 106 | NSDictionary *params = @{@"foo": @"bar", @"bar": @[@"foo"]}; 107 | NSString *result1 = @"foo=bar&bar[]=foo"; 108 | NSString *result2 = @"foo[]=bar&bar[]=foo"; 109 | XCTAssertEqualObjects([NSString URLQueryWithParameters:params options:(URLQueryOptions)(URLQueryOptionUseArrays|URLQueryOptionUseArraySyntax)], result1, @"failed"); 110 | XCTAssertEqualObjects([NSString URLQueryWithParameters:params options:(URLQueryOptions)(URLQueryOptionAlwaysUseArrays|URLQueryOptionUseArraySyntax)], result2, @"failed"); 111 | } 112 | 113 | - (void)testAppendQuery 114 | { 115 | NSString *query1 = @"?foo=bar"; 116 | NSString *query2 = @"foo=bar"; 117 | NSString *URLString1 = @"http://apple.com?"; 118 | NSString *URLString2 = @"http://apple.com"; 119 | NSString *result = @"http://apple.com?foo=bar"; 120 | XCTAssertEqualObjects([URLString1 stringByAppendingURLQuery:query1], result); 121 | XCTAssertEqualObjects([URLString1 stringByAppendingURLQuery:query2], result); 122 | XCTAssertEqualObjects([URLString2 stringByAppendingURLQuery:query1], result); 123 | XCTAssertEqualObjects([URLString2 stringByAppendingURLQuery:query2], result); 124 | } 125 | 126 | - (void)testMergeQuery 127 | { 128 | NSString *query1 = @"?foo=bar"; 129 | NSString *query2 = @"foo=bar"; 130 | NSString *URLString1 = @"http://apple.com?"; 131 | NSString *URLString2 = @"http://apple.com"; 132 | NSString *URLString3 = @"http://apple.com?baz=bleem"; 133 | NSString *result1 = @"http://apple.com?foo=bar"; 134 | NSString *result2 = @"http://apple.com?baz=bleem&foo=bar"; 135 | XCTAssertEqualObjects([URLString1 stringByMergingURLQuery:query1], result1); 136 | XCTAssertEqualObjects([URLString1 stringByMergingURLQuery:query2], result1); 137 | XCTAssertEqualObjects([URLString2 stringByMergingURLQuery:query1], result1); 138 | XCTAssertEqualObjects([URLString2 stringByMergingURLQuery:query2], result1); 139 | XCTAssertEqualObjects([URLString3 stringByMergingURLQuery:query1], result2); 140 | XCTAssertEqualObjects([URLString3 stringByMergingURLQuery:query2], result2); 141 | } 142 | 143 | - (void)testOrderedQuery 144 | { 145 | NSDictionary *parameters = @{@"baz": @1, @"foo": @2, @"bar": @3}; 146 | NSString *result = @"bar=3&baz=1&foo=2"; 147 | XCTAssertEqualObjects([NSString URLQueryWithParameters:parameters options:URLQueryOptionSortKeys], result); 148 | } 149 | 150 | @end 151 | -------------------------------------------------------------------------------- /Tests/RequestUtilsTests/URLTests.m: -------------------------------------------------------------------------------- 1 | // 2 | // URLTests.m 3 | // RequestUtilsTests 4 | // 5 | // Created by Tate Johnson on 28/07/2014. 6 | // Copyright (c) 2014 Charcoal Design. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "RequestUtils.h" 11 | 12 | 13 | @interface URLTests : XCTestCase 14 | 15 | @end 16 | 17 | @implementation URLTests 18 | 19 | - (void)testURLWithPath 20 | { 21 | NSURL *url = [[NSURL URLWithString:@"http://local.host"] URLWithPath:@"/test"]; 22 | XCTAssertEqualObjects([url absoluteString], @"http://local.host/test"); 23 | } 24 | 25 | @end 26 | --------------------------------------------------------------------------------