diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..e4f81142 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,22 @@ + +# EditorConfig helps developers define and maintain consistent +# coding styles between different editors and IDEs +# editorconfig.org + +root = true + + +[*] + +# Change these settings to your own preference +indent_style = space +indent_size = 4 + +# We recommend you to keep these unchanged +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.md] +trim_trailing_whitespace = false \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..2fe8c5f4 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,46 @@ +# Changelog + +## v1.0.0 + +- Added getBasicAuthHeader function +- Added necessary iOS framework (Thanks to EddyVerbruggen) +- Request internet permission in android (Thanks to mbektchiev) +- Fix acceptAllCerts doesn't call callbacks (Thanks to EddyVerbruggen) +- Add validateDomainName (Thanks to denisbabineau) +- Add HEAD request support (untested) (Thanks to denisbabineau) + +### Potentially Breaking Changes + +- Update cordova file plugin dependency (Thanks to denisbabineau) +- useBasicAuthHeader and setHeader are now synchronous functions +- updated AFNetworking to 3.0.4 - only iOS 7+ is now supported +- updated http-request to 6.0 + +## v0.1.4 + +- Support for certificates in www/certificates folder (Thanks to EddyVerbruggen) + +## v0.1.3 + +- Update AFNetworking to 2.4.1 for iOS bug fix in Xcode 6 + +## v0.1.2 + +- Fixed plugin.xml for case sensitive filesystems (Thanks to andrey-tsaplin) + +## v0.1.1 + +- Fixed a bug that prevented building + +## v0.1.0 + +- Initial release + + +## Contributions not noted above + +- Fixed examples (Thanks to devgeeks) +- Reports SSL Handshake errors rather than giving a generic error (Thanks to devgeeks) +- Exporting http as a module (Thanks to pvsaikrishna) +- Added Limitations section to readme (Thanks to cvillerm) +- Fixed examples (Thanks to hideov) \ No newline at end of file diff --git a/README.md b/README.md index 589ff7f9..3ef1665e 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,10 @@ Cordova / Phonegap plugin for communicating with HTTP servers. Supports iOS and - Background threading - all requests are done in a background thread. - SSL Pinning - read more at [LumberBlog](http://blog.lumberlabs.com/2012/04/why-app-developers-should-care-about.html). +## Updates + +Please check [CHANGELOG.md](CHANGELOG.md) for details about updating to a new version. + ## Installation The plugin conforms to the Cordova plugin specification, it can be installed @@ -32,30 +36,31 @@ You can then inject the cordovaHTTP service into your controllers. The function This plugin registers a `cordovaHTTP` global on window -## Functions +## Sync Functions + +### getBasicAuthHeader +This returns an object representing a basic HTTP Authorization header of the form `{'Authorization': 'Basic base64encodedusernameandpassword'}` -All available functions are documented below. Every function takes a success and error callback function as the last 2 arguments. + var header = cordovaHTTP.getBasicAuthHeader("user", "password"); ### useBasicAuth This sets up all future requests to use Basic HTTP authentication with the given username and password. - cordovaHTTP.useBasicAuth("user", "password", function() { - console.log('success!'); - }, function() { - console.log('error :('); - }); + cordovaHTTP.useBasicAuth("user", "password"); ### setHeader Set a header for all future requests. Takes a header and a value. - cordovaHTTP.setHeader("Header", "Value", function() { - console.log('success!'); - }, function() { - console.log('error :('); - }); + cordovaHTTP.setHeader("Header", "Value"); + + +## Async Functions +These functions all take success and error callbacks as their last 2 arguments. ### enableSSLPinning -Enable or disable SSL pinning. To use SSL pinning you must include at least one .cer SSL certificate in your app project. You can pin to your server certificate or to one of the issuing CA certificates. For ios include your certificate in the root level of your bundle (just add the .cer file to your project/target at the root level). For android include your certificate in your project's platforms/android/assets folder. In both cases all .cer files found will be loaded automatically. If you only have a .pem certificate see this [stackoverflow answer](http://stackoverflow.com/a/16583429/3182729). You want to convert it to a DER encoded certificate with a .cer extension. +Enable or disable SSL pinning. This defaults to false. + +To use SSL pinning you must include at least one .cer SSL certificate in your app project. You can pin to your server certificate or to one of the issuing CA certificates. For ios include your certificate in the root level of your bundle (just add the .cer file to your project/target at the root level). For android include your certificate in your project's platforms/android/assets folder. In both cases all .cer files found will be loaded automatically. If you only have a .pem certificate see this [stackoverflow answer](http://stackoverflow.com/a/16583429/3182729). You want to convert it to a DER encoded certificate with a .cer extension. As an alternative, you can store your .cer files in the www/certificates folder. @@ -66,7 +71,7 @@ As an alternative, you can store your .cer files in the www/certificates folder. }); ### acceptAllCerts -Accept all SSL certificates. Or disable accepting all certificates. +Accept all SSL certificates. Or disable accepting all certificates. This defaults to false. cordovaHTTP.acceptAllCerts(true, function() { console.log('success!'); @@ -74,6 +79,15 @@ Accept all SSL certificates. Or disable accepting all certificates. console.log('error :('); }); +### validateDomainName +Whether or not to validate the domain name in the certificate. This defaults to true. + + cordovaHTTP.validateDomainName(false, function() { + console.log('success!'); + }, function() { + console.log('error :('); + }); + ### post Execute a POST request. Takes a URL, parameters, and headers. @@ -167,7 +181,7 @@ This plugin utilizes some awesome open source networking libraries. These are b We made a few modifications to http-request. They can be found in a separate repo here: https://github.com/wymsee/http-request -## Limitations +## Current Limitations This plugin isn't equivalent to using XMLHttpRequest or Ajax calls in Javascript. For instance, the following features are currently not supported: diff --git a/package.json b/package.json new file mode 100644 index 00000000..c91b8b03 --- /dev/null +++ b/package.json @@ -0,0 +1,35 @@ +{ + "name": "cordova-plugin-http", + "version": "1.0.0", + "description": "Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning", + "cordova": { + "id": "cordova-plugin-http", + "platforms": [ + "ios", + "android" + ] + }, + "repository": { + "type": "git", + "url": "git+https://github.com/wymsee/cordova-HTTP.git" + }, + "keywords": [ + "cordova", + "device", + "ecosystem:cordova", + "cordova-ios", + "cordova-android" + ], + "engines": [ + { + "name": "cordova", + "version": ">=3.0.0" + } + ], + "author": "Wymsee", + "license": "MIT", + "bugs": { + "url": "https://github.com/wymsee/cordova-HTTP/issues" + }, + "homepage": "https://github.com/wymsee/cordova-HTTP#readme" +} diff --git a/plugin.xml b/plugin.xml index ef01acab..a1bde91b 100644 --- a/plugin.xml +++ b/plugin.xml @@ -1,8 +1,8 @@ + id="cordova-plugin-http" + version="0.2.0"> SSL Pinning @@ -14,10 +14,10 @@ - + - + @@ -31,18 +31,9 @@ - - - - - - - - - @@ -54,9 +45,6 @@ - - - @@ -78,12 +66,17 @@ + + + + + - \ No newline at end of file + diff --git a/src/android/com/synconset/CordovaHTTP/CordovaHttp.java b/src/android/com/synconset/CordovaHTTP/CordovaHttp.java index e90ad6fa..71b47097 100644 --- a/src/android/com/synconset/CordovaHTTP/CordovaHttp.java +++ b/src/android/com/synconset/CordovaHTTP/CordovaHttp.java @@ -12,6 +12,8 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; +import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; @@ -35,7 +37,8 @@ public abstract class CordovaHttp { private static AtomicBoolean sslPinning = new AtomicBoolean(false); private static AtomicBoolean acceptAllCerts = new AtomicBoolean(false); - + private static AtomicBoolean validateDomainName = new AtomicBoolean(true); + private String urlString; private Map params; private Map headers; @@ -61,7 +64,11 @@ public static void acceptAllCerts(boolean accept) { sslPinning.set(false); } } - + + public static void validateDomainName(boolean accept) { + validateDomainName.set(accept); + } + protected String getUrlString() { return this.urlString; } @@ -81,6 +88,8 @@ protected CallbackContext getCallbackContext() { protected HttpRequest setupSecurity(HttpRequest request) { if (acceptAllCerts.get()) { request.trustAllCerts(); + } + if (!validateDomainName.get()) { request.trustAllHosts(); } if (sslPinning.get()) { @@ -103,4 +112,17 @@ protected void respondWithError(int status, String msg) { protected void respondWithError(String msg) { this.respondWithError(500, msg); } + + protected void addResponseHeaders(HttpRequest request, JSONObject response) throws JSONException { + Map> headers = request.headers(); + Map parsed_headers = new HashMap(); + for (Map.Entry> entry : headers.entrySet()) { + String key = entry.getKey(); + List value = entry.getValue(); + if ((key != null) && (!value.isEmpty())) { + parsed_headers.put(key, value.get(0)); + } + } + response.put("headers", new JSONObject(parsed_headers)); + } } diff --git a/src/android/com/synconset/CordovaHTTP/CordovaHttpDownload.java b/src/android/com/synconset/CordovaHTTP/CordovaHttpDownload.java index e0461860..cd0a9d58 100644 --- a/src/android/com/synconset/CordovaHTTP/CordovaHttpDownload.java +++ b/src/android/com/synconset/CordovaHTTP/CordovaHttpDownload.java @@ -40,12 +40,13 @@ public void run() { int code = request.code(); JSONObject response = new JSONObject(); + this.addResponseHeaders(request, response); response.put("status", code); if (code >= 200 && code < 300) { URI uri = new URI(filePath); File file = new File(uri); request.receive(file); - JSONObject fileEntry = FileUtils.getEntry(file); + JSONObject fileEntry = FileUtils.getFilePlugin().getEntryForFile(file); response.put("file", fileEntry); this.getCallbackContext().success(response); } else { diff --git a/src/android/com/synconset/CordovaHTTP/CordovaHttpGet.java b/src/android/com/synconset/CordovaHTTP/CordovaHttpGet.java index 490597b6..4c3ed730 100644 --- a/src/android/com/synconset/CordovaHTTP/CordovaHttpGet.java +++ b/src/android/com/synconset/CordovaHTTP/CordovaHttpGet.java @@ -40,6 +40,7 @@ public void run() { int code = request.code(); String body = request.body(CHARSET); JSONObject response = new JSONObject(); + this.addResponseHeaders(request, response); response.put("status", code); if (code >= 200 && code < 300) { response.put("data", body); diff --git a/src/android/com/synconset/CordovaHTTP/CordovaHttpHead.java b/src/android/com/synconset/CordovaHTTP/CordovaHttpHead.java new file mode 100644 index 00000000..9be50b7b --- /dev/null +++ b/src/android/com/synconset/CordovaHTTP/CordovaHttpHead.java @@ -0,0 +1,64 @@ +/** + * A HTTP plugin for Cordova / Phonegap + */ +package com.synconset; + +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.UnknownHostException; +import java.util.Map; + +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.HostnameVerifier; + +import javax.net.ssl.SSLHandshakeException; + +import org.apache.cordova.CallbackContext; +import org.json.JSONException; +import org.json.JSONObject; + +import android.util.Log; + +import com.github.kevinsawicki.http.HttpRequest; +import com.github.kevinsawicki.http.HttpRequest.HttpRequestException; + +public class CordovaHttpHead extends CordovaHttp implements Runnable { + public CordovaHttpHead(String urlString, Map params, Map headers, CallbackContext callbackContext) { + super(urlString, params, headers, callbackContext); + } + + @Override + public void run() { + try { + HttpRequest request = HttpRequest.head(this.getUrlString(), this.getParams(), true); + this.setupSecurity(request); + request.acceptCharset(CHARSET); + request.headers(this.getHeaders()); + int code = request.code(); + JSONObject response = new JSONObject(); + this.addResponseHeaders(request, response); + response.put("status", code); + if (code >= 200 && code < 300) { + // no 'body' to return for HEAD request + this.getCallbackContext().success(response); + } else { + String body = request.body(CHARSET); + response.put("error", body); + this.getCallbackContext().error(response); + } + } catch (JSONException e) { + this.respondWithError("There was an error generating the response"); + } catch (HttpRequestException e) { + if (e.getCause() instanceof UnknownHostException) { + this.respondWithError(0, "The host could not be resolved"); + } else if (e.getCause() instanceof SSLHandshakeException) { + this.respondWithError("SSL handshake failed"); + } else { + this.respondWithError("There was an error with the request"); + } + } + } +} \ No newline at end of file diff --git a/src/android/com/synconset/CordovaHTTP/CordovaHttpPlugin.java b/src/android/com/synconset/CordovaHTTP/CordovaHttpPlugin.java index b2cf398f..7efcae94 100644 --- a/src/android/com/synconset/CordovaHTTP/CordovaHttpPlugin.java +++ b/src/android/com/synconset/CordovaHTTP/CordovaHttpPlugin.java @@ -40,12 +40,9 @@ public class CordovaHttpPlugin extends CordovaPlugin { private static final String TAG = "CordovaHTTP"; - private HashMap globalHeaders; - @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); - this.globalHeaders = new HashMap(); } @Override @@ -55,22 +52,25 @@ public boolean execute(String action, final JSONArray args, final CallbackContex JSONObject params = args.getJSONObject(1); JSONObject headers = args.getJSONObject(2); HashMap paramsMap = this.getMapFromJSONObject(params); - HashMap headersMap = this.addToMap(this.globalHeaders, headers); + HashMap headersMap = this.getStringMapFromJSONObject(headers); CordovaHttpGet get = new CordovaHttpGet(urlString, paramsMap, headersMap, callbackContext); cordova.getThreadPool().execute(get); + } else if (action.equals("head")) { + String urlString = args.getString(0); + JSONObject params = args.getJSONObject(1); + JSONObject headers = args.getJSONObject(2); + HashMap paramsMap = this.getMapFromJSONObject(params); + HashMap headersMap = this.getStringMapFromJSONObject(headers); + CordovaHttpHead head = new CordovaHttpHead(urlString, paramsMap, headersMap, callbackContext); + cordova.getThreadPool().execute(head); } else if (action.equals("post")) { String urlString = args.getString(0); JSONObject params = args.getJSONObject(1); JSONObject headers = args.getJSONObject(2); HashMap paramsMap = this.getMapFromJSONObject(params); - HashMap headersMap = this.addToMap(this.globalHeaders, headers); + HashMap headersMap = this.getStringMapFromJSONObject(headers); CordovaHttpPost post = new CordovaHttpPost(urlString, paramsMap, headersMap, callbackContext); cordova.getThreadPool().execute(post); - } else if (action.equals("useBasicAuth")) { - String username = args.getString(0); - String password = args.getString(1); - this.useBasicAuth(username, password); - callbackContext.success(); } else if (action.equals("enableSSLPinning")) { try { boolean enable = args.getBoolean(0); @@ -83,17 +83,17 @@ public boolean execute(String action, final JSONArray args, final CallbackContex } else if (action.equals("acceptAllCerts")) { boolean accept = args.getBoolean(0); CordovaHttp.acceptAllCerts(accept); - } else if (action.equals("setHeader")) { - String header = args.getString(0); - String value = args.getString(1); - this.setHeader(header, value); + callbackContext.success(); + } else if (action.equals("validateDomainName")) { + boolean accept = args.getBoolean(0); + CordovaHttp.validateDomainName(accept); callbackContext.success(); } else if (action.equals("uploadFile")) { String urlString = args.getString(0); JSONObject params = args.getJSONObject(1); JSONObject headers = args.getJSONObject(2); HashMap paramsMap = this.getMapFromJSONObject(params); - HashMap headersMap = this.addToMap(this.globalHeaders, headers); + HashMap headersMap = this.getStringMapFromJSONObject(headers); String filePath = args.getString(3); String name = args.getString(4); CordovaHttpUpload upload = new CordovaHttpUpload(urlString, paramsMap, headersMap, callbackContext, filePath, name); @@ -103,7 +103,7 @@ public boolean execute(String action, final JSONArray args, final CallbackContex JSONObject params = args.getJSONObject(1); JSONObject headers = args.getJSONObject(2); HashMap paramsMap = this.getMapFromJSONObject(params); - HashMap headersMap = this.addToMap(this.globalHeaders, headers); + HashMap headersMap = this.getStringMapFromJSONObject(headers); String filePath = args.getString(3); CordovaHttpDownload download = new CordovaHttpDownload(urlString, paramsMap, headersMap, callbackContext, filePath); cordova.getThreadPool().execute(download); @@ -113,16 +113,6 @@ public boolean execute(String action, final JSONArray args, final CallbackContex return true; } - private void useBasicAuth(String username, String password) { - String loginInfo = username + ":" + password; - loginInfo = "Basic " + Base64.encodeToString(loginInfo.getBytes(), Base64.NO_WRAP); - this.globalHeaders.put("Authorization", loginInfo); - } - - private void setHeader(String header, String value) { - this.globalHeaders.put(header, value); - } - private void enableSSLPinning(boolean enable) throws GeneralSecurityException, IOException { if (enable) { AssetManager assetManager = cordova.getActivity().getAssets(); @@ -160,15 +150,15 @@ private void enableSSLPinning(boolean enable) throws GeneralSecurityException, I } } - private HashMap addToMap(HashMap map, JSONObject object) throws JSONException { - HashMap newMap = (HashMap)map.clone(); + private HashMap getStringMapFromJSONObject(JSONObject object) throws JSONException { + HashMap map = new HashMap(); Iterator i = object.keys(); while (i.hasNext()) { String key = (String)i.next(); - newMap.put(key, object.getString(key)); + map.put(key, object.getString(key)); } - return newMap; + return map; } private HashMap getMapFromJSONObject(JSONObject object) throws JSONException { diff --git a/src/android/com/synconset/CordovaHTTP/CordovaHttpPost.java b/src/android/com/synconset/CordovaHTTP/CordovaHttpPost.java index 7e31b75b..2b8e2273 100644 --- a/src/android/com/synconset/CordovaHTTP/CordovaHttpPost.java +++ b/src/android/com/synconset/CordovaHTTP/CordovaHttpPost.java @@ -33,6 +33,7 @@ public void run() { int code = request.code(); String body = request.body(CHARSET); JSONObject response = new JSONObject(); + this.addResponseHeaders(request, response); response.put("status", code); if (code >= 200 && code < 300) { response.put("data", body); diff --git a/src/android/com/synconset/CordovaHTTP/CordovaHttpUpload.java b/src/android/com/synconset/CordovaHTTP/CordovaHttpUpload.java index 086e7ac5..2e895589 100644 --- a/src/android/com/synconset/CordovaHTTP/CordovaHttpUpload.java +++ b/src/android/com/synconset/CordovaHTTP/CordovaHttpUpload.java @@ -70,6 +70,7 @@ public void run() { String body = request.body(CHARSET); JSONObject response = new JSONObject(); + this.addResponseHeaders(request, response); response.put("status", code); if (code >= 200 && code < 300) { response.put("data", body); diff --git a/src/android/com/synconset/CordovaHTTP/HttpRequest.java b/src/android/com/synconset/CordovaHTTP/HttpRequest.java index a6e39a59..78dce7a3 100644 --- a/src/android/com/synconset/CordovaHTTP/HttpRequest.java +++ b/src/android/com/synconset/CordovaHTTP/HttpRequest.java @@ -71,6 +71,7 @@ import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; @@ -351,6 +352,32 @@ else if (queryStart < lastChar && baseUrl.charAt(lastChar) != '&') return result; } + private static StringBuilder addParam(final Object key, Object value, + final StringBuilder result) { + if (value != null && value.getClass().isArray()) + value = arrayToList(value); + + if (value instanceof Iterable) { + Iterator iterator = ((Iterable) value).iterator(); + while (iterator.hasNext()) { + result.append(key); + result.append("[]="); + Object element = iterator.next(); + if (element != null) + result.append(element); + if (iterator.hasNext()) + result.append("&"); + } + } else { + result.append(key); + result.append("="); + if (value != null) + result.append(value); + } + + return result; + } + /** * Creates {@link HttpURLConnection HTTP connections} for * {@link URL urls}. @@ -870,6 +897,36 @@ public RequestOutputStream write(final String value) throws IOException { } } + /** + * Represents array of any type as list of objects so we can easily iterate over it + * @param array of elements + * @return list with the same elements + */ + private static List arrayToList(final Object array) { + if (array instanceof Object[]) + return Arrays.asList((Object[]) array); + + List result = new ArrayList(); + // Arrays of the primitive types can't be cast to array of Object, so this: + if (array instanceof int[]) + for (int value : (int[]) array) result.add(value); + else if (array instanceof boolean[]) + for (boolean value : (boolean[]) array) result.add(value); + else if (array instanceof long[]) + for (long value : (long[]) array) result.add(value); + else if (array instanceof float[]) + for (float value : (float[]) array) result.add(value); + else if (array instanceof double[]) + for (double value : (double[]) array) result.add(value); + else if (array instanceof short[]) + for (short value : (short[]) array) result.add(value); + else if (array instanceof byte[]) + for (byte value : (byte[]) array) result.add(value); + else if (array instanceof char[]) + for (char value : (char[]) array) result.add(value); + return result; + } + /** * Encode the given URL as an ASCII {@link String} *

@@ -933,23 +990,14 @@ public static String append(final CharSequence url, final Map params) { addParamPrefix(baseUrl, result); Entry entry; - Object value; Iterator iterator = params.entrySet().iterator(); entry = (Entry) iterator.next(); - result.append(entry.getKey().toString()); - result.append('='); - value = entry.getValue(); - if (value != null) - result.append(value); + addParam(entry.getKey().toString(), entry.getValue(), result); while (iterator.hasNext()) { result.append('&'); entry = (Entry) iterator.next(); - result.append(entry.getKey().toString()); - result.append('='); - value = entry.getValue(); - if (value != null) - result.append(value); + addParam(entry.getKey().toString(), entry.getValue(), result); } return result.toString(); @@ -980,20 +1028,11 @@ public static String append(final CharSequence url, final Object... params) { addPathSeparator(baseUrl, result); addParamPrefix(baseUrl, result); - Object value; - result.append(params[0]); - result.append('='); - value = params[1]; - if (value != null) - result.append(value); + addParam(params[0], params[1], result); for (int i = 2; i < params.length; i += 2) { result.append('&'); - result.append(params[i]); - result.append('='); - value = params[i + 1]; - if (value != null) - result.append(value); + addParam(params[i], params[i + 1], result); } return result.toString(); @@ -1052,7 +1091,7 @@ public static HttpRequest get(final CharSequence baseUrl, * the name/value query parameter pairs to include as part of the * baseUrl * - * @see #append(CharSequence, String...) + * @see #append(CharSequence, Object...) * @see #encode(CharSequence) * * @return request @@ -1116,7 +1155,7 @@ public static HttpRequest post(final CharSequence baseUrl, * the name/value query parameter pairs to include as part of the * baseUrl * - * @see #append(CharSequence, String...) + * @see #append(CharSequence, Object...) * @see #encode(CharSequence) * * @return request @@ -1180,7 +1219,7 @@ public static HttpRequest put(final CharSequence baseUrl, * the name/value query parameter pairs to include as part of the * baseUrl * - * @see #append(CharSequence, String...) + * @see #append(CharSequence, Object...) * @see #encode(CharSequence) * * @return request @@ -1244,7 +1283,7 @@ public static HttpRequest delete(final CharSequence baseUrl, * the name/value query parameter pairs to include as part of the * baseUrl * - * @see #append(CharSequence, String...) + * @see #append(CharSequence, Object...) * @see #encode(CharSequence) * * @return request @@ -1308,7 +1347,7 @@ public static HttpRequest head(final CharSequence baseUrl, * the name/value query parameter pairs to include as part of the * baseUrl * - * @see #append(CharSequence, String...) + * @see #append(CharSequence, Object...) * @see #encode(CharSequence) * * @return request @@ -1388,7 +1427,7 @@ public static void maxConnections(final int maxConnections) { } /** - * Set the 'http.proxyHost' & 'https.proxyHost' properties to the given host + * Set the 'http.proxyHost' and 'https.proxyHost' properties to the given host * value. *

* This setting will apply to all requests. @@ -1401,7 +1440,7 @@ public static void proxyHost(final String host) { } /** - * Set the 'http.proxyPort' & 'https.proxyPort' properties to the given port + * Set the 'http.proxyPort' and 'https.proxyPort' properties to the given port * number. *

* This setting will apply to all requests. diff --git a/src/ios/AFNetworking/AFHTTPRequestOperation.h b/src/ios/AFNetworking/AFHTTPRequestOperation.h deleted file mode 100644 index dfa82f66..00000000 --- a/src/ios/AFNetworking/AFHTTPRequestOperation.h +++ /dev/null @@ -1,67 +0,0 @@ -// AFHTTPRequestOperation.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#import "AFURLConnectionOperation.h" - -/** - `AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request. - */ -@interface AFHTTPRequestOperation : AFURLConnectionOperation - -///------------------------------------------------ -/// @name Getting HTTP URL Connection Information -///------------------------------------------------ - -/** - The last HTTP response received by the operation's connection. - */ -@property (readonly, nonatomic, strong) NSHTTPURLResponse *response; - -/** - 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 AFHTTPResponse serializer, which uses the raw data as its response object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed. - - @warning `responseSerializer` must not be `nil`. Setting a response serializer will clear out any cached value - */ -@property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; - -/** - An object constructed by the `responseSerializer` from the response and response data. Returns `nil` unless the operation `isFinished`, has a `response`, and has `responseData` with non-zero content length. If an error occurs during serialization, `nil` will be returned, and the `error` property will be populated with the serialization error. - */ -@property (readonly, nonatomic, strong) id responseObject; - -///----------------------------------------------------------- -/// @name Setting Completion Block Success / Failure Callbacks -///----------------------------------------------------------- - -/** - Sets the `completionBlock` property with a block that executes either the specified success or failure block, depending on the state of the request on completion. If `error` returns a value, which can be caused by an unacceptable status code or content type, then `failure` is executed. Otherwise, `success` is executed. - - This method should be overridden in subclasses in order to specify the response object passed into the success block. - - @param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request. - @param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request. - */ -- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -@end diff --git a/src/ios/AFNetworking/AFHTTPRequestOperation.m b/src/ios/AFNetworking/AFHTTPRequestOperation.m deleted file mode 100644 index 1de5812c..00000000 --- a/src/ios/AFNetworking/AFHTTPRequestOperation.m +++ /dev/null @@ -1,206 +0,0 @@ -// AFHTTPRequestOperation.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFHTTPRequestOperation.h" - -static dispatch_queue_t http_request_operation_processing_queue() { - static dispatch_queue_t af_http_request_operation_processing_queue; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_http_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.http-request.processing", DISPATCH_QUEUE_CONCURRENT); - }); - - return af_http_request_operation_processing_queue; -} - -static dispatch_group_t http_request_operation_completion_group() { - static dispatch_group_t af_http_request_operation_completion_group; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_http_request_operation_completion_group = dispatch_group_create(); - }); - - return af_http_request_operation_completion_group; -} - -#pragma mark - - -@interface AFURLConnectionOperation () -@property (readwrite, nonatomic, strong) NSURLRequest *request; -@property (readwrite, nonatomic, strong) NSURLResponse *response; -@end - -@interface AFHTTPRequestOperation () -@property (readwrite, nonatomic, strong) NSHTTPURLResponse *response; -@property (readwrite, nonatomic, strong) id responseObject; -@property (readwrite, nonatomic, strong) NSError *responseSerializationError; -@property (readwrite, nonatomic, strong) NSRecursiveLock *lock; -@end - -@implementation AFHTTPRequestOperation -@dynamic lock; - -- (instancetype)initWithRequest:(NSURLRequest *)urlRequest { - self = [super initWithRequest:urlRequest]; - if (!self) { - return nil; - } - - self.responseSerializer = [AFHTTPResponseSerializer serializer]; - - return self; -} - -- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { - NSParameterAssert(responseSerializer); - - [self.lock lock]; - _responseSerializer = responseSerializer; - self.responseObject = nil; - self.responseSerializationError = nil; - [self.lock unlock]; -} - -- (id)responseObject { - [self.lock lock]; - if (!_responseObject && [self isFinished] && !self.error) { - NSError *error = nil; - self.responseObject = [self.responseSerializer responseObjectForResponse:self.response data:self.responseData error:&error]; - if (error) { - self.responseSerializationError = error; - } - } - [self.lock unlock]; - - return _responseObject; -} - -- (NSError *)error { - if (_responseSerializationError) { - return _responseSerializationError; - } else { - return [super error]; - } -} - -#pragma mark - AFHTTPRequestOperation - -- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle. -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Warc-retain-cycles" -#pragma clang diagnostic ignored "-Wgnu" - self.completionBlock = ^{ - if (self.completionGroup) { - dispatch_group_enter(self.completionGroup); - } - - dispatch_async(http_request_operation_processing_queue(), ^{ - if (self.error) { - if (failure) { - dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ - failure(self, self.error); - }); - } - } else { - id responseObject = self.responseObject; - if (self.error) { - if (failure) { - dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ - failure(self, self.error); - }); - } - } else { - if (success) { - dispatch_group_async(self.completionGroup ?: http_request_operation_completion_group(), self.completionQueue ?: dispatch_get_main_queue(), ^{ - success(self, responseObject); - }); - } - } - } - - if (self.completionGroup) { - dispatch_group_leave(self.completionGroup); - } - }); - }; -#pragma clang diagnostic pop -} - -#pragma mark - AFURLRequestOperation - -- (void)pause { - [super pause]; - - u_int64_t offset = 0; - if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) { - offset = [(NSNumber *)[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue]; - } else { - offset = [(NSData *)[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length]; - } - - NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy]; - if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) { - [mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"]; - } - [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"]; - self.request = mutableURLRequest; -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (id)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - - self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFHTTPRequestOperation *operation = [super copyWithZone:zone]; - - operation.responseSerializer = [self.responseSerializer copyWithZone:zone]; - operation.completionQueue = self.completionQueue; - operation.completionGroup = self.completionGroup; - - return operation; -} - -@end diff --git a/src/ios/AFNetworking/AFHTTPRequestOperationManager.h b/src/ios/AFNetworking/AFHTTPRequestOperationManager.h deleted file mode 100644 index 9f390294..00000000 --- a/src/ios/AFNetworking/AFHTTPRequestOperationManager.h +++ /dev/null @@ -1,308 +0,0 @@ -// AFHTTPRequestOperationManager.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#import -#import - -#if __IPHONE_OS_VERSION_MIN_REQUIRED -#import -#else -#import -#endif - -#import "AFHTTPRequestOperation.h" -#import "AFURLResponseSerialization.h" -#import "AFURLRequestSerialization.h" -#import "AFSecurityPolicy.h" -#import "AFNetworkReachabilityManager.h" - -/** - `AFHTTPRequestOperationManager` encapsulates the common patterns of communicating with a web application over HTTP, including request creation, response serialization, network reachability monitoring, and security, as well as request operation management. - - ## Subclassing Notes - - Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application. - - For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect. - - ## Methods to Override - - To change the behavior of all request operation construction for an `AFHTTPRequestOperationManager` subclass, override `HTTPRequestOperationWithRequest:success:failure`. - - ## Serialization - - Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to ``. - - Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `` - - ## URL Construction Using Relative Paths - - For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`. - - Below are a few examples of how `baseURL` and relative paths interact: - - NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]; - [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo - [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz - [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo - [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo - [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/ - [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/ - - Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash. - - ## Network Reachability Monitoring - - Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details. - - ## NSSecureCoding & NSCopying Caveats - - `AFHTTPRequestOperationManager` conforms to the `NSSecureCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however: - - - Archives and copies of HTTP clients will be initialized with an empty operation queue. - - NSSecureCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set. - */ -@interface AFHTTPRequestOperationManager : NSObject - -/** - The URL used to monitor reachability, and construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. - */ -@property (readonly, nonatomic, strong) NSURL *baseURL; - -/** - Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies. - - @warning `requestSerializer` must not be `nil`. - */ -@property (nonatomic, strong) AFHTTPRequestSerializer * requestSerializer; - -/** - Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to a JSON serializer, which serializes data from responses with a `application/json` MIME type, and falls back to the raw data object. The serializer validates the status code to be in the `2XX` range, denoting success. If the response serializer generates an error in `-responseObjectForResponse:data:error:`, the `failure` callback of the session task or request operation will be executed; otherwise, the `success` callback will be executed. - - @warning `responseSerializer` must not be `nil`. - */ -@property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; - -/** - The operation queue on which request operations are scheduled and run. - */ -@property (nonatomic, strong) NSOperationQueue *operationQueue; - -///------------------------------- -/// @name Managing URL Credentials -///------------------------------- - -/** - Whether request operations should consult the credential storage for authenticating the connection. `YES` by default. - - @see AFURLConnectionOperation -shouldUseCredentialStorage - */ -@property (nonatomic, assign) BOOL shouldUseCredentialStorage; - -/** - The credential used by request operations for authentication challenges. - - @see AFURLConnectionOperation -credential - */ -@property (nonatomic, strong) NSURLCredential *credential; - -///------------------------------- -/// @name Managing Security Policy -///------------------------------- - -/** - The security policy used by created request operations to evaluate server trust for secure connections. `AFHTTPRequestOperationManager` uses the `defaultPolicy` unless otherwise specified. - */ -@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; - -///------------------------------------ -/// @name Managing Network Reachability -///------------------------------------ - -/** - The network reachability manager. `AFHTTPRequestOperationManager` uses the `sharedManager` by default. - */ -@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; - -///------------------------------- -/// @name Managing Callback Queues -///------------------------------- - -/** - The dispatch queue for the `completionBlock` of request operations. If `NULL` (default), the main queue is used. - */ -@property (nonatomic, strong) dispatch_queue_t completionQueue; - -/** - The dispatch group for the `completionBlock` of request operations. If `NULL` (default), a private dispatch group is used. - */ -@property (nonatomic, strong) dispatch_group_t completionGroup; - -///--------------------------------------------- -/// @name Creating and Initializing HTTP Clients -///--------------------------------------------- - -/** - Creates and returns an `AFHTTPRequestOperationManager` object. - */ -+ (instancetype)manager; - -/** - Initializes an `AFHTTPRequestOperationManager` object with the specified base URL. - - This is the designated initializer. - - @param url The base URL for the HTTP client. - - @return The newly-initialized HTTP client - */ -- (instancetype)initWithBaseURL:(NSURL *)url; - -///--------------------------------------- -/// @name Managing HTTP Request Operations -///--------------------------------------- - -/** - Creates an `AFHTTPRequestOperation`, and sets the response serializers to that of the HTTP client. - - @param request The request object to be loaded asynchronously during execution of the operation. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. - @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred. - */ -- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -///--------------------------- -/// @name Making HTTP Requests -///--------------------------- - -/** - Creates and runs an `AFHTTPRequestOperation` with a `GET` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)GET:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a `HEAD` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes a single arguments: the request operation. - @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)HEAD:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a `POST` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)POST:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a multipart `POST` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)POST:(NSString *)URLString - parameters:(id)parameters - constructingBodyWithBlock:(void (^)(id formData))block - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a `PUT` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)PUT:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a `PATCH` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)PATCH:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates and runs an `AFHTTPRequestOperation` with a `DELETE` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer. - @param failure A block object to be executed when the request operation 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 request operation and the error describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (AFHTTPRequestOperation *)DELETE:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -@end - diff --git a/src/ios/AFNetworking/AFHTTPRequestOperationManager.m b/src/ios/AFNetworking/AFHTTPRequestOperationManager.m deleted file mode 100644 index 4ae72754..00000000 --- a/src/ios/AFNetworking/AFHTTPRequestOperationManager.m +++ /dev/null @@ -1,253 +0,0 @@ -// AFHTTPRequestOperationManager.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#import "AFHTTPRequestOperationManager.h" -#import "AFHTTPRequestOperation.h" - -#import -#import - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#import -#endif - -@interface AFHTTPRequestOperationManager () -@property (readwrite, nonatomic, strong) NSURL *baseURL; -@end - -@implementation AFHTTPRequestOperationManager - -+ (instancetype)manager { - return [[self alloc] initWithBaseURL:nil]; -} - -- (instancetype)init { - return [self initWithBaseURL:nil]; -} - -- (instancetype)initWithBaseURL:(NSURL *)url { - self = [super init]; - if (!self) { - return nil; - } - - // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected - if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { - url = [url URLByAppendingPathComponent:@""]; - } - - self.baseURL = url; - - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - self.responseSerializer = [AFJSONResponseSerializer serializer]; - - self.securityPolicy = [AFSecurityPolicy defaultPolicy]; - - self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; - - self.operationQueue = [[NSOperationQueue alloc] init]; - - self.shouldUseCredentialStorage = YES; - - return self; -} - -#pragma mark - - -#ifdef _SYSTEMCONFIGURATION_H -#endif - -- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { - NSParameterAssert(requestSerializer); - - _requestSerializer = requestSerializer; -} - -- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { - NSParameterAssert(responseSerializer); - - _responseSerializer = responseSerializer; -} - -#pragma mark - - -- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; - operation.responseSerializer = self.responseSerializer; - operation.shouldUseCredentialStorage = self.shouldUseCredentialStorage; - operation.credential = self.credential; - operation.securityPolicy = self.securityPolicy; - - [operation setCompletionBlockWithSuccess:success failure:failure]; - operation.completionQueue = self.completionQueue; - operation.completionGroup = self.completionGroup; - - return operation; -} - -#pragma mark - - -- (AFHTTPRequestOperation *)GET:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)HEAD:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"HEAD" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *requestOperation, __unused id responseObject) { - if (success) { - success(requestOperation); - } - } failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)POST:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)POST:(NSString *)URLString - parameters:(id)parameters - constructingBodyWithBlock:(void (^)(id formData))block - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)PUT:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"PUT" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)PATCH:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"PATCH" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -- (AFHTTPRequestOperation *)DELETE:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"DELETE" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - - [self.operationQueue addOperation:operation]; - - return operation; -} - -#pragma mark - NSObject - -- (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.operationQueue]; -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (id)initWithCoder:(NSCoder *)decoder { - NSURL *baseURL = [decoder decodeObjectForKey:NSStringFromSelector(@selector(baseURL))]; - - self = [self initWithBaseURL:baseURL]; - if (!self) { - return nil; - } - - self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; - self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))]; - [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; - [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFHTTPRequestOperationManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL]; - - HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; - HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; - - return HTTPClient; -} - -@end diff --git a/src/ios/AFNetworking/AFHTTPSessionManager.h b/src/ios/AFNetworking/AFHTTPSessionManager.h index a84fcc55..61e1042c 100644 --- a/src/ios/AFNetworking/AFHTTPSessionManager.h +++ b/src/ios/AFNetworking/AFHTTPSessionManager.h @@ -1,6 +1,5 @@ // AFHTTPSessionManager.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -21,10 +20,12 @@ // THE SOFTWARE. #import +#if !TARGET_OS_WATCH #import -#import +#endif +#import -#if __IPHONE_OS_VERSION_MIN_REQUIRED +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV #import #else #import @@ -34,27 +35,27 @@ /** `AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths. - + ## Subclassing Notes - + Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application. - + For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect. ## Methods to Override To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:completionHandler:`. - + ## Serialization - + Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to ``. - + Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `` ## URL Construction Using Relative Paths For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`. - + Below are a few examples of how `baseURL` and relative paths interact: NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]; @@ -66,20 +67,22 @@ [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/ Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash. + + @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. */ -#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) +NS_ASSUME_NONNULL_BEGIN @interface AFHTTPSessionManager : AFURLSessionManager /** - The URL used to monitor reachability, and construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. + The URL used to construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. */ -@property (readonly, nonatomic, strong) NSURL *baseURL; +@property (readonly, nonatomic, strong, nullable) NSURL *baseURL; /** Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies. - + @warning `requestSerializer` must not be `nil`. */ @property (nonatomic, strong) AFHTTPRequestSerializer * requestSerializer; @@ -102,12 +105,12 @@ /** Initializes an `AFHTTPSessionManager` object with the specified base URL. - + @param url The base URL for the HTTP client. @return The newly-initialized HTTP client */ -- (instancetype)initWithBaseURL:(NSURL *)url; +- (instancetype)initWithBaseURL:(nullable NSURL *)url; /** Initializes an `AFHTTPSessionManager` object with the specified base URL. @@ -119,8 +122,8 @@ @return The newly-initialized HTTP client */ -- (instancetype)initWithBaseURL:(NSURL *)url - sessionConfiguration:(NSURLSessionConfiguration *)configuration; +- (instancetype)initWithBaseURL:(nullable NSURL *)url + sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; ///--------------------------- /// @name Making HTTP Requests @@ -136,10 +139,28 @@ @see -dataTaskWithRequest:completionHandler: */ -- (NSURLSessionDataTask *)GET:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; +- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; + + +/** + Creates and runs an `NSURLSessionDataTask` with a `GET` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param progress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(nullable id)parameters + progress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; /** Creates and runs an `NSURLSessionDataTask` with a `HEAD` request. @@ -151,10 +172,10 @@ @see -dataTaskWithRequest:completionHandler: */ -- (NSURLSessionDataTask *)HEAD:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; +- (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; /** Creates and runs an `NSURLSessionDataTask` with a `POST` request. @@ -166,10 +187,27 @@ @see -dataTaskWithRequest:completionHandler: */ -- (NSURLSessionDataTask *)POST:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; + +/** + Creates and runs an `NSURLSessionDataTask` with a `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param progress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + progress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; /** Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. @@ -182,11 +220,30 @@ @see -dataTaskWithRequest:completionHandler: */ -- (NSURLSessionDataTask *)POST:(NSString *)URLString - parameters:(id)parameters - constructingBodyWithBlock:(void (^)(id formData))block - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; + +/** + Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. + @param progress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + progress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; /** Creates and runs an `NSURLSessionDataTask` with a `PUT` request. @@ -198,10 +255,10 @@ @see -dataTaskWithRequest:completionHandler: */ -- (NSURLSessionDataTask *)PUT:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; +- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; /** Creates and runs an `NSURLSessionDataTask` with a `PATCH` request. @@ -213,10 +270,10 @@ @see -dataTaskWithRequest:completionHandler: */ -- (NSURLSessionDataTask *)PATCH:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; +- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; /** Creates and runs an `NSURLSessionDataTask` with a `DELETE` request. @@ -228,11 +285,11 @@ @see -dataTaskWithRequest:completionHandler: */ -- (NSURLSessionDataTask *)DELETE:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure; +- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString + parameters:(nullable id)parameters + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; @end -#endif +NS_ASSUME_NONNULL_END diff --git a/src/ios/AFNetworking/AFHTTPSessionManager.m b/src/ios/AFNetworking/AFHTTPSessionManager.m index 6413297d..249631bc 100644 --- a/src/ios/AFNetworking/AFHTTPSessionManager.m +++ b/src/ios/AFNetworking/AFHTTPSessionManager.m @@ -1,6 +1,5 @@ // AFHTTPSessionManager.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -22,24 +21,23 @@ #import "AFHTTPSessionManager.h" -#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) - #import "AFURLRequestSerialization.h" #import "AFURLResponseSerialization.h" #import +#import #import -#ifdef _SYSTEMCONFIGURATION_H #import #import #import #import #import -#endif -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV #import +#elif TARGET_OS_WATCH +#import #endif @interface AFHTTPSessionManager () @@ -47,6 +45,7 @@ @interface AFHTTPSessionManager () @end @implementation AFHTTPSessionManager +@dynamic responseSerializer; + (instancetype)manager { return [[[self class] alloc] initWithBaseURL:nil]; @@ -87,9 +86,6 @@ - (instancetype)initWithBaseURL:(NSURL *)url #pragma mark - -#ifdef _SYSTEMCONFIGURATION_H -#endif - - (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { NSParameterAssert(requestSerializer); @@ -109,7 +105,24 @@ - (NSURLSessionDataTask *)GET:(NSString *)URLString success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure { - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" URLString:URLString parameters:parameters success:success failure:failure]; + + return [self GET:URLString parameters:parameters progress:nil success:success failure:failure]; +} + +- (NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(id)parameters + progress:(void (^)(NSProgress * _Nonnull))downloadProgress + success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success + failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" + URLString:URLString + parameters:parameters + uploadProgress:nil + downloadProgress:downloadProgress + success:success + failure:failure]; [dataTask resume]; @@ -121,7 +134,7 @@ - (NSURLSessionDataTask *)HEAD:(NSString *)URLString success:(void (^)(NSURLSessionDataTask *task))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure { - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters success:^(NSURLSessionDataTask *task, __unused id responseObject) { + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) { if (success) { success(task); } @@ -137,16 +150,35 @@ - (NSURLSessionDataTask *)POST:(NSString *)URLString success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure { - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters success:success failure:failure]; + return [self POST:URLString parameters:parameters progress:nil success:success failure:failure]; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(id)parameters + progress:(void (^)(NSProgress * _Nonnull))uploadProgress + success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success + failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure]; [dataTask resume]; return dataTask; } +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + constructingBodyWithBlock:(nullable void (^)(id _Nonnull))block + success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + return [self POST:URLString parameters:parameters constructingBodyWithBlock:block progress:nil success:success failure:failure]; +} + - (NSURLSessionDataTask *)POST:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(void (^)(id formData))block + progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure { @@ -165,7 +197,7 @@ - (NSURLSessionDataTask *)POST:(NSString *)URLString return nil; } - __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { + __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { if (error) { if (failure) { failure(task, error); @@ -187,7 +219,7 @@ - (NSURLSessionDataTask *)PUT:(NSString *)URLString success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure { - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters success:success failure:failure]; + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; [dataTask resume]; @@ -199,7 +231,7 @@ - (NSURLSessionDataTask *)PATCH:(NSString *)URLString success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure { - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters success:success failure:failure]; + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; [dataTask resume]; @@ -211,7 +243,7 @@ - (NSURLSessionDataTask *)DELETE:(NSString *)URLString success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure { - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters success:success failure:failure]; + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; [dataTask resume]; @@ -221,6 +253,8 @@ - (NSURLSessionDataTask *)DELETE:(NSString *)URLString - (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method URLString:(NSString *)URLString parameters:(id)parameters + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress success:(void (^)(NSURLSessionDataTask *, id))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure { @@ -240,7 +274,10 @@ - (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method } __block NSURLSessionDataTask *dataTask = nil; - dataTask = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { + dataTask = [self dataTaskWithRequest:request + uploadProgress:uploadProgress + downloadProgress:downloadProgress + completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { if (error) { if (failure) { failure(dataTask, error); @@ -267,7 +304,7 @@ + (BOOL)supportsSecureCoding { return YES; } -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))]; NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; if (!configuration) { @@ -288,6 +325,10 @@ - (id)initWithCoder:(NSCoder *)decoder { self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; + AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))]; + if (decodedPolicy) { + self.securityPolicy = decodedPolicy; + } return self; } @@ -303,19 +344,18 @@ - (void)encodeWithCoder:(NSCoder *)coder { } [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; + [coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))]; } #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration]; HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; - + HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone]; return HTTPClient; } @end - -#endif diff --git a/src/ios/AFNetworking/AFNetworkReachabilityManager.h b/src/ios/AFNetworking/AFNetworkReachabilityManager.h index 5e610d88..88d9181f 100644 --- a/src/ios/AFNetworking/AFNetworkReachabilityManager.h +++ b/src/ios/AFNetworking/AFNetworkReachabilityManager.h @@ -1,6 +1,5 @@ // AFNetworkReachabilityManager.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -8,10 +7,10 @@ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +20,8 @@ // THE SOFTWARE. #import + +#if !TARGET_OS_WATCH #import typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { @@ -30,13 +31,15 @@ typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { AFNetworkReachabilityStatusReachableViaWiFi = 2, }; +NS_ASSUME_NONNULL_BEGIN + /** `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. - + Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability. See Apple's Reachability Sample Code (https://developer.apple.com/library/ios/samplecode/reachability/) - + @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined. */ @interface AFNetworkReachabilityManager : NSObject @@ -71,10 +74,17 @@ typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { + (instancetype)sharedManager; /** - Creates and returns a network reachability manager for the specified domain. + Creates and returns a network reachability manager with the default socket address. + @return An initialized network reachability manager, actively monitoring the default socket address. + */ ++ (instancetype)manager; + +/** + Creates and returns a network reachability manager for the specified domain. + @param domain The domain used to evaluate network reachability. - + @return An initialized network reachability manager, actively monitoring the specified domain. */ + (instancetype)managerForDomain:(NSString *)domain; @@ -82,7 +92,7 @@ typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { /** Creates and returns a network reachability manager for the socket address. - @param address The socket address (`sockaddr_in`) used to evaluate network reachability. + @param address The socket address (`sockaddr_in6`) used to evaluate network reachability. @return An initialized network reachability manager, actively monitoring the specified socket address. */ @@ -90,12 +100,12 @@ typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { /** Initializes an instance of a network reachability manager from the specified reachability object. - + @param reachability The reachability object to monitor. - + @return An initialized network reachability manager, actively monitoring the specified reachability. */ -- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability; +- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER; ///-------------------------------------------------- /// @name Starting & Stopping Reachability Monitoring @@ -129,7 +139,7 @@ typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`. */ -- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block; +- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block; @end @@ -180,8 +190,8 @@ typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { @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`). */ -extern NSString * const AFNetworkingReachabilityDidChangeNotification; -extern NSString * const AFNetworkingReachabilityNotificationStatusItem; +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification; +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem; ///-------------------- /// @name Functions @@ -190,4 +200,7 @@ extern NSString * const AFNetworkingReachabilityNotificationStatusItem; /** Returns a localized string representation of an `AFNetworkReachabilityStatus` value. */ -extern NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); +FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); + +NS_ASSUME_NONNULL_END +#endif diff --git a/src/ios/AFNetworking/AFNetworkReachabilityManager.m b/src/ios/AFNetworking/AFNetworkReachabilityManager.m index 1da14828..d39b81bc 100644 --- a/src/ios/AFNetworking/AFNetworkReachabilityManager.m +++ b/src/ios/AFNetworking/AFNetworkReachabilityManager.m @@ -1,6 +1,5 @@ // AFNetworkReachabilityManager.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -8,10 +7,10 @@ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,6 +20,7 @@ // THE SOFTWARE. #import "AFNetworkReachabilityManager.h" +#if !TARGET_OS_WATCH #import #import @@ -33,12 +33,6 @@ typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status); -typedef NS_ENUM(NSUInteger, AFNetworkReachabilityAssociation) { - AFNetworkReachabilityForAddress = 1, - AFNetworkReachabilityForAddressPair = 2, - AFNetworkReachabilityForName = 3, -}; - NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) { switch (status) { case AFNetworkReachabilityStatusNotReachable: @@ -76,21 +70,31 @@ static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetwork return status; } -static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { +/** + * Queue a status change notification for the main thread. + * + * This is done to ensure that the notifications are received in the same order + * as they are sent. If notifications are sent directly, it is possible that + * a queued notification (for an earlier status condition) is processed after + * the later update, resulting in the listener being left in the wrong state. + */ +static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusBlock block) { AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); - AFNetworkReachabilityStatusBlock block = (__bridge AFNetworkReachabilityStatusBlock)info; - if (block) { - block(status); - } - - dispatch_async(dispatch_get_main_queue(), ^{ + if (block) { + block(status); + } NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:@{ AFNetworkingReachabilityNotificationStatusItem: @(status) }]; + NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) }; + [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo]; }); - } +static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { + AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusBlock)info); +} + + static const void * AFNetworkReachabilityRetainCallback(const void *info) { return Block_copy(info); } @@ -102,8 +106,7 @@ static void AFNetworkReachabilityReleaseCallback(const void *info) { } @interface AFNetworkReachabilityManager () -@property (readwrite, nonatomic, assign) SCNetworkReachabilityRef networkReachability; -@property (readwrite, nonatomic, assign) AFNetworkReachabilityAssociation networkReachabilityAssociation; +@property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability; @property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; @property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; @end @@ -114,12 +117,7 @@ + (instancetype)sharedManager { static AFNetworkReachabilityManager *_sharedManager = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - struct sockaddr_in address; - bzero(&address, sizeof(address)); - address.sin_len = sizeof(address); - address.sin_family = AF_INET; - - _sharedManager = [self managerForAddress:&address]; + _sharedManager = [self manager]; }); return _sharedManager; @@ -129,38 +127,59 @@ + (instancetype)managerForDomain:(NSString *)domain { SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; - manager.networkReachabilityAssociation = AFNetworkReachabilityForName; + + CFRelease(reachability); return manager; } + (instancetype)managerForAddress:(const void *)address { SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address); - AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; - manager.networkReachabilityAssociation = AFNetworkReachabilityForAddress; + CFRelease(reachability); + return manager; } ++ (instancetype)manager +{ +#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + struct sockaddr_in6 address; + bzero(&address, sizeof(address)); + address.sin6_len = sizeof(address); + address.sin6_family = AF_INET6; +#else + struct sockaddr_in address; + bzero(&address, sizeof(address)); + address.sin_len = sizeof(address); + address.sin_family = AF_INET; +#endif + return [self managerForAddress:&address]; +} + - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { self = [super init]; if (!self) { return nil; } - self.networkReachability = reachability; + _networkReachability = CFRetain(reachability); self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; return self; } +- (instancetype)init NS_UNAVAILABLE +{ + return nil; +} + - (void)dealloc { [self stopMonitoring]; - - if (_networkReachability) { + + if (_networkReachability != NULL) { CFRelease(_networkReachability); - _networkReachability = NULL; } } @@ -202,28 +221,12 @@ - (void)startMonitoring { SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); - switch (self.networkReachabilityAssociation) { - case AFNetworkReachabilityForName: - break; - case AFNetworkReachabilityForAddress: - case AFNetworkReachabilityForAddressPair: - default: { - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ - SCNetworkReachabilityFlags flags; - SCNetworkReachabilityGetFlags(self.networkReachability, &flags); - AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); - dispatch_async(dispatch_get_main_queue(), ^{ - callback(status); - - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:@{ AFNetworkingReachabilityNotificationStatusItem: @(status) }]; - - - }); - }); + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ + SCNetworkReachabilityFlags flags; + if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) { + AFPostReachabilityStatusChange(flags, callback); } - break; - } + }); } - (void)stopMonitoring { @@ -257,3 +260,4 @@ + (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { } @end +#endif diff --git a/src/ios/AFNetworking/AFNetworking.h b/src/ios/AFNetworking/AFNetworking.h index 68273da5..e2fb2f44 100644 --- a/src/ios/AFNetworking/AFNetworking.h +++ b/src/ios/AFNetworking/AFNetworking.h @@ -22,6 +22,7 @@ #import #import +#import #ifndef _AFNETWORKING_ #define _AFNETWORKING_ @@ -29,16 +30,12 @@ #import "AFURLRequestSerialization.h" #import "AFURLResponseSerialization.h" #import "AFSecurityPolicy.h" - #import "AFNetworkReachabilityManager.h" - #import "AFURLConnectionOperation.h" - #import "AFHTTPRequestOperation.h" - #import "AFHTTPRequestOperationManager.h" +#if !TARGET_OS_WATCH + #import "AFNetworkReachabilityManager.h" +#endif -#if ( ( defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) || \ - ( defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 ) ) #import "AFURLSessionManager.h" #import "AFHTTPSessionManager.h" -#endif #endif /* _AFNETWORKING_ */ diff --git a/src/ios/AFNetworking/AFSecurityPolicy.h b/src/ios/AFNetworking/AFSecurityPolicy.h index b86e76b4..de3ce924 100644 --- a/src/ios/AFNetworking/AFSecurityPolicy.h +++ b/src/ios/AFNetworking/AFSecurityPolicy.h @@ -1,6 +1,5 @@ -// AFSecurity.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// AFSecurityPolicy.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -31,25 +30,27 @@ typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { /** `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. - + Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled. */ -@interface AFSecurityPolicy : NSObject + +NS_ASSUME_NONNULL_BEGIN + +@interface AFSecurityPolicy : NSObject /** The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. */ -@property (nonatomic, assign) AFSSLPinningMode SSLPinningMode; +@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode; /** - Whether to evaluate an entire SSL certificate chain, or just the leaf certificate. Defaults to `YES`. - */ -@property (nonatomic, assign) BOOL validatesCertificateChain; + The certificates used to evaluate server trust according to the SSL pinning mode. -/** - The certificates used to evaluate server trust according to the SSL pinning mode. By default, this property is set to any (`.cer`) certificates included in the app bundle. + By default, this property is set to any (`.cer`) certificates included in the target compiling AFNetworking. Note that if you are using AFNetworking as embedded framework, no certificates will be pinned by default. Use `certificatesInBundle` to load certificates from your target, and then create a new policy by calling `policyWithPinningMode:withPinnedCertificates`. + + Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches. */ -@property (nonatomic, strong) NSArray *pinnedCertificates; +@property (nonatomic, strong, nullable) NSSet *pinnedCertificates; /** Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. @@ -57,17 +58,28 @@ typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { @property (nonatomic, assign) BOOL allowInvalidCertificates; /** - Whether or not to validate the domain name in the certificates CN field. Defaults to `YES` for `AFSSLPinningModePublicKey` or `AFSSLPinningModeCertificate`, otherwise `NO`. + Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`. */ @property (nonatomic, assign) BOOL validatesDomainName; +///----------------------------------------- +/// @name Getting Certificates from the Bundle +///----------------------------------------- + +/** + Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`. + + @return The certificates included in the given bundle. + */ ++ (NSSet *)certificatesInBundle:(NSBundle *)bundle; + ///----------------------------------------- /// @name Getting Specific Security Policies ///----------------------------------------- /** - Returns the shared default security policy, which does not accept invalid certificates, and does not validate against pinned certificates or public keys. - + Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys. + @return The default security policy. */ + (instancetype)defaultPolicy; @@ -78,13 +90,23 @@ typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { /** Creates and returns a security policy with the specified pinning mode. - + @param pinningMode The SSL pinning mode. - + @return A new security policy. */ + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; +/** + Creates and returns a security policy with the specified pinning mode. + + @param pinningMode The SSL pinning mode. + @param pinnedCertificates The certificates to pin against. + + @return A new security policy. + */ ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates; + ///------------------------------ /// @name Evaluating Server Trust ///------------------------------ @@ -94,29 +116,18 @@ typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { This method should be used when responding to an authentication challenge from a server. - @param serverTrust The X.509 certificate trust of the server. - - @return Whether or not to trust the server. - - @warning This method has been deprecated in favor of `-evaluateServerTrust:forDomain:`. - */ -- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust DEPRECATED_ATTRIBUTE; - -/** - Whether or not the specified server trust should be accepted, based on the security policy. - - This method should be used when responding to an authentication challenge from a server. - @param serverTrust The X.509 certificate trust of the server. @param domain The domain of serverTrust. If `nil`, the domain will not be validated. - + @return Whether or not to trust the server. */ - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust - forDomain:(NSString *)domain; + forDomain:(nullable NSString *)domain; @end +NS_ASSUME_NONNULL_END + ///---------------- /// @name Constants ///---------------- diff --git a/src/ios/AFNetworking/AFSecurityPolicy.m b/src/ios/AFNetworking/AFSecurityPolicy.m index 35703163..34a10d77 100644 --- a/src/ios/AFNetworking/AFSecurityPolicy.m +++ b/src/ios/AFNetworking/AFSecurityPolicy.m @@ -1,6 +1,5 @@ -// AFSecurity.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// AFSecurityPolicy.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -22,31 +21,13 @@ #import "AFSecurityPolicy.h" -// Equivalent of macro in , without causing compiler warning: -// "'DebugAssert' is deprecated: first deprecated in OS X 10.8" -#ifndef AF_Require - #define AF_Require(assertion, exceptionLabel) \ - do { \ - if (__builtin_expect(!(assertion), 0)) { \ - goto exceptionLabel; \ - } \ - } while (0) -#endif - -#ifndef AF_Require_noErr - #define AF_Require_noErr(errorCode, exceptionLabel) \ - do { \ - if (__builtin_expect(0 != (errorCode), 0)) { \ - goto exceptionLabel; \ - } \ - } while (0) -#endif +#import -#if !defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV static NSData * AFSecKeyGetData(SecKeyRef key) { CFDataRef data = NULL; - AF_Require_noErr(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out); + __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out); return (__bridge_transfer NSData *)data; @@ -60,7 +41,7 @@ #endif static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV return [(__bridge id)key1 isEqual:(__bridge id)key2]; #else return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)]; @@ -77,14 +58,14 @@ static id AFPublicKeyForCertificate(NSData *certificate) { SecTrustResultType result; allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); - AF_Require(allowedCertificate != NULL, _out); + __Require_Quiet(allowedCertificate != NULL, _out); allowedCertificates[0] = allowedCertificate; tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); policy = SecPolicyCreateBasicX509(); - AF_Require_noErr(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out); - AF_Require_noErr(SecTrustEvaluate(allowedTrust, &result), _out); + __Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out); + __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out); allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); @@ -111,7 +92,7 @@ static id AFPublicKeyForCertificate(NSData *certificate) { static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { BOOL isValid = NO; SecTrustResultType result; - AF_Require_noErr(SecTrustEvaluate(serverTrust, &result), _out); + __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out); isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed); @@ -142,10 +123,10 @@ static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); SecTrustRef trust; - AF_Require_noErr(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); - + __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); + SecTrustResultType result; - AF_Require_noErr(SecTrustEvaluate(trust, &result), _out); + __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out); [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; @@ -168,30 +149,37 @@ static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { #pragma mark - @interface AFSecurityPolicy() -@property (readwrite, nonatomic, strong) NSArray *pinnedPublicKeys; +@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode; +@property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys; @end @implementation AFSecurityPolicy -+ (NSArray *)defaultPinnedCertificates { - static NSArray *_defaultPinnedCertificates = nil; ++ (NSSet *)certificatesInBundle:(NSBundle *)bundle { + NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; + + NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]]; + for (NSString *path in paths) { + NSData *certificateData = [NSData dataWithContentsOfFile:path]; + [certificates addObject:certificateData]; + } + + // also add certs from www/certificates + paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"www/certificates"]; + for (NSString *path in paths) { + NSData *certificateData = [NSData dataWithContentsOfFile:path]; + [certificates addObject:certificateData]; + } + + return [NSSet setWithSet:certificates]; +} + ++ (NSSet *)defaultPinnedCertificates { + static NSSet *_defaultPinnedCertificates = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSBundle *bundle = [NSBundle bundleForClass:[self class]]; - NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; - NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]]; - for (NSString *path in paths) { - NSData *certificateData = [NSData dataWithContentsOfFile:path]; - [certificates addObject:certificateData]; - } - // also add certs from www/certificates - paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"www/certificates"]; - for (NSString *path in paths) { - NSData *certificateData = [NSData dataWithContentsOfFile:path]; - [certificates addObject:certificateData]; - } - - _defaultPinnedCertificates = [[NSArray alloc] initWithArray:certificates]; + _defaultPinnedCertificates = [self certificatesInBundle:bundle]; }); return _defaultPinnedCertificates; @@ -205,32 +193,34 @@ + (instancetype)defaultPolicy { } + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { + return [self policyWithPinningMode:pinningMode withPinnedCertificates:[self defaultPinnedCertificates]]; +} + ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates { AFSecurityPolicy *securityPolicy = [[self alloc] init]; securityPolicy.SSLPinningMode = pinningMode; - securityPolicy.validatesDomainName = YES; - [securityPolicy setPinnedCertificates:[self defaultPinnedCertificates]]; + + [securityPolicy setPinnedCertificates:pinnedCertificates]; return securityPolicy; } -- (id)init { +- (instancetype)init { self = [super init]; if (!self) { return nil; } - self.validatesCertificateChain = YES; + self.validatesDomainName = YES; return self; } -#pragma mark - - -- (void)setPinnedCertificates:(NSArray *)pinnedCertificates { +- (void)setPinnedCertificates:(NSSet *)pinnedCertificates { _pinnedCertificates = pinnedCertificates; if (self.pinnedCertificates) { - NSMutableArray *mutablePinnedPublicKeys = [NSMutableArray arrayWithCapacity:[self.pinnedCertificates count]]; + NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]]; for (NSData *certificate in self.pinnedCertificates) { id publicKey = AFPublicKeyForCertificate(certificate); if (!publicKey) { @@ -238,7 +228,7 @@ - (void)setPinnedCertificates:(NSArray *)pinnedCertificates { } [mutablePinnedPublicKeys addObject:publicKey]; } - self.pinnedPublicKeys = [NSArray arrayWithArray:mutablePinnedPublicKeys]; + self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys]; } else { self.pinnedPublicKeys = nil; } @@ -246,13 +236,22 @@ - (void)setPinnedCertificates:(NSArray *)pinnedCertificates { #pragma mark - -- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust { - return [self evaluateServerTrust:serverTrust forDomain:nil]; -} - - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust forDomain:(NSString *)domain { + if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) { + // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html + // According to the docs, you should only trust your provided certs for evaluation. + // Pinned certificates are added to the trust. Without pinned certificates, + // there is nothing to evaluate against. + // + // From Apple Docs: + // "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors). + // Instead, add your own (self-signed) CA certificate to the list of trusted anchors." + NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning."); + return NO; + } + NSMutableArray *policies = [NSMutableArray array]; if (self.validatesDomainName) { [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)]; @@ -262,14 +261,16 @@ - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies); - if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) { + if (self.SSLPinningMode == AFSSLPinningModeNone) { + return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust); + } else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) { return NO; } - NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); switch (self.SSLPinningMode) { case AFSSLPinningModeNone: - return YES; + default: + return NO; case AFSSLPinningModeCertificate: { NSMutableArray *pinnedCertificates = [NSMutableArray array]; for (NSData *certificateData in self.pinnedCertificates) { @@ -281,25 +282,20 @@ - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust return NO; } - if (!self.validatesCertificateChain) { - return YES; - } - - NSUInteger trustedCertificateCount = 0; - for (NSData *trustChainCertificate in serverCertificates) { + // obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA) + NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); + + for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) { if ([self.pinnedCertificates containsObject:trustChainCertificate]) { - trustedCertificateCount++; + return YES; } } - - return trustedCertificateCount == [serverCertificates count]; + + return NO; } case AFSSLPinningModePublicKey: { NSUInteger trustedPublicKeyCount = 0; NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust); - if (!self.validatesCertificateChain && [publicKeys count] > 0) { - publicKeys = @[[publicKeys firstObject]]; - } for (id trustChainPublicKey in publicKeys) { for (id pinnedPublicKey in self.pinnedPublicKeys) { @@ -308,8 +304,7 @@ - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust } } } - - return trustedPublicKeyCount > 0 && ((self.validatesCertificateChain && trustedPublicKeyCount == [serverCertificates count]) || (!self.validatesCertificateChain && trustedPublicKeyCount >= 1)); + return trustedPublicKeyCount > 0; } } @@ -322,4 +317,44 @@ + (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys { return [NSSet setWithObject:@"pinnedCertificates"]; } +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + + self = [self init]; + if (!self) { + return nil; + } + + self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue]; + self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; + self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))]; + self.pinnedCertificates = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(pinnedCertificates))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))]; + [coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; + [coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))]; + [coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init]; + securityPolicy.SSLPinningMode = self.SSLPinningMode; + securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates; + securityPolicy.validatesDomainName = self.validatesDomainName; + securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone]; + + return securityPolicy; +} + @end diff --git a/src/ios/AFNetworking/AFURLConnectionOperation.h b/src/ios/AFNetworking/AFURLConnectionOperation.h deleted file mode 100644 index 85435564..00000000 --- a/src/ios/AFNetworking/AFURLConnectionOperation.h +++ /dev/null @@ -1,328 +0,0 @@ -// AFURLConnectionOperation.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#import -#import "AFURLRequestSerialization.h" -#import "AFURLResponseSerialization.h" -#import "AFSecurityPolicy.h" - -/** - `AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods. - - ## Subclassing Notes - - This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors. - - If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes. - - ## NSURLConnection Delegate Methods - - `AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods: - - - `connection:didReceiveResponse:` - - `connection:didReceiveData:` - - `connectionDidFinishLoading:` - - `connection:didFailWithError:` - - `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:` - - `connection:willCacheResponse:` - - `connectionShouldUseCredentialStorage:` - - `connection:needNewBodyStream:` - - `connection:willSendRequestForAuthenticationChallenge:` - - If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. - - ## Callbacks and Completion Blocks - - The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this. - - Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/). - - ## SSL Pinning - - Relying on the CA trust model to validate SSL certificates exposes your app to security vulnerabilities, such as man-in-the-middle attacks. For applications that connect to known servers, SSL certificate pinning provides an increased level of security, by checking server certificate validity against those specified in the app bundle. - - SSL with certificate pinning is strongly recommended for any application that transmits sensitive information to an external webservice. - - Connections will be validated on all matching certificates with a `.cer` extension in the bundle root. - - ## App Extensions - - When using AFNetworking in an App Extension, `#define AF_APP_EXTENSIONS` to avoid using unavailable APIs. - - ## NSCoding & NSCopying Conformance - - `AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind: - - ### NSCoding Caveats - - - Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`. - - Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged. - - ### NSCopying Caveats - - - `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations. - - A copy of an operation will not include the `outputStream` of the original. - - Operation copies do not include `completionBlock`, as it often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied. - */ - -@interface AFURLConnectionOperation : NSOperation - -///------------------------------- -/// @name Accessing Run Loop Modes -///------------------------------- - -/** - The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`. - */ -@property (nonatomic, strong) NSSet *runLoopModes; - -///----------------------------------------- -/// @name Getting URL Connection Information -///----------------------------------------- - -/** - The request used by the operation's connection. - */ -@property (readonly, nonatomic, strong) NSURLRequest *request; - -/** - The last response received by the operation's connection. - */ -@property (readonly, nonatomic, strong) NSURLResponse *response; - -/** - The error, if any, that occurred in the lifecycle of the request. - */ -@property (readonly, nonatomic, strong) NSError *error; - -///---------------------------- -/// @name Getting Response Data -///---------------------------- - -/** - The data received during the request. - */ -@property (readonly, nonatomic, strong) NSData *responseData; - -/** - The string representation of the response data. - */ -@property (readonly, nonatomic, copy) NSString *responseString; - -/** - The string encoding of the response. - - If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`. - */ -@property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding; - -///------------------------------- -/// @name Managing URL Credentials -///------------------------------- - -/** - Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default. - - This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`. - */ -@property (nonatomic, assign) BOOL shouldUseCredentialStorage; - -/** - The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. - - This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. - */ -@property (nonatomic, strong) NSURLCredential *credential; - -///------------------------------- -/// @name Managing Security Policy -///------------------------------- - -/** - The security policy used to evaluate server trust for secure connections. - */ -@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; - -///------------------------ -/// @name Accessing Streams -///------------------------ - -/** - The input stream used to read data to be sent during the request. - - This property acts as a proxy to the `HTTPBodyStream` property of `request`. - */ -@property (nonatomic, strong) NSInputStream *inputStream; - -/** - The output stream that is used to write data received until the request is finished. - - By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request, with the intermediary `outputStream` property set to `nil`. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set. - */ -@property (nonatomic, strong) NSOutputStream *outputStream; - -///--------------------------------- -/// @name Managing Callback Queues -///--------------------------------- - -/** - The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. - */ -@property (nonatomic, strong) dispatch_queue_t completionQueue; - -/** - The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. - */ -@property (nonatomic, strong) dispatch_group_t completionGroup; - -///--------------------------------------------- -/// @name Managing Request Operation Information -///--------------------------------------------- - -/** - The user info dictionary for the receiver. - */ -@property (nonatomic, strong) NSDictionary *userInfo; - -///------------------------------------------------------ -/// @name Initializing an AFURLConnectionOperation Object -///------------------------------------------------------ - -/** - Initializes and returns a newly allocated operation object with a url connection configured with the specified url request. - - This is the designated initializer. - - @param urlRequest The request object to be used by the operation connection. - */ -- (instancetype)initWithRequest:(NSURLRequest *)urlRequest; - -///---------------------------------- -/// @name Pausing / Resuming Requests -///---------------------------------- - -/** - Pauses the execution of the request operation. - - A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect. - */ -- (void)pause; - -/** - Whether the request operation is currently paused. - - @return `YES` if the operation is currently paused, otherwise `NO`. - */ -- (BOOL)isPaused; - -/** - Resumes the execution of the paused request operation. - - Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request. - */ -- (void)resume; - -///---------------------------------------------- -/// @name Configuring Backgrounding Task Behavior -///---------------------------------------------- - -/** - Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task. - - @param handler A handler to be called shortly before the application’s remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified. - */ -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS) -- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler; -#endif - -///--------------------------------- -/// @name Setting Progress Callbacks -///--------------------------------- - -/** - Sets a callback to be called when an undetermined number of bytes have been uploaded to the server. - - @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 three arguments: the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread. - */ -- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block; - -/** - Sets a callback to be called when an undetermined number of bytes have been downloaded from the server. - - @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 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 main thread. - */ -- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block; - -///------------------------------------------------- -/// @name Setting NSURLConnection Delegate Callbacks -///------------------------------------------------- - -/** - Sets a block to be executed when the connection will authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequestForAuthenticationChallenge:`. - - @param block A block object to be executed when the connection will authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated. This block must invoke one of the challenge-responder methods (NSURLAuthenticationChallengeSender protocol). - - If `allowsInvalidSSLCertificate` is set to YES, `connection:willSendRequestForAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates. - */ -- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block; - -/** - Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDataDelegate` method `connection:willSendRequest:redirectResponse:`. - - @param block A block object to be executed when the request URL was changed. The block returns an `NSURLRequest` object, the URL request to redirect, and takes three arguments: the URL connection object, the the proposed redirected request, and the URL response that caused the redirect. - */ -- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block; - - -/** - Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`. - - @param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request. - */ -- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block; - -/// - -/** - - */ -+ (NSArray *)batchOfRequestOperations:(NSArray *)operations - progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock - completionBlock:(void (^)(NSArray *operations))completionBlock; - -@end - -///-------------------- -/// @name Notifications -///-------------------- - -/** - Posted when an operation begins executing. - */ -extern NSString * const AFNetworkingOperationDidStartNotification; - -/** - Posted when an operation finishes. - */ -extern NSString * const AFNetworkingOperationDidFinishNotification; diff --git a/src/ios/AFNetworking/AFURLConnectionOperation.m b/src/ios/AFNetworking/AFURLConnectionOperation.m deleted file mode 100644 index d8b55e3e..00000000 --- a/src/ios/AFNetworking/AFURLConnectionOperation.m +++ /dev/null @@ -1,786 +0,0 @@ -// AFURLConnectionOperation.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFURLConnectionOperation.h" - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#import -#endif - -#if !__has_feature(objc_arc) -#error AFNetworking must be built with ARC. -// You can turn on ARC for only AFNetworking files by adding -fobjc-arc to the build phase for each of its files. -#endif - -typedef NS_ENUM(NSInteger, AFOperationState) { - AFOperationPausedState = -1, - AFOperationReadyState = 1, - AFOperationExecutingState = 2, - AFOperationFinishedState = 3, -}; - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS) -typedef UIBackgroundTaskIdentifier AFBackgroundTaskIdentifier; -#else -typedef id AFBackgroundTaskIdentifier; -#endif - -static dispatch_group_t url_request_operation_completion_group() { - static dispatch_group_t af_url_request_operation_completion_group; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_url_request_operation_completion_group = dispatch_group_create(); - }); - - return af_url_request_operation_completion_group; -} - -static dispatch_queue_t url_request_operation_completion_queue() { - static dispatch_queue_t af_url_request_operation_completion_queue; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_url_request_operation_completion_queue = dispatch_queue_create("com.alamofire.networking.operation.queue", DISPATCH_QUEUE_CONCURRENT ); - }); - - return af_url_request_operation_completion_queue; -} - -static NSString * const kAFNetworkingLockName = @"com.alamofire.networking.operation.lock"; - -NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start"; -NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish"; - -typedef void (^AFURLConnectionOperationProgressBlock)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected); -typedef void (^AFURLConnectionOperationAuthenticationChallengeBlock)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge); -typedef NSCachedURLResponse * (^AFURLConnectionOperationCacheResponseBlock)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse); -typedef NSURLRequest * (^AFURLConnectionOperationRedirectResponseBlock)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse); - -static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { - switch (state) { - case AFOperationReadyState: - return @"isReady"; - case AFOperationExecutingState: - return @"isExecuting"; - case AFOperationFinishedState: - return @"isFinished"; - case AFOperationPausedState: - return @"isPaused"; - default: { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunreachable-code" - return @"state"; -#pragma clang diagnostic pop - } - } -} - -static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperationState toState, BOOL isCancelled) { - switch (fromState) { - case AFOperationReadyState: - switch (toState) { - case AFOperationPausedState: - case AFOperationExecutingState: - return YES; - case AFOperationFinishedState: - return isCancelled; - default: - return NO; - } - case AFOperationExecutingState: - switch (toState) { - case AFOperationPausedState: - case AFOperationFinishedState: - return YES; - default: - return NO; - } - case AFOperationFinishedState: - return NO; - case AFOperationPausedState: - return toState == AFOperationReadyState; - default: { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunreachable-code" - switch (toState) { - case AFOperationPausedState: - case AFOperationReadyState: - case AFOperationExecutingState: - case AFOperationFinishedState: - return YES; - default: - return NO; - } - } -#pragma clang diagnostic pop - } -} - -@interface AFURLConnectionOperation () -@property (readwrite, nonatomic, assign) AFOperationState state; -@property (readwrite, nonatomic, strong) NSRecursiveLock *lock; -@property (readwrite, nonatomic, strong) NSURLConnection *connection; -@property (readwrite, nonatomic, strong) NSURLRequest *request; -@property (readwrite, nonatomic, strong) NSURLResponse *response; -@property (readwrite, nonatomic, strong) NSError *error; -@property (readwrite, nonatomic, strong) NSData *responseData; -@property (readwrite, nonatomic, copy) NSString *responseString; -@property (readwrite, nonatomic, assign) NSStringEncoding responseStringEncoding; -@property (readwrite, nonatomic, assign) long long totalBytesRead; -@property (readwrite, nonatomic, assign) AFBackgroundTaskIdentifier backgroundTaskIdentifier; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationAuthenticationChallengeBlock authenticationChallenge; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationCacheResponseBlock cacheResponse; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationRedirectResponseBlock redirectResponse; - -- (void)operationDidStart; -- (void)finish; -- (void)cancelConnection; -@end - -@implementation AFURLConnectionOperation -@synthesize outputStream = _outputStream; - -+ (void)networkRequestThreadEntryPoint:(id)__unused object { - @autoreleasepool { - [[NSThread currentThread] setName:@"AFNetworking"]; - - NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; - [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; - [runLoop run]; - } -} - -+ (NSThread *)networkRequestThread { - static NSThread *_networkRequestThread = nil; - static dispatch_once_t oncePredicate; - dispatch_once(&oncePredicate, ^{ - _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil]; - [_networkRequestThread start]; - }); - - return _networkRequestThread; -} - -- (instancetype)initWithRequest:(NSURLRequest *)urlRequest { - NSParameterAssert(urlRequest); - - self = [super init]; - if (!self) { - return nil; - } - - _state = AFOperationReadyState; - - self.lock = [[NSRecursiveLock alloc] init]; - self.lock.name = kAFNetworkingLockName; - - self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes]; - - self.request = urlRequest; - - self.shouldUseCredentialStorage = YES; - - self.securityPolicy = [AFSecurityPolicy defaultPolicy]; - - return self; -} - -- (void)dealloc { - if (_outputStream) { - [_outputStream close]; - _outputStream = nil; - } - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS) - if (_backgroundTaskIdentifier) { - [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier]; - _backgroundTaskIdentifier = UIBackgroundTaskInvalid; - } -#endif -} - -#pragma mark - - -- (void)setResponseData:(NSData *)responseData { - [self.lock lock]; - if (!responseData) { - _responseData = nil; - } else { - _responseData = [NSData dataWithBytes:responseData.bytes length:responseData.length]; - } - [self.lock unlock]; -} - -- (NSString *)responseString { - [self.lock lock]; - if (!_responseString && self.response && self.responseData) { - self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding]; - } - [self.lock unlock]; - - return _responseString; -} - -- (NSStringEncoding)responseStringEncoding { - [self.lock lock]; - if (!_responseStringEncoding && self.response) { - NSStringEncoding stringEncoding = NSUTF8StringEncoding; - if (self.response.textEncodingName) { - CFStringEncoding IANAEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)self.response.textEncodingName); - if (IANAEncoding != kCFStringEncodingInvalidId) { - stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding); - } - } - - self.responseStringEncoding = stringEncoding; - } - [self.lock unlock]; - - return _responseStringEncoding; -} - -- (NSInputStream *)inputStream { - return self.request.HTTPBodyStream; -} - -- (void)setInputStream:(NSInputStream *)inputStream { - NSMutableURLRequest *mutableRequest = [self.request mutableCopy]; - mutableRequest.HTTPBodyStream = inputStream; - self.request = mutableRequest; -} - -- (NSOutputStream *)outputStream { - if (!_outputStream) { - self.outputStream = [NSOutputStream outputStreamToMemory]; - } - - return _outputStream; -} - -- (void)setOutputStream:(NSOutputStream *)outputStream { - [self.lock lock]; - if (outputStream != _outputStream) { - if (_outputStream) { - [_outputStream close]; - } - - _outputStream = outputStream; - } - [self.lock unlock]; -} - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && !defined(AF_APP_EXTENSIONS) -- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler { - [self.lock lock]; - if (!self.backgroundTaskIdentifier) { - UIApplication *application = [UIApplication sharedApplication]; - __weak __typeof(self)weakSelf = self; - self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{ - __strong __typeof(weakSelf)strongSelf = weakSelf; - - if (handler) { - handler(); - } - - if (strongSelf) { - [strongSelf cancel]; - - [application endBackgroundTask:strongSelf.backgroundTaskIdentifier]; - strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid; - } - }]; - } - [self.lock unlock]; -} -#endif - -#pragma mark - - -- (void)setState:(AFOperationState)state { - if (!AFStateTransitionIsValid(self.state, state, [self isCancelled])) { - return; - } - - [self.lock lock]; - NSString *oldStateKey = AFKeyPathFromOperationState(self.state); - NSString *newStateKey = AFKeyPathFromOperationState(state); - - [self willChangeValueForKey:newStateKey]; - [self willChangeValueForKey:oldStateKey]; - _state = state; - [self didChangeValueForKey:oldStateKey]; - [self didChangeValueForKey:newStateKey]; - [self.lock unlock]; -} - -- (void)pause { - if ([self isPaused] || [self isFinished] || [self isCancelled]) { - return; - } - - [self.lock lock]; - if ([self isExecuting]) { - [self performSelector:@selector(operationDidPause) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; - - dispatch_async(dispatch_get_main_queue(), ^{ - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - [notificationCenter postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; - }); - } - - self.state = AFOperationPausedState; - [self.lock unlock]; -} - -- (void)operationDidPause { - [self.lock lock]; - [self.connection cancel]; - [self.lock unlock]; -} - -- (BOOL)isPaused { - return self.state == AFOperationPausedState; -} - -- (void)resume { - if (![self isPaused]) { - return; - } - - [self.lock lock]; - self.state = AFOperationReadyState; - - [self start]; - [self.lock unlock]; -} - -#pragma mark - - -- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block { - self.uploadProgress = block; -} - -- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block { - self.downloadProgress = block; -} - -- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block { - self.authenticationChallenge = block; -} - -- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block { - self.cacheResponse = block; -} - -- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block { - self.redirectResponse = block; -} - -#pragma mark - NSOperation - -- (void)setCompletionBlock:(void (^)(void))block { - [self.lock lock]; - if (!block) { - [super setCompletionBlock:nil]; - } else { - __weak __typeof(self)weakSelf = self; - [super setCompletionBlock:^ { - __strong __typeof(weakSelf)strongSelf = weakSelf; - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - dispatch_group_t group = strongSelf.completionGroup ?: url_request_operation_completion_group(); - dispatch_queue_t queue = strongSelf.completionQueue ?: dispatch_get_main_queue(); -#pragma clang diagnostic pop - - dispatch_group_async(group, queue, ^{ - block(); - }); - - dispatch_group_notify(group, url_request_operation_completion_queue(), ^{ - [strongSelf setCompletionBlock:nil]; - }); - }]; - } - [self.lock unlock]; -} - -- (BOOL)isReady { - return self.state == AFOperationReadyState && [super isReady]; -} - -- (BOOL)isExecuting { - return self.state == AFOperationExecutingState; -} - -- (BOOL)isFinished { - return self.state == AFOperationFinishedState; -} - -- (BOOL)isConcurrent { - return YES; -} - -- (void)start { - [self.lock lock]; - if ([self isCancelled]) { - [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; - } else if ([self isReady]) { - self.state = AFOperationExecutingState; - - [self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; - } - [self.lock unlock]; -} - -- (void)operationDidStart { - [self.lock lock]; - if (![self isCancelled]) { - self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; - - NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; - for (NSString *runLoopMode in self.runLoopModes) { - [self.connection scheduleInRunLoop:runLoop forMode:runLoopMode]; - [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode]; - } - - [self.outputStream open]; - [self.connection start]; - } - [self.lock unlock]; - - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self]; - }); -} - -- (void)finish { - [self.lock lock]; - self.state = AFOperationFinishedState; - [self.lock unlock]; - - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; - }); -} - -- (void)cancel { - [self.lock lock]; - if (![self isFinished] && ![self isCancelled]) { - [super cancel]; - - if ([self isExecuting]) { - [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; - } - } - [self.lock unlock]; -} - -- (void)cancelConnection { - NSDictionary *userInfo = nil; - if ([self.request URL]) { - userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; - } - NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; - - if (![self isFinished]) { - if (self.connection) { - [self.connection cancel]; - [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:error]; - } else { - // Accomodate race condition where `self.connection` has not yet been set before cancellation - self.error = error; - [self finish]; - } - } -} - -#pragma mark - - -+ (NSArray *)batchOfRequestOperations:(NSArray *)operations - progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock - completionBlock:(void (^)(NSArray *operations))completionBlock -{ - if (!operations || [operations count] == 0) { - return @[[NSBlockOperation blockOperationWithBlock:^{ - dispatch_async(dispatch_get_main_queue(), ^{ - if (completionBlock) { - completionBlock(@[]); - } - }); - }]]; - } - - __block dispatch_group_t group = dispatch_group_create(); - NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{ - dispatch_group_notify(group, dispatch_get_main_queue(), ^{ - if (completionBlock) { - completionBlock(operations); - } - }); - }]; - - for (AFURLConnectionOperation *operation in operations) { - operation.completionGroup = group; - void (^originalCompletionBlock)(void) = [operation.completionBlock copy]; - __weak __typeof(operation)weakOperation = operation; - operation.completionBlock = ^{ - __strong __typeof(weakOperation)strongOperation = weakOperation; -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - dispatch_queue_t queue = strongOperation.completionQueue ?: dispatch_get_main_queue(); -#pragma clang diagnostic pop - dispatch_group_async(group, queue, ^{ - if (originalCompletionBlock) { - originalCompletionBlock(); - } - - NSUInteger numberOfFinishedOperations = [[operations indexesOfObjectsPassingTest:^BOOL(id op, NSUInteger __unused idx, BOOL __unused *stop) { - return [op isFinished]; - }] count]; - - if (progressBlock) { - progressBlock(numberOfFinishedOperations, [operations count]); - } - - dispatch_group_leave(group); - }); - }; - - dispatch_group_enter(group); - [batchedOperation addDependency:operation]; - } - - return [operations arrayByAddingObject:batchedOperation]; -} - -#pragma mark - NSObject - -- (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p, state: %@, cancelled: %@ request: %@, response: %@>", NSStringFromClass([self class]), self, AFKeyPathFromOperationState(self.state), ([self isCancelled] ? @"YES" : @"NO"), self.request, self.response]; -} - -#pragma mark - NSURLConnectionDelegate - -- (void)connection:(NSURLConnection *)connection -willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge -{ - if (self.authenticationChallenge) { - self.authenticationChallenge(connection, challenge); - return; - } - - if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { - if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { - NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; - [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; - } else { - [[challenge sender] cancelAuthenticationChallenge:challenge]; - } - } else { - if ([challenge previousFailureCount] == 0) { - if (self.credential) { - [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge]; - } else { - [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; - } - } else { - [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; - } - } -} - -- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection { - return self.shouldUseCredentialStorage; -} - -- (NSURLRequest *)connection:(NSURLConnection *)connection - willSendRequest:(NSURLRequest *)request - redirectResponse:(NSURLResponse *)redirectResponse -{ - if (self.redirectResponse) { - return self.redirectResponse(connection, request, redirectResponse); - } else { - return request; - } -} - -- (void)connection:(NSURLConnection __unused *)connection - didSendBodyData:(NSInteger)bytesWritten - totalBytesWritten:(NSInteger)totalBytesWritten -totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite -{ - dispatch_async(dispatch_get_main_queue(), ^{ - if (self.uploadProgress) { - self.uploadProgress((NSUInteger)bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); - } - }); -} - -- (void)connection:(NSURLConnection __unused *)connection -didReceiveResponse:(NSURLResponse *)response -{ - self.response = response; -} - -- (void)connection:(NSURLConnection __unused *)connection - didReceiveData:(NSData *)data -{ - NSUInteger length = [data length]; - while (YES) { - NSInteger totalNumberOfBytesWritten = 0; - if ([self.outputStream hasSpaceAvailable]) { - const uint8_t *dataBuffer = (uint8_t *)[data bytes]; - - NSInteger numberOfBytesWritten = 0; - while (totalNumberOfBytesWritten < (NSInteger)length) { - numberOfBytesWritten = [self.outputStream write:&dataBuffer[(NSUInteger)totalNumberOfBytesWritten] maxLength:(length - (NSUInteger)totalNumberOfBytesWritten)]; - if (numberOfBytesWritten == -1) { - break; - } - - totalNumberOfBytesWritten += numberOfBytesWritten; - } - - break; - } - - if (self.outputStream.streamError) { - [self.connection cancel]; - [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.outputStream.streamError]; - return; - } - } - - dispatch_async(dispatch_get_main_queue(), ^{ - self.totalBytesRead += (long long)length; - - if (self.downloadProgress) { - self.downloadProgress(length, self.totalBytesRead, self.response.expectedContentLength); - } - }); -} - -- (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection { - self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; - - [self.outputStream close]; - if (self.responseData) { - self.outputStream = nil; - } - - self.connection = nil; - - [self finish]; -} - -- (void)connection:(NSURLConnection __unused *)connection - didFailWithError:(NSError *)error -{ - self.error = error; - - [self.outputStream close]; - if (self.responseData) { - self.outputStream = nil; - } - - self.connection = nil; - - [self finish]; -} - -- (NSCachedURLResponse *)connection:(NSURLConnection *)connection - willCacheResponse:(NSCachedURLResponse *)cachedResponse -{ - if (self.cacheResponse) { - return self.cacheResponse(connection, cachedResponse); - } else { - if ([self isCancelled]) { - return nil; - } - - return cachedResponse; - } -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (id)initWithCoder:(NSCoder *)decoder { - NSURLRequest *request = [decoder decodeObjectOfClass:[NSURLRequest class] forKey:NSStringFromSelector(@selector(request))]; - - self = [self initWithRequest:request]; - if (!self) { - return nil; - } - - self.state = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(state))] integerValue]; - self.response = [decoder decodeObjectOfClass:[NSHTTPURLResponse class] forKey:NSStringFromSelector(@selector(response))]; - self.error = [decoder decodeObjectOfClass:[NSError class] forKey:NSStringFromSelector(@selector(error))]; - self.responseData = [decoder decodeObjectOfClass:[NSData class] forKey:NSStringFromSelector(@selector(responseData))]; - self.totalBytesRead = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(totalBytesRead))] longLongValue]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [self pause]; - - [coder encodeObject:self.request forKey:NSStringFromSelector(@selector(request))]; - - switch (self.state) { - case AFOperationExecutingState: - case AFOperationPausedState: - [coder encodeInteger:AFOperationReadyState forKey:NSStringFromSelector(@selector(state))]; - break; - default: - [coder encodeInteger:self.state forKey:NSStringFromSelector(@selector(state))]; - break; - } - - [coder encodeObject:self.response forKey:NSStringFromSelector(@selector(response))]; - [coder encodeObject:self.error forKey:NSStringFromSelector(@selector(error))]; - [coder encodeObject:self.responseData forKey:NSStringFromSelector(@selector(responseData))]; - [coder encodeInt64:self.totalBytesRead forKey:NSStringFromSelector(@selector(totalBytesRead))]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFURLConnectionOperation *operation = [(AFURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request]; - - operation.uploadProgress = self.uploadProgress; - operation.downloadProgress = self.downloadProgress; - operation.authenticationChallenge = self.authenticationChallenge; - operation.cacheResponse = self.cacheResponse; - operation.redirectResponse = self.redirectResponse; - operation.completionQueue = self.completionQueue; - operation.completionGroup = self.completionGroup; - - return operation; -} - -@end diff --git a/src/ios/AFNetworking/AFURLRequestSerialization.h b/src/ios/AFNetworking/AFURLRequestSerialization.h index 17a4e496..a6f179bf 100644 --- a/src/ios/AFNetworking/AFURLRequestSerialization.h +++ b/src/ios/AFNetworking/AFURLRequestSerialization.h @@ -1,6 +1,5 @@ -// AFSerialization.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// AFURLRequestSerialization.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -8,10 +7,10 @@ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,10 +20,41 @@ // THE SOFTWARE. #import -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#import + +#if TARGET_OS_IOS || TARGET_OS_TV #import +#elif TARGET_OS_WATCH +#import #endif +NS_ASSUME_NONNULL_BEGIN + +/** + Returns a percent-escaped string following RFC 3986 for a query string key or value. + RFC 3986 states that the following characters are "reserved" characters. + - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + should be percent-escaped in the query string. + + @param string The string to be percent-escaped. + + @return The percent-escaped string. + */ +FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string); + +/** + A helper method to generate encoded url query parameters for appending to the end of a URL. + + @param parameters A dictionary of key/values to be encoded. + + @return A url encoded query string + */ +FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters); + /** The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary. @@ -41,9 +71,9 @@ @return A serialized request. */ -- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request - withParameters:(id)parameters - error:(NSError * __autoreleasing *)error; +- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(nullable id)parameters + error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; @end @@ -72,42 +102,42 @@ typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) { /** Whether created requests can use the device’s cellular radio (if present). `YES` by default. - + @see NSMutableURLRequest -setAllowsCellularAccess: */ @property (nonatomic, assign) BOOL allowsCellularAccess; /** The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default. - + @see NSMutableURLRequest -setCachePolicy: */ @property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy; /** Whether created requests should use the default cookie handling. `YES` by default. - + @see NSMutableURLRequest -setHTTPShouldHandleCookies: */ @property (nonatomic, assign) BOOL HTTPShouldHandleCookies; /** Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default - + @see NSMutableURLRequest -setHTTPShouldUsePipelining: */ @property (nonatomic, assign) BOOL HTTPShouldUsePipelining; /** The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default. - + @see NSMutableURLRequest -setNetworkServiceType: */ @property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType; /** The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds. - + @see NSMutableURLRequest -setTimeoutInterval: */ @property (nonatomic, assign) NSTimeInterval timeoutInterval; @@ -117,9 +147,14 @@ typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) { ///--------------------------------------- /** - Default HTTP header field values to be applied to serialized requests. + Default HTTP header field values to be applied to serialized requests. By default, these include the following: + + - `Accept-Language` with the contents of `NSLocale +preferredLanguages` + - `User-Agent` with the contents of various bundle identifiers and OS designations + + @discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`. */ -@property (readonly, nonatomic, strong) NSDictionary *HTTPRequestHeaders; +@property (readonly, nonatomic, strong) NSDictionary *HTTPRequestHeaders; /** Creates and returns a serializer with default configuration. @@ -132,17 +167,17 @@ typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) { @param field The HTTP header to set a default value for @param value The value set as default for the specified header, or `nil` */ -- (void)setValue:(NSString *)value +- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(NSString *)field; /** Returns the value for the HTTP headers set in the request serializer. @param field The HTTP header to retrieve the default value for - + @return The value set as default for the specified header, or `nil` */ -- (NSString *)valueForHTTPHeaderField:(NSString *)field; +- (nullable NSString *)valueForHTTPHeaderField:(NSString *)field; /** Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header. @@ -153,12 +188,6 @@ forHTTPHeaderField:(NSString *)field; - (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username password:(NSString *)password; -/** - @deprecated This method has been deprecated. Use -setValue:forHTTPHeaderField: instead. - */ -- (void)setAuthorizationHeaderFieldWithToken:(NSString *)token DEPRECATED_ATTRIBUTE; - - /** Clears any existing value for the "Authorization" HTTP header. */ @@ -171,7 +200,7 @@ forHTTPHeaderField:(NSString *)field; /** HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default. */ -@property (nonatomic, strong) NSSet *HTTPMethodsEncodingParametersInURI; +@property (nonatomic, strong) NSSet *HTTPMethodsEncodingParametersInURI; /** Set the method of query string serialization according to one of the pre-defined styles. @@ -187,19 +216,12 @@ forHTTPHeaderField:(NSString *)field; @param block A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occurred when attempting to encode parameters for the given request. */ -- (void)setQueryStringSerializationWithBlock:(NSString * (^)(NSURLRequest *request, NSDictionary *parameters, NSError * __autoreleasing *error))block; +- (void)setQueryStringSerializationWithBlock:(nullable NSString * (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block; ///------------------------------- /// @name Creating Request Objects ///------------------------------- -/** - @deprecated This method has been deprecated. Use -requestWithMethod:URLString:parameters:error: instead. - */ -- (NSMutableURLRequest *)requestWithMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(id)parameters DEPRECATED_ATTRIBUTE; - /** Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string. @@ -208,22 +230,14 @@ forHTTPHeaderField:(NSString *)field; @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`. @param URLString The URL string used to create the request URL. @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body. - @param error The error that occured while constructing the request. + @param error The error that occurred while constructing the request. @return An `NSMutableURLRequest` object. */ - (NSMutableURLRequest *)requestWithMethod:(NSString *)method URLString:(NSString *)URLString - parameters:(id)parameters - error:(NSError * __autoreleasing *)error; - -/** - @deprecated This method has been deprecated. Use -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error: instead. - */ -- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(NSDictionary *)parameters - constructingBodyWithBlock:(void (^)(id formData))block DEPRECATED_ATTRIBUTE; + parameters:(nullable id)parameters + error:(NSError * _Nullable __autoreleasing *)error; /** Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2 @@ -234,30 +248,30 @@ forHTTPHeaderField:(NSString *)field; @param URLString The URL string used to create the request URL. @param parameters The parameters to be encoded and set in the request HTTP body. @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. - @param error The error that occured while constructing the request. + @param error The error that occurred while constructing the request. @return An `NSMutableURLRequest` object */ - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method URLString:(NSString *)URLString - parameters:(NSDictionary *)parameters - constructingBodyWithBlock:(void (^)(id formData))block - error:(NSError * __autoreleasing *)error; + parameters:(nullable NSDictionary *)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + error:(NSError * _Nullable __autoreleasing *)error; /** Creates an `NSMutableURLRequest` by removing the `HTTPBodyStream` from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished. - - @param request The multipart form request. + + @param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`. @param fileURL The file URL to write multipart form contents to. @param handler A handler block to execute. - + @discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request. @see https://github.com/AFNetworking/AFNetworking/issues/1398 */ - (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request writingStreamContentsToFile:(NSURL *)fileURL - completionHandler:(void (^)(NSError *error))handler; + completionHandler:(nullable void (^)(NSError * _Nullable error))handler; @end @@ -281,7 +295,7 @@ forHTTPHeaderField:(NSString *)field; */ - (BOOL)appendPartWithFileURL:(NSURL *)fileURL name:(NSString *)name - error:(NSError * __autoreleasing *)error; + error:(NSError * _Nullable __autoreleasing *)error; /** Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. @@ -298,7 +312,7 @@ forHTTPHeaderField:(NSString *)field; name:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType - error:(NSError * __autoreleasing *)error; + error:(NSError * _Nullable __autoreleasing *)error; /** Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary. @@ -309,7 +323,7 @@ forHTTPHeaderField:(NSString *)field; @param length The length of the specified input stream in bytes. @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. */ -- (void)appendPartWithInputStream:(NSInputStream *)inputStream +- (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream name:(NSString *)name fileName:(NSString *)fileName length:(int64_t)length @@ -345,7 +359,7 @@ forHTTPHeaderField:(NSString *)field; @param headers The HTTP headers to be appended to the form data. @param body The data to be encoded and appended to the form data. This parameter must not be `nil`. */ -- (void)appendPartWithHeaders:(NSDictionary *)headers +- (void)appendPartWithHeaders:(nullable NSDictionary *)headers body:(NSData *)body; /** @@ -363,6 +377,9 @@ forHTTPHeaderField:(NSString *)field; #pragma mark - +/** + `AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`. + */ @interface AFJSONRequestSerializer : AFHTTPRequestSerializer /** @@ -379,6 +396,11 @@ forHTTPHeaderField:(NSString *)field; @end +#pragma mark - + +/** + `AFPropertyListRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`. + */ @interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer /** @@ -396,7 +418,7 @@ forHTTPHeaderField:(NSString *)field; @param format The property list format. @param writeOptions The property list write options. - + @warning The `writeOptions` property is currently unused. */ + (instancetype)serializerWithFormat:(NSPropertyListFormat)format @@ -404,6 +426,8 @@ forHTTPHeaderField:(NSString *)field; @end +#pragma mark - + ///---------------- /// @name Constants ///---------------- @@ -420,21 +444,21 @@ forHTTPHeaderField:(NSString *)field; `AFURLRequestSerializationErrorDomain` AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. */ -extern NSString * const AFURLRequestSerializationErrorDomain; +FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain; /** ## User info dictionary keys These keys may exist in the user info dictionary, in addition to those defined for NSError. - - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` + - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey` ### Constants `AFNetworkingOperationFailingURLRequestErrorKey` The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`. */ -extern NSString * const AFNetworkingOperationFailingURLRequestErrorKey; +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey; /** ## Throttling Bandwidth for HTTP Request Input Streams @@ -449,5 +473,7 @@ extern NSString * const AFNetworkingOperationFailingURLRequestErrorKey; `kAFUploadStream3GSuggestedDelay` Duration of delay each time a packet is read. Equal to 0.2 seconds. */ -extern NSUInteger const kAFUploadStream3GSuggestedPacketSize; -extern NSTimeInterval const kAFUploadStream3GSuggestedDelay; +FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize; +FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay; + +NS_ASSUME_NONNULL_END diff --git a/src/ios/AFNetworking/AFURLRequestSerialization.m b/src/ios/AFNetworking/AFURLRequestSerialization.m index aea41d9b..086e6747 100644 --- a/src/ios/AFNetworking/AFURLRequestSerialization.m +++ b/src/ios/AFNetworking/AFURLRequestSerialization.m @@ -1,6 +1,5 @@ -// AFSerialization.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// AFURLRequestSerialization.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -8,10 +7,10 @@ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -22,7 +21,7 @@ #import "AFURLRequestSerialization.h" -#if __IPHONE_OS_VERSION_MIN_REQUIRED +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV #import #else #import @@ -31,47 +30,53 @@ NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request"; NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response"; -typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error); +typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error); -static NSString * AFBase64EncodedStringFromString(NSString *string) { - NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]]; - NSUInteger length = [data length]; - NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4]; +/** + Returns a percent-escaped string following RFC 3986 for a query string key or value. + RFC 3986 states that the following characters are "reserved" characters. + - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" - uint8_t *input = (uint8_t *)[data bytes]; - uint8_t *output = (uint8_t *)[mutableData mutableBytes]; + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + should be percent-escaped in the query string. + - parameter string: The string to be percent-escaped. + - returns: The percent-escaped string. + */ +NSString * AFPercentEscapedStringFromString(NSString *string) { + static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4 + static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;="; - for (NSUInteger i = 0; i < length; i += 3) { - NSUInteger value = 0; - for (NSUInteger j = i; j < (i + 3); j++) { - value <<= 8; - if (j < length) { - value |= (0xFF & input[j]); - } - } + NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]]; - static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + // FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028 + // return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; - NSUInteger idx = (i / 3) * 4; - output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F]; - output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F]; - output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '='; - output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '='; - } + static NSUInteger const batchSize = 50; - return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding]; -} + NSUInteger index = 0; + NSMutableString *escaped = @"".mutableCopy; -static NSString * const kAFCharactersToBeEscapedInQueryString = @":/?&=;+!@#$()',*"; + while (index < string.length) { +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wgnu" + NSUInteger length = MIN(string.length - index, batchSize); +#pragma GCC diagnostic pop + NSRange range = NSMakeRange(index, length); -static NSString * AFPercentEscapedQueryStringKeyFromStringWithEncoding(NSString *string, NSStringEncoding encoding) { - static NSString * const kAFCharactersToLeaveUnescapedInQueryStringPairKey = @"[]."; + // To avoid breaking up character sequences such as 👴🏻👮🏽 + range = [string rangeOfComposedCharacterSequencesForRange:range]; - return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, (__bridge CFStringRef)kAFCharactersToLeaveUnescapedInQueryStringPairKey, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding)); -} + NSString *substring = [string substringWithRange:range]; + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + [escaped appendString:encoded]; + + index += range.length; + } -static NSString * AFPercentEscapedQueryStringValueFromStringWithEncoding(NSString *string, NSStringEncoding encoding) { - return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding)); + return escaped; } #pragma mark - @@ -80,14 +85,14 @@ @interface AFQueryStringPair : NSObject @property (readwrite, nonatomic, strong) id field; @property (readwrite, nonatomic, strong) id value; -- (id)initWithField:(id)field value:(id)value; +- (instancetype)initWithField:(id)field value:(id)value; -- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding; +- (NSString *)URLEncodedStringValue; @end @implementation AFQueryStringPair -- (id)initWithField:(id)field value:(id)value { +- (instancetype)initWithField:(id)field value:(id)value { self = [super init]; if (!self) { return nil; @@ -99,11 +104,11 @@ - (id)initWithField:(id)field value:(id)value { return self; } -- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding { +- (NSString *)URLEncodedStringValue { if (!self.value || [self.value isEqual:[NSNull null]]) { - return AFPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding); + return AFPercentEscapedStringFromString([self.field description]); } else { - return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding), AFPercentEscapedQueryStringValueFromStringWithEncoding([self.value description], stringEncoding)]; + return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedStringFromString([self.field description]), AFPercentEscapedStringFromString([self.value description])]; } } @@ -111,13 +116,13 @@ - (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding #pragma mark - -extern NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); -extern NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); -static NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding stringEncoding) { +NSString * AFQueryStringFromParameters(NSDictionary *parameters) { NSMutableArray *mutablePairs = [NSMutableArray array]; for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { - [mutablePairs addObject:[pair URLEncodedStringValueWithEncoding:stringEncoding]]; + [mutablePairs addObject:[pair URLEncodedStringValue]]; } return [mutablePairs componentsJoinedByString:@"&"]; @@ -136,7 +141,7 @@ - (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding NSDictionary *dictionary = value; // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { - id nestedValue = [dictionary objectForKey:nestedKey]; + id nestedValue = dictionary[nestedKey]; if (nestedValue) { [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)]; } @@ -154,7 +159,7 @@ - (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding } else { [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]]; } - + return mutableQueryStringComponents; } @@ -216,11 +221,14 @@ - (instancetype)init { NSString *userAgent = nil; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu" -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; +#elif TARGET_OS_WATCH // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 - userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], (__bridge id)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey) ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; watchOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[WKInterfaceDevice currentDevice] model], [[WKInterfaceDevice currentDevice] systemVersion], [[WKInterfaceDevice currentDevice] screenScale]]; #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) - userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]; + userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]; #endif #pragma clang diagnostic pop if (userAgent) { @@ -238,7 +246,9 @@ - (instancetype)init { self.mutableObservedChangedKeyPaths = [NSMutableSet set]; for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { - [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext]; + if ([self respondsToSelector:NSSelectorFromString(keyPath)]) { + [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext]; + } } return self; @@ -246,12 +256,55 @@ - (instancetype)init { - (void)dealloc { for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { - [self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext]; + if ([self respondsToSelector:NSSelectorFromString(keyPath)]) { + [self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext]; + } } } #pragma mark - +// Workarounds for crashing behavior using Key-Value Observing with XCTest +// See https://github.com/AFNetworking/AFNetworking/issues/2523 + +- (void)setAllowsCellularAccess:(BOOL)allowsCellularAccess { + [self willChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))]; + _allowsCellularAccess = allowsCellularAccess; + [self didChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))]; +} + +- (void)setCachePolicy:(NSURLRequestCachePolicy)cachePolicy { + [self willChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))]; + _cachePolicy = cachePolicy; + [self didChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))]; +} + +- (void)setHTTPShouldHandleCookies:(BOOL)HTTPShouldHandleCookies { + [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))]; + _HTTPShouldHandleCookies = HTTPShouldHandleCookies; + [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))]; +} + +- (void)setHTTPShouldUsePipelining:(BOOL)HTTPShouldUsePipelining { + [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))]; + _HTTPShouldUsePipelining = HTTPShouldUsePipelining; + [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))]; +} + +- (void)setNetworkServiceType:(NSURLRequestNetworkServiceType)networkServiceType { + [self willChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))]; + _networkServiceType = networkServiceType; + [self didChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))]; +} + +- (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval { + [self willChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))]; + _timeoutInterval = timeoutInterval; + [self didChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))]; +} + +#pragma mark - + - (NSDictionary *)HTTPRequestHeaders { return [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders]; } @@ -269,12 +322,9 @@ - (NSString *)valueForHTTPHeaderField:(NSString *)field { - (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username password:(NSString *)password { - NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; - [self setValue:[NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)] forHTTPHeaderField:@"Authorization"]; -} - -- (void)setAuthorizationHeaderFieldWithToken:(NSString *)token { - [self setValue:[NSString stringWithFormat:@"Token token=\"%@\"", token] forHTTPHeaderField:@"Authorization"]; + NSData *basicAuthCredentials = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding]; + NSString *base64AuthCredentials = [basicAuthCredentials base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0]; + [self setValue:[NSString stringWithFormat:@"Basic %@", base64AuthCredentials] forHTTPHeaderField:@"Authorization"]; } - (void)clearAuthorizationHeader { @@ -288,19 +338,12 @@ - (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializat self.queryStringSerialization = nil; } -- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, NSDictionary *, NSError *__autoreleasing *))block { +- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, id, NSError *__autoreleasing *))block { self.queryStringSerialization = block; } #pragma mark - -- (NSMutableURLRequest *)requestWithMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(id)parameters -{ - return [self requestWithMethod:method URLString:URLString parameters:parameters error:nil]; -} - - (NSMutableURLRequest *)requestWithMethod:(NSString *)method URLString:(NSString *)URLString parameters:(id)parameters @@ -327,14 +370,6 @@ - (NSMutableURLRequest *)requestWithMethod:(NSString *)method return mutableRequest; } -- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(NSDictionary *)parameters - constructingBodyWithBlock:(void (^)(id formData))block -{ - return [self multipartFormRequestWithMethod:method URLString:URLString parameters:parameters constructingBodyWithBlock:block error:nil]; -} - - (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method URLString:(NSString *)URLString parameters:(NSDictionary *)parameters @@ -376,10 +411,7 @@ - (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request writingStreamContentsToFile:(NSURL *)fileURL completionHandler:(void (^)(NSError *error))handler { - if (!request.HTTPBodyStream) { - return [request mutableCopy]; - } - + NSParameterAssert(request.HTTPBodyStream); NSParameterAssert([fileURL isFileURL]); NSInputStream *inputStream = request.HTTPBodyStream; @@ -445,8 +477,8 @@ - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request } }]; + NSString *query = nil; if (parameters) { - NSString *query = nil; if (self.queryStringSerialization) { NSError *serializationError; query = self.queryStringSerialization(request, parameters, &serializationError); @@ -461,19 +493,25 @@ - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request } else { switch (self.queryStringSerializationStyle) { case AFHTTPRequestQueryStringDefaultStyle: - query = AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding); + query = AFQueryStringFromParameters(parameters); break; } } + } - if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + if (query) { mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]]; - } else { - if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { - [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; - } - [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]]; } + } else { + // #2864: an empty string is a valid x-www-form-urlencoded payload + if (!query) { + query = @""; + } + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { + [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; + } + [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]]; } return mutableRequest; @@ -481,6 +519,14 @@ - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request #pragma mark - NSKeyValueObserving ++ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key { + if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) { + return NO; + } + + return [super automaticallyNotifiesObserversForKey:key]; +} + - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(__unused id)object change:(NSDictionary *)change @@ -501,14 +547,14 @@ + (BOOL)supportsSecureCoding { return YES; } -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [self init]; if (!self) { return nil; } self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy]; - self.queryStringSerializationStyle = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue]; + self.queryStringSerializationStyle = (AFHTTPRequestQueryStringSerializationStyle)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue]; return self; } @@ -520,12 +566,12 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init]; serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone]; serializer.queryStringSerializationStyle = self.queryStringSerializationStyle; serializer.queryStringSerialization = self.queryStringSerialization; - + return serializer; } @@ -552,7 +598,6 @@ - (id)copyWithZone:(NSZone *)zone { } static inline NSString * AFContentTypeForPathExtension(NSString *extension) { -#ifdef __UTTYPE__ NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL); NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType); if (!contentType) { @@ -560,10 +605,6 @@ - (id)copyWithZone:(NSZone *)zone { } else { return contentType; } -#else -#pragma unused (extension) - return @"application/octet-stream"; -#endif } NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16; @@ -594,7 +635,7 @@ @interface AFMultipartBodyStream : NSInputStream @property (readonly, nonatomic, assign) unsigned long long contentLength; @property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty; -- (id)initWithStringEncoding:(NSStringEncoding)encoding; +- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding; - (void)setInitialAndFinalBoundaries; - (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart; @end @@ -610,8 +651,8 @@ @interface AFStreamingMultipartFormData () @implementation AFStreamingMultipartFormData -- (id)initWithURLRequest:(NSMutableURLRequest *)urlRequest - stringEncoding:(NSStringEncoding)encoding +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest + stringEncoding:(NSStringEncoding)encoding { self = [super init]; if (!self) { @@ -670,17 +711,17 @@ - (BOOL)appendPartWithFileURL:(NSURL *)fileURL if (!fileAttributes) { return NO; } - + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; - + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; bodyPart.stringEncoding = self.stringEncoding; bodyPart.headers = mutableHeaders; bodyPart.boundary = self.boundary; bodyPart.body = fileURL; - bodyPart.bodyContentLength = [[fileAttributes objectForKey:NSFileSize] unsignedLongLongValue]; + bodyPart.bodyContentLength = [fileAttributes[NSFileSize] unsignedLongLongValue]; [self.bodyStream appendHTTPBodyPart:bodyPart]; return YES; @@ -803,7 +844,7 @@ @implementation AFMultipartBodyStream @synthesize streamError; #pragma clang diagnostic pop -- (id)initWithStringEncoding:(NSStringEncoding)encoding { +- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding { self = [super init]; if (!self) { return nil; @@ -823,7 +864,7 @@ - (void)setInitialAndFinalBoundaries { bodyPart.hasFinalBoundary = NO; } - [[self.HTTPBodyParts objectAtIndex:0] setHasInitialBoundary:YES]; + [[self.HTTPBodyParts firstObject] setHasInitialBoundary:YES]; [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES]; } } @@ -855,7 +896,7 @@ - (NSInteger)read:(uint8_t *)buffer break; } } else { - NSUInteger maxLength = length - (NSUInteger)totalNumberOfBytesRead; + NSUInteger maxLength = MIN(length, self.numberOfBytesInPacket) - (NSUInteger)totalNumberOfBytesRead; NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength]; if (numberOfBytesRead == -1) { self.streamError = self.currentHTTPBodyPart.inputStream.streamError; @@ -946,7 +987,7 @@ - (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags #pragma mark - NSCopying --(id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding]; for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { @@ -983,7 +1024,7 @@ - (NSInteger)readData:(NSData *)data @implementation AFHTTPBodyPart -- (id)init { +- (instancetype)init { self = [super init]; if (!self) { return nil; @@ -1127,7 +1168,9 @@ - (NSInteger)readData:(NSData *)data - (BOOL)transitionToNextPhase { if (![[NSThread currentThread] isMainThread]) { - [self performSelectorOnMainThread:@selector(transitionToNextPhase) withObject:nil waitUntilDone:YES]; + dispatch_sync(dispatch_get_main_queue(), ^{ + [self transitionToNextPhase]; + }); return YES; } @@ -1159,15 +1202,15 @@ - (BOOL)transitionToNextPhase { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init]; - + bodyPart.stringEncoding = self.stringEncoding; bodyPart.headers = self.headers; bodyPart.bodyContentLength = self.bodyContentLength; bodyPart.body = self.body; bodyPart.boundary = self.boundary; - + return bodyPart; } @@ -1208,11 +1251,10 @@ - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request [mutableRequest setValue:value forHTTPHeaderField:field]; } }]; - + if (parameters) { if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { - NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)); - [mutableRequest setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] forHTTPHeaderField:@"Content-Type"]; + [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; } [mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]]; @@ -1223,7 +1265,7 @@ - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request #pragma mark - NSSecureCoding -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; @@ -1242,7 +1284,7 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFJSONRequestSerializer *serializer = [super copyWithZone:zone]; serializer.writingOptions = self.writingOptions; @@ -1291,8 +1333,7 @@ - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request if (parameters) { if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { - NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)); - [mutableRequest setValue:[NSString stringWithFormat:@"application/x-plist; charset=%@", charset] forHTTPHeaderField:@"Content-Type"]; + [mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"]; } [mutableRequest setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error]]; @@ -1303,13 +1344,13 @@ - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request #pragma mark - NSSecureCoding -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; } - self.format = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; + self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue]; return self; @@ -1324,7 +1365,7 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone]; serializer.format = self.format; serializer.writeOptions = self.writeOptions; diff --git a/src/ios/AFNetworking/AFURLResponseSerialization.h b/src/ios/AFNetworking/AFURLResponseSerialization.h index ed1204c2..c1357aed 100644 --- a/src/ios/AFNetworking/AFURLResponseSerialization.h +++ b/src/ios/AFNetworking/AFURLResponseSerialization.h @@ -1,6 +1,5 @@ -// AFSerialization.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// AFURLResponseSerialization.h +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -8,10 +7,10 @@ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,6 +22,8 @@ #import #import +NS_ASSUME_NONNULL_BEGIN + /** The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data. @@ -39,9 +40,9 @@ @return The object decoded from the specified response data. */ -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error; +- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response + data:(nullable NSData *)data + error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; @end @@ -54,8 +55,10 @@ */ @interface AFHTTPResponseSerializer : NSObject +- (instancetype)init; + /** - The string encoding used to serialize parameters. + The string encoding used to serialize data received from the server, when no string encoding is specified by the response. `NSUTF8StringEncoding` by default. */ @property (nonatomic, assign) NSStringEncoding stringEncoding; @@ -73,12 +76,12 @@ See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html */ -@property (nonatomic, copy) NSIndexSet *acceptableStatusCodes; +@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes; /** The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation. */ -@property (nonatomic, copy) NSSet *acceptableContentTypes; +@property (nonatomic, copy, nullable) NSSet *acceptableContentTypes; /** Validates the specified response and data. @@ -91,9 +94,9 @@ @return `YES` if the response is valid, otherwise `NO`. */ -- (BOOL)validateResponse:(NSHTTPURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error; +- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response + data:(nullable NSData *)data + error:(NSError * _Nullable __autoreleasing *)error; @end @@ -111,6 +114,8 @@ */ @interface AFJSONResponseSerializer : AFHTTPResponseSerializer +- (instancetype)init; + /** Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. */ @@ -133,9 +138,9 @@ #pragma mark - /** - `AFXMLParserSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects. + `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects. - By default, `AFXMLParserSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: + By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: - `application/xml` - `text/xml` @@ -149,15 +154,17 @@ #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED /** - `AFXMLDocumentSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. + `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. - By default, `AFXMLDocumentSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: + By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: - `application/xml` - `text/xml` */ @interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer +- (instancetype)init; + /** Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. */ @@ -177,14 +184,16 @@ #pragma mark - /** - `AFPropertyListSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. + `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. - By default, `AFPropertyListSerializer` accepts the following MIME types: + By default, `AFPropertyListResponseSerializer` accepts the following MIME types: - `application/x-plist` */ @interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer +- (instancetype)init; + /** The property list format. Possible values are described in "NSPropertyListFormat". */ @@ -209,9 +218,9 @@ #pragma mark - /** - `AFImageSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses. + `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses. - By default, `AFImageSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: + By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: - `image/tiff` - `image/jpeg` @@ -226,7 +235,7 @@ */ @interface AFImageResponseSerializer : AFHTTPResponseSerializer -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH /** The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. */ @@ -250,14 +259,14 @@ /** The component response serializers. */ -@property (readonly, nonatomic, copy) NSArray *responseSerializers; +@property (readonly, nonatomic, copy) NSArray > *responseSerializers; /** Creates and returns a compound serializer comprised of the specified response serializers. @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`. */ -+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers; ++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray > *)responseSerializers; @end @@ -277,7 +286,7 @@ `AFURLResponseSerializationErrorDomain` AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. */ -extern NSString * const AFURLResponseSerializationErrorDomain; +FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain; /** ## User info dictionary keys @@ -291,12 +300,12 @@ extern NSString * const AFURLResponseSerializationErrorDomain; `AFNetworkingOperationFailingURLResponseErrorKey` The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. - + `AFNetworkingOperationFailingURLResponseDataErrorKey` The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. */ -extern NSString * const AFNetworkingOperationFailingURLResponseErrorKey; - -extern NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey; +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; +NS_ASSUME_NONNULL_END diff --git a/src/ios/AFNetworking/AFURLResponseSerialization.m b/src/ios/AFNetworking/AFURLResponseSerialization.m old mode 100644 new mode 100755 index 7b042f75..1402e8d3 --- a/src/ios/AFNetworking/AFURLResponseSerialization.m +++ b/src/ios/AFNetworking/AFURLResponseSerialization.m @@ -1,6 +1,5 @@ -// AFSerialization.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// AFURLResponseSerialization.m +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -8,10 +7,10 @@ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -22,8 +21,12 @@ #import "AFURLResponseSerialization.h" -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#import + +#if TARGET_OS_IOS #import +#elif TARGET_OS_WATCH +#import #elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) #import #endif @@ -68,11 +71,11 @@ static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingO } else if ([JSONObject isKindOfClass:[NSDictionary class]]) { NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject]; for (id key in [(NSDictionary *)JSONObject allKeys]) { - id value = [(NSDictionary *)JSONObject objectForKey:key]; + id value = (NSDictionary *)JSONObject[key]; if (!value || [value isEqual:[NSNull null]]) { [mutableDictionary removeObjectForKey:key]; } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) { - [mutableDictionary setObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions) forKey:key]; + mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions); } } @@ -113,7 +116,7 @@ - (BOOL)validateResponse:(NSHTTPURLResponse *)response if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) { if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]]) { - if ([data length] > 0) { + if ([data length] > 0 && [response URL]) { NSMutableDictionary *mutableUserInfo = [@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]], NSURLErrorFailingURLErrorKey:[response URL], @@ -129,7 +132,7 @@ - (BOOL)validateResponse:(NSHTTPURLResponse *)response responseIsValid = NO; } - if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode]) { + if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) { NSMutableDictionary *mutableUserInfo = [@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode], NSURLErrorFailingURLErrorKey:[response URL], @@ -170,7 +173,7 @@ + (BOOL)supportsSecureCoding { return YES; } -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [self init]; if (!self) { return nil; @@ -189,7 +192,7 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone]; serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone]; @@ -237,56 +240,31 @@ - (id)responseObjectForResponse:(NSURLResponse *)response } } - // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization. - // See https://github.com/rails/rails/issues/1742 - NSStringEncoding stringEncoding = self.stringEncoding; - if (response.textEncodingName) { - CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName); - if (encoding != kCFStringEncodingInvalidId) { - stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); - } - } - id responseObject = nil; NSError *serializationError = nil; - @autoreleasepool { - NSString *responseString = [[NSString alloc] initWithData:data encoding:stringEncoding]; - if (responseString && ![responseString isEqualToString:@" "]) { - // Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character - // See http://stackoverflow.com/a/12843465/157142 - data = [responseString dataUsingEncoding:NSUTF8StringEncoding]; - - if (data) { - if ([data length] > 0) { - responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError]; - } else { - return nil; - } - } else { - NSDictionary *userInfo = @{ - NSLocalizedDescriptionKey: NSLocalizedStringFromTable(@"Data failed decoding as a UTF-8 string", @"AFNetworking", nil), - NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Could not decode string: %@", @"AFNetworking", nil), responseString] - }; - - serializationError = [NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo]; - } - } + // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization. + // See https://github.com/rails/rails/issues/1742 + BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]]; + if (data.length > 0 && !isSpace) { + responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError]; + } else { + return nil; } if (self.removesKeysWithNullValues && responseObject) { responseObject = AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions); } - + if (error) { *error = AFErrorWithUnderlyingError(serializationError, *error); } - + return responseObject; } #pragma mark - NSSecureCoding -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; @@ -307,7 +285,7 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; serializer.readingOptions = self.readingOptions; serializer.removesKeysWithNullValues = self.removesKeysWithNullValues; @@ -407,7 +385,7 @@ - (id)responseObjectForResponse:(NSURLResponse *)response #pragma mark - NSSecureCoding -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; @@ -426,7 +404,7 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; serializer.options = self.options; @@ -494,13 +472,13 @@ - (id)responseObjectForResponse:(NSURLResponse *)response #pragma mark - NSSecureCoding -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; } - self.format = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; + self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue]; return self; @@ -515,7 +493,7 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; serializer.format = self.format; serializer.readOptions = self.readOptions; @@ -527,12 +505,39 @@ - (id)copyWithZone:(NSZone *)zone { #pragma mark - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH #import +#import -static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) { - UIImage *image = [[UIImage alloc] initWithData:data]; +@interface UIImage (AFNetworkingSafeImageLoading) ++ (UIImage *)af_safeImageWithData:(NSData *)data; +@end + +static NSLock* imageLock = nil; + +@implementation UIImage (AFNetworkingSafeImageLoading) + ++ (UIImage *)af_safeImageWithData:(NSData *)data { + UIImage* image = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + imageLock = [[NSLock alloc] init]; + }); + + [imageLock lock]; + image = [UIImage imageWithData:data]; + [imageLock unlock]; + return image; +} +@end + +static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) { + UIImage *image = [UIImage af_safeImageWithData:data]; + if (image.images) { + return image; + } + return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation]; } @@ -549,10 +554,11 @@ - (id)copyWithZone:(NSZone *)zone { } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) { imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); - // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so if so, fall back to AFImageWithDataAtScale if (imageRef) { CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef); CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace); + + // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale if (imageColorSpaceModel == kCGColorSpaceModelCMYK) { CGImageRelease(imageRef); imageRef = NULL; @@ -584,7 +590,8 @@ - (id)copyWithZone:(NSZone *)zone { return image; } - size_t bytesPerRow = 0; // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate + // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate + size_t bytesPerRow = 0; CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace); CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); @@ -622,7 +629,7 @@ - (id)copyWithZone:(NSZone *)zone { CGImageRelease(inflatedImageRef); CGImageRelease(imageRef); - + return inflatedImage; } #endif @@ -638,9 +645,12 @@ - (instancetype)init { self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV self.imageScale = [[UIScreen mainScreen] scale]; self.automaticallyInflatesResponseImage = YES; +#elif TARGET_OS_WATCH + self.imageScale = [[WKInterfaceDevice currentDevice] screenScale]; + self.automaticallyInflatesResponseImage = YES; #endif return self; @@ -658,13 +668,13 @@ - (id)responseObjectForResponse:(NSURLResponse *)response } } -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH if (self.automaticallyInflatesResponseImage) { return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale); } else { return AFImageWithDataAtScale(data, self.imageScale); } -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +#else // Ensure that the image is set to it's correct pixel width and height NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data]; NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])]; @@ -678,13 +688,13 @@ - (id)responseObjectForResponse:(NSURLResponse *)response #pragma mark - NSSecureCoding -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; } -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))]; #if CGFLOAT_IS_DOUBLE self.imageScale = [imageScale doubleValue]; @@ -701,7 +711,7 @@ - (id)initWithCoder:(NSCoder *)decoder { - (void)encodeWithCoder:(NSCoder *)coder { [super encodeWithCoder:coder]; -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))]; [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; #endif @@ -709,10 +719,10 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH serializer.imageScale = self.imageScale; serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage; #endif @@ -758,13 +768,13 @@ - (id)responseObjectForResponse:(NSURLResponse *)response return responseObject; } } - + return [super responseObjectForResponse:response data:data error:error]; } #pragma mark - NSSecureCoding -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; if (!self) { return nil; @@ -783,7 +793,7 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; serializer.responseSerializers = self.responseSerializers; diff --git a/src/ios/AFNetworking/AFURLSessionManager.h b/src/ios/AFNetworking/AFURLSessionManager.h index 6939b7d4..691e80c8 100644 --- a/src/ios/AFNetworking/AFURLSessionManager.h +++ b/src/ios/AFNetworking/AFURLSessionManager.h @@ -1,6 +1,5 @@ // AFURLSessionManager.h -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -8,10 +7,10 @@ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,39 +19,42 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. + #import #import "AFURLResponseSerialization.h" #import "AFURLRequestSerialization.h" #import "AFSecurityPolicy.h" +#if !TARGET_OS_WATCH #import "AFNetworkReachabilityManager.h" +#endif /** `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. - + ## Subclassing Notes - + This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead. - + ## NSURLSession & NSURLSessionTask Delegate Methods - + `AFURLSessionManager` implements the following delegate methods: - + ### `NSURLSessionDelegate` - + - `URLSession:didBecomeInvalidWithError:` - `URLSession:didReceiveChallenge:completionHandler:` - `URLSessionDidFinishEventsForBackgroundURLSession:` ### `NSURLSessionTaskDelegate` - + - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:` - `URLSession:task:didReceiveChallenge:completionHandler:` - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:` - `URLSession:task:didCompleteWithError:` ### `NSURLSessionDataDelegate` - + - `URLSession:dataTask:didReceiveResponse:completionHandler:` - `URLSession:dataTask:didBecomeDownloadTask:` - `URLSession:dataTask:didReceiveData:` @@ -63,24 +65,26 @@ - `URLSession:downloadTask:didFinishDownloadingToURL:` - `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:` - `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:` - + If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. - + ## Network Reachability Monitoring Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details. - + ## NSCoding Caveats - + - Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`. ## NSCopying Caveats - `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original. - Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied. + + @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. */ -#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) +NS_ASSUME_NONNULL_BEGIN @interface AFURLSessionManager : NSObject @@ -106,10 +110,11 @@ ///------------------------------- /** - The security policy used by created request operations to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. + The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. */ @property (nonatomic, strong) AFSecurityPolicy *securityPolicy; +#if !TARGET_OS_WATCH ///-------------------------------------- /// @name Monitoring Network Reachability ///-------------------------------------- @@ -118,6 +123,7 @@ The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default. */ @property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; +#endif ///---------------------------- /// @name Getting Session Tasks @@ -126,22 +132,22 @@ /** The data, upload, and download tasks currently run by the managed session. */ -@property (readonly, nonatomic, strong) NSArray *tasks; +@property (readonly, nonatomic, strong) NSArray *tasks; /** The data tasks currently run by the managed session. */ -@property (readonly, nonatomic, strong) NSArray *dataTasks; +@property (readonly, nonatomic, strong) NSArray *dataTasks; /** The upload tasks currently run by the managed session. */ -@property (readonly, nonatomic, strong) NSArray *uploadTasks; +@property (readonly, nonatomic, strong) NSArray *uploadTasks; /** The download tasks currently run by the managed session. */ -@property (readonly, nonatomic, strong) NSArray *downloadTasks; +@property (readonly, nonatomic, strong) NSArray *downloadTasks; ///------------------------------- /// @name Managing Callback Queues @@ -150,12 +156,12 @@ /** The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. */ -@property (nonatomic, strong) dispatch_queue_t completionQueue; +@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; /** The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. */ -@property (nonatomic, strong) dispatch_group_t completionGroup; +@property (nonatomic, strong, nullable) dispatch_group_t completionGroup; ///--------------------------------- /// @name Working Around System Bugs @@ -176,16 +182,16 @@ /** Creates and returns a manager for a session created with the specified configuration. This is the designated initializer. - + @param configuration The configuration used to create the managed session. - + @return A manager for a newly-created session. */ -- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration; +- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; /** Invalidates the managed session, optionally canceling pending tasks. - + @param cancelPendingTasks Whether or not to cancel pending tasks. */ - (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks; @@ -201,7 +207,20 @@ @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. */ - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionDataTask` with the specified request. + + @param request The HTTP request for the request. + @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; ///--------------------------- /// @name Running Upload Tasks @@ -212,39 +231,39 @@ @param request The HTTP request for the request. @param fileURL A URL to the local file to be uploaded. - @param progress A progress object monitoring the current upload progress. + @param progress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. - + @see `attemptsToRecreateUploadTasksForBackgroundSessions` */ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL - progress:(NSProgress * __autoreleasing *)progress - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; + progress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; /** Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body. @param request The HTTP request for the request. @param bodyData A data object containing the HTTP body to be uploaded. - @param progress A progress object monitoring the current upload progress. + @param progress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. */ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request - fromData:(NSData *)bodyData - progress:(NSProgress * __autoreleasing *)progress - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; + fromData:(nullable NSData *)bodyData + progress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; /** Creates an `NSURLSessionUploadTask` with the specified streaming request. @param request The HTTP request for the request. - @param progress A progress object monitoring the current upload progress. + @param progress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. */ - (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request - progress:(NSProgress * __autoreleasing *)progress - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler; + progress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; ///----------------------------- /// @name Running Download Tasks @@ -254,29 +273,29 @@ Creates an `NSURLSessionDownloadTask` with the specified request. @param request The HTTP request for the request. - @param progress A progress object monitoring the current download progress. + @param progress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. - + @warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method. */ - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request - progress:(NSProgress * __autoreleasing *)progress - destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination - completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler; + progress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; /** Creates an `NSURLSessionDownloadTask` with the specified resume data. @param resumeData The data used to resume downloading. - @param progress A progress object monitoring the current download progress. + @param progress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. */ - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData - progress:(NSProgress * __autoreleasing *)progress - destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination - completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler; + progress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; ///--------------------------------- /// @name Getting Progress for Tasks @@ -285,20 +304,20 @@ /** Returns the upload progress of the specified task. - @param uploadTask The session upload task. Must not be `nil`. + @param task The session task. Must not be `nil`. @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable. */ -- (NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask; +- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task; /** Returns the download progress of the specified task. - - @param downloadTask The session download task. Must not be `nil`. - + + @param task The session task. Must not be `nil`. + @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable. */ -- (NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask; +- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task; ///----------------------------------------- /// @name Setting Session Delegate Callbacks @@ -306,17 +325,17 @@ /** Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`. - + @param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation. */ -- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block; +- (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block; /** Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`. @param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. */ -- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block; +- (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; ///-------------------------------------- /// @name Setting Task Delegate Callbacks @@ -327,35 +346,35 @@ @param block A block object to be executed when a task requires a new request body stream. */ -- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block; +- (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block; /** Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`. - + @param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response. */ -- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block; +- (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block; /** Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`. - + @param block A block object to be executed when a session task has received a request specific authentication challenge. The block returns the disposition of the authentication challenge, and takes four arguments: the session, the task, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. */ -- (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block; +- (void)setTaskDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; /** Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. - + @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes five arguments: the session, the task, the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread. */ -- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block; +- (void)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block; /** Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`. - + @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task. */ -- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block; +- (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block; ///------------------------------------------- /// @name Setting Data Task Delegate Callbacks @@ -366,35 +385,35 @@ @param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response. */ -- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block; +- (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block; /** Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`. - + @param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become. */ -- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block; +- (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block; /** Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`. - + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue. */ -- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block; +- (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block; /** Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`. - + @param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response. */ -- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block; +- (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block; /** Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`. - + @param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session. */ -- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block; +- (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block; ///----------------------------------------------- /// @name Setting Download Task Delegate Callbacks @@ -402,128 +421,79 @@ /** Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`. - + @param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error. */ -- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block; +- (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block; /** Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`. - + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue. */ -- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block; +- (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block; /** Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. - + @param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded. */ -- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block; +- (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block; @end -#endif - ///-------------------- /// @name Notifications ///-------------------- -/** - Posted when a task begins executing. - - @deprecated Use `AFNetworkingTaskDidResumeNotification` instead. - */ -extern NSString * const AFNetworkingTaskDidStartNotification DEPRECATED_ATTRIBUTE; - /** Posted when a task resumes. */ -extern NSString * const AFNetworkingTaskDidResumeNotification; - -/** - Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. - - @deprecated Use `AFNetworkingTaskDidCompleteNotification` instead. - */ -extern NSString * const AFNetworkingTaskDidFinishNotification DEPRECATED_ATTRIBUTE; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification; /** Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. */ -extern NSString * const AFNetworkingTaskDidCompleteNotification; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification; /** Posted when a task suspends its execution. */ -extern NSString * const AFNetworkingTaskDidSuspendNotification; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification; /** Posted when a session is invalidated. */ -extern NSString * const AFURLSessionDidInvalidateNotification; +FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification; /** Posted when a session download task encountered an error when moving the temporary download file to a specified destination. */ -extern NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification; - -/** - The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if response data exists for the task. - - @deprecated Use `AFNetworkingTaskDidCompleteResponseDataKey` instead. - */ -extern NSString * const AFNetworkingTaskDidFinishResponseDataKey DEPRECATED_ATTRIBUTE; - -/** - The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if response data exists for the task. - */ -extern NSString * const AFNetworkingTaskDidCompleteResponseDataKey; +FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification; /** - The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the response was serialized. - - @deprecated Use `AFNetworkingTaskDidCompleteSerializedResponseKey` instead. + The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task. */ -extern NSString * const AFNetworkingTaskDidFinishSerializedResponseKey DEPRECATED_ATTRIBUTE; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey; /** - The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the response was serialized. + The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized. */ -extern NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey; /** - The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the task has an associated response serializer. - - @deprecated Use `AFNetworkingTaskDidCompleteResponseSerializerKey` instead. + The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer. */ -extern NSString * const AFNetworkingTaskDidFinishResponseSerializerKey DEPRECATED_ATTRIBUTE; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey; /** - The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if the task has an associated response serializer. + 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. */ -extern NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey; /** - The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an the response data has been stored directly to disk. - - @deprecated Use `AFNetworkingTaskDidCompleteAssetPathKey` instead. + Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists. */ -extern NSString * const AFNetworkingTaskDidFinishAssetPathKey DEPRECATED_ATTRIBUTE; +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey; -/** - The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an the response data has been stored directly to disk. - */ -extern NSString * const AFNetworkingTaskDidCompleteAssetPathKey; - -/** - Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an error exists. - - @deprecated Use `AFNetworkingTaskDidCompleteErrorKey` instead. - */ -extern NSString * const AFNetworkingTaskDidFinishErrorKey DEPRECATED_ATTRIBUTE; - -/** - Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidFinishNotification` if an error exists. - */ -extern NSString * const AFNetworkingTaskDidCompleteErrorKey; +NS_ASSUME_NONNULL_END diff --git a/src/ios/AFNetworking/AFURLSessionManager.m b/src/ios/AFNetworking/AFURLSessionManager.m index 0775c4da..170581ac 100644 --- a/src/ios/AFNetworking/AFURLSessionManager.m +++ b/src/ios/AFNetworking/AFURLSessionManager.m @@ -1,6 +1,5 @@ // AFURLSessionManager.m -// -// Copyright (c) 2013-2014 AFNetworking (http://afnetworking.com) +// Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -8,10 +7,10 @@ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,8 +20,13 @@ // THE SOFTWARE. #import "AFURLSessionManager.h" +#import -#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090) +#ifndef NSFoundationVersionNumber_iOS_8_0 +#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug 1140.11 +#else +#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug NSFoundationVersionNumber_iOS_8_0 +#endif static dispatch_queue_t url_session_manager_creation_queue() { static dispatch_queue_t af_url_session_manager_creation_queue; @@ -34,6 +38,17 @@ static dispatch_queue_t url_session_manager_creation_queue() { return af_url_session_manager_creation_queue; } +static void url_session_manager_create_task_safely(dispatch_block_t block) { + if (NSFoundationVersionNumber < NSFoundationVersionNumber_With_Fixed_5871104061079552_bug) { + // Fix of bug + // Open Radar:http://openradar.appspot.com/radar?id=5871104061079552 (status: Fixed in iOS8) + // Issue about:https://github.com/AFNetworking/AFNetworking/issues/2093 + dispatch_sync(url_session_manager_creation_queue(), block); + } else { + block(); + } +} + static dispatch_queue_t url_session_manager_processing_queue() { static dispatch_queue_t af_url_session_manager_processing_queue; static dispatch_once_t onceToken; @@ -60,21 +75,12 @@ static dispatch_group_t url_session_manager_completion_group() { NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate"; NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error"; -NSString * const AFNetworkingTaskDidStartNotification = @"com.alamofire.networking.task.resume"; // Deprecated -NSString * const AFNetworkingTaskDidFinishNotification = @"com.alamofire.networking.task.complete"; // Deprecated - NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error"; NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; -NSString * const AFNetworkingTaskDidFinishSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; // Deprecated -NSString * const AFNetworkingTaskDidFinishResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; // Deprecated -NSString * const AFNetworkingTaskDidFinishResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; // Deprecated -NSString * const AFNetworkingTaskDidFinishErrorKey = @"com.alamofire.networking.task.complete.error"; // Deprecated -NSString * const AFNetworkingTaskDidFinishAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; // Deprecated - static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock"; static NSUInteger const AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask = 3; @@ -100,17 +106,22 @@ static dispatch_group_t url_session_manager_completion_group() { typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location); typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite); typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes); +typedef void (^AFURLSessionTaskProgressBlock)(NSProgress *); typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error); + #pragma mark - @interface AFURLSessionManagerTaskDelegate : NSObject @property (nonatomic, weak) AFURLSessionManager *manager; @property (nonatomic, strong) NSMutableData *mutableData; -@property (nonatomic, strong) NSProgress *progress; +@property (nonatomic, strong) NSProgress *uploadProgress; +@property (nonatomic, strong) NSProgress *downloadProgress; @property (nonatomic, copy) NSURL *downloadFileURL; @property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; +@property (nonatomic, copy) AFURLSessionTaskProgressBlock uploadProgressBlock; +@property (nonatomic, copy) AFURLSessionTaskProgressBlock downloadProgressBlock; @property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler; @end @@ -123,24 +134,119 @@ - (instancetype)init { } self.mutableData = [NSMutableData data]; + self.uploadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; + self.uploadProgress.totalUnitCount = NSURLSessionTransferSizeUnknown; - self.progress = [NSProgress progressWithTotalUnitCount:0]; - + self.downloadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; + self.downloadProgress.totalUnitCount = NSURLSessionTransferSizeUnknown; return self; } -#pragma mark - NSURLSessionTaskDelegate +#pragma mark - NSProgress Tracking -- (void)URLSession:(__unused NSURLSession *)session - task:(__unused NSURLSessionTask *)task - didSendBodyData:(__unused int64_t)bytesSent - totalBytesSent:(int64_t)totalBytesSent -totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend -{ - self.progress.totalUnitCount = totalBytesExpectedToSend; - self.progress.completedUnitCount = totalBytesSent; +- (void)setupProgressForTask:(NSURLSessionTask *)task { + __weak __typeof__(task) weakTask = task; + + self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend; + self.downloadProgress.totalUnitCount = task.countOfBytesExpectedToReceive; + [self.uploadProgress setCancellable:YES]; + [self.uploadProgress setCancellationHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask cancel]; + }]; + [self.uploadProgress setPausable:YES]; + [self.uploadProgress setPausingHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask suspend]; + }]; + if ([self.uploadProgress respondsToSelector:@selector(setResumingHandler:)]) { + [self.uploadProgress setResumingHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask resume]; + }]; + } + + [self.downloadProgress setCancellable:YES]; + [self.downloadProgress setCancellationHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask cancel]; + }]; + [self.downloadProgress setPausable:YES]; + [self.downloadProgress setPausingHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask suspend]; + }]; + + if ([self.downloadProgress respondsToSelector:@selector(setResumingHandler:)]) { + [self.downloadProgress setResumingHandler:^{ + __typeof__(weakTask) strongTask = weakTask; + [strongTask resume]; + }]; + } + + [task addObserver:self + forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived)) + options:NSKeyValueObservingOptionNew + context:NULL]; + [task addObserver:self + forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToReceive)) + options:NSKeyValueObservingOptionNew + context:NULL]; + + [task addObserver:self + forKeyPath:NSStringFromSelector(@selector(countOfBytesSent)) + options:NSKeyValueObservingOptionNew + context:NULL]; + [task addObserver:self + forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToSend)) + options:NSKeyValueObservingOptionNew + context:NULL]; + + [self.downloadProgress addObserver:self + forKeyPath:NSStringFromSelector(@selector(fractionCompleted)) + options:NSKeyValueObservingOptionNew + context:NULL]; + [self.uploadProgress addObserver:self + forKeyPath:NSStringFromSelector(@selector(fractionCompleted)) + options:NSKeyValueObservingOptionNew + context:NULL]; +} + +- (void)cleanUpProgressForTask:(NSURLSessionTask *)task { + [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))]; + [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))]; + [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))]; + [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesExpectedToSend))]; + [self.downloadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))]; + [self.uploadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))]; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + if ([object isKindOfClass:[NSURLSessionTask class]] || [object isKindOfClass:[NSURLSessionDownloadTask class]]) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) { + self.downloadProgress.completedUnitCount = [change[@"new"] longLongValue]; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))]) { + self.downloadProgress.totalUnitCount = [change[@"new"] longLongValue]; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) { + self.uploadProgress.completedUnitCount = [change[@"new"] longLongValue]; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesExpectedToSend))]) { + self.uploadProgress.totalUnitCount = [change[@"new"] longLongValue]; + } + } + else if ([object isEqual:self.downloadProgress]) { + if (self.downloadProgressBlock) { + self.downloadProgressBlock(object); + } + } + else if ([object isEqual:self.uploadProgress]) { + if (self.uploadProgressBlock) { + self.uploadProgressBlock(object); + } + } } +#pragma mark - NSURLSessionTaskDelegate + - (void)URLSession:(__unused NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error @@ -154,10 +260,18 @@ - (void)URLSession:(__unused NSURLSession *)session __block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer; + //Performance Improvement from #2672 + NSData *data = nil; + if (self.mutableData) { + data = [self.mutableData copy]; + //We no longer need the reference, so nil it out to gain back some memory. + self.mutableData = nil; + } + if (self.downloadFileURL) { userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL; - } else if (self.mutableData) { - userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = [NSData dataWithData:self.mutableData]; + } else if (data) { + userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data; } if (error) { @@ -175,7 +289,7 @@ - (void)URLSession:(__unused NSURLSession *)session } else { dispatch_async(url_session_manager_processing_queue(), ^{ NSError *serializationError = nil; - responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:[NSData dataWithData:self.mutableData] error:&serializationError]; + responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError]; if (self.downloadFileURL) { responseObject = self.downloadFileURL; @@ -193,7 +307,7 @@ - (void)URLSession:(__unused NSURLSession *)session if (self.completionHandler) { self.completionHandler(task.response, responseObject, serializationError); } - + dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; }); @@ -233,24 +347,133 @@ - (void)URLSession:(NSURLSession *)session } } -- (void)URLSession:(__unused NSURLSession *)session - downloadTask:(__unused NSURLSessionDownloadTask *)downloadTask - didWriteData:(__unused int64_t)bytesWritten - totalBytesWritten:(int64_t)totalBytesWritten -totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite -{ - self.progress.totalUnitCount = totalBytesExpectedToWrite; - self.progress.completedUnitCount = totalBytesWritten; +@end + +#pragma mark - + +/** + * A workaround for issues related to key-value observing the `state` of an `NSURLSessionTask`. + * + * See: + * - https://github.com/AFNetworking/AFNetworking/issues/1477 + * - https://github.com/AFNetworking/AFNetworking/issues/2638 + * - https://github.com/AFNetworking/AFNetworking/pull/2702 + */ + +static inline void af_swizzleSelector(Class theClass, SEL originalSelector, SEL swizzledSelector) { + Method originalMethod = class_getInstanceMethod(theClass, originalSelector); + Method swizzledMethod = class_getInstanceMethod(theClass, swizzledSelector); + method_exchangeImplementations(originalMethod, swizzledMethod); } -- (void)URLSession:(__unused NSURLSession *)session - downloadTask:(__unused NSURLSessionDownloadTask *)downloadTask - didResumeAtOffset:(int64_t)fileOffset -expectedTotalBytes:(int64_t)expectedTotalBytes { - self.progress.totalUnitCount = expectedTotalBytes; - self.progress.completedUnitCount = fileOffset; +static inline BOOL af_addMethod(Class theClass, SEL selector, Method method) { + return class_addMethod(theClass, selector, method_getImplementation(method), method_getTypeEncoding(method)); } +static NSString * const AFNSURLSessionTaskDidResumeNotification = @"com.alamofire.networking.nsurlsessiontask.resume"; +static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofire.networking.nsurlsessiontask.suspend"; + +@interface _AFURLSessionTaskSwizzling : NSObject + +@end + +@implementation _AFURLSessionTaskSwizzling + ++ (void)load { + /** + WARNING: Trouble Ahead + https://github.com/AFNetworking/AFNetworking/pull/2702 + */ + + if (NSClassFromString(@"NSURLSessionTask")) { + /** + iOS 7 and iOS 8 differ in NSURLSessionTask implementation, which makes the next bit of code a bit tricky. + Many Unit Tests have been built to validate as much of this behavior has possible. + Here is what we know: + - NSURLSessionTasks are implemented with class clusters, meaning the class you request from the API isn't actually the type of class you will get back. + - Simply referencing `[NSURLSessionTask class]` will not work. You need to ask an `NSURLSession` to actually create an object, and grab the class from there. + - On iOS 7, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `__NSCFURLSessionTask`. + - On iOS 8, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `NSURLSessionTask`. + - On iOS 7, `__NSCFLocalSessionTask` and `__NSCFURLSessionTask` are the only two classes that have their own implementations of `resume` and `suspend`, and `__NSCFLocalSessionTask` DOES NOT CALL SUPER. This means both classes need to be swizzled. + - On iOS 8, `NSURLSessionTask` is the only class that implements `resume` and `suspend`. This means this is the only class that needs to be swizzled. + - Because `NSURLSessionTask` is not involved in the class hierarchy for every version of iOS, its easier to add the swizzled methods to a dummy class and manage them there. + + Some Assumptions: + - No implementations of `resume` or `suspend` call super. If this were to change in a future version of iOS, we'd need to handle it. + - No background task classes override `resume` or `suspend` + + The current solution: + 1) Grab an instance of `__NSCFLocalDataTask` by asking an instance of `NSURLSession` for a data task. + 2) Grab a pointer to the original implementation of `af_resume` + 3) Check to see if the current class has an implementation of resume. If so, continue to step 4. + 4) Grab the super class of the current class. + 5) Grab a pointer for the current class to the current implementation of `resume`. + 6) Grab a pointer for the super class to the current implementation of `resume`. + 7) If the current class implementation of `resume` is not equal to the super class implementation of `resume` AND the current implementation of `resume` is not equal to the original implementation of `af_resume`, THEN swizzle the methods + 8) Set the current class to the super class, and repeat steps 3-8 + */ + NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration]; + NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration]; +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnonnull" + NSURLSessionDataTask *localDataTask = [session dataTaskWithURL:nil]; +#pragma clang diagnostic pop + IMP originalAFResumeIMP = method_getImplementation(class_getInstanceMethod([self class], @selector(af_resume))); + Class currentClass = [localDataTask class]; + + while (class_getInstanceMethod(currentClass, @selector(resume))) { + Class superClass = [currentClass superclass]; + IMP classResumeIMP = method_getImplementation(class_getInstanceMethod(currentClass, @selector(resume))); + IMP superclassResumeIMP = method_getImplementation(class_getInstanceMethod(superClass, @selector(resume))); + if (classResumeIMP != superclassResumeIMP && + originalAFResumeIMP != classResumeIMP) { + [self swizzleResumeAndSuspendMethodForClass:currentClass]; + } + currentClass = [currentClass superclass]; + } + + [localDataTask cancel]; + [session finishTasksAndInvalidate]; + } +} + ++ (void)swizzleResumeAndSuspendMethodForClass:(Class)theClass { + Method afResumeMethod = class_getInstanceMethod(self, @selector(af_resume)); + Method afSuspendMethod = class_getInstanceMethod(self, @selector(af_suspend)); + + if (af_addMethod(theClass, @selector(af_resume), afResumeMethod)) { + af_swizzleSelector(theClass, @selector(resume), @selector(af_resume)); + } + + if (af_addMethod(theClass, @selector(af_suspend), afSuspendMethod)) { + af_swizzleSelector(theClass, @selector(suspend), @selector(af_suspend)); + } +} + +- (NSURLSessionTaskState)state { + NSAssert(NO, @"State method should never be called in the actual dummy class"); + return NSURLSessionTaskStateCanceling; +} + +- (void)af_resume { + NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state"); + NSURLSessionTaskState state = [self state]; + [self af_resume]; + + if (state != NSURLSessionTaskStateRunning) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidResumeNotification object:self]; + } +} + +- (void)af_suspend { + NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state"); + NSURLSessionTaskState state = [self state]; + [self af_suspend]; + + if (state != NSURLSessionTaskStateSuspended) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidSuspendNotification object:self]; + } +} @end #pragma mark - @@ -260,6 +483,7 @@ @interface AFURLSessionManager () @property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue; @property (readwrite, nonatomic, strong) NSURLSession *session; @property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier; +@property (readonly, nonatomic, copy) NSString *taskDescriptionForSessionTasks; @property (readwrite, nonatomic, strong) NSLock *lock; @property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid; @property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge; @@ -305,22 +529,24 @@ - (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)config self.securityPolicy = [AFSecurityPolicy defaultPolicy]; +#if !TARGET_OS_WATCH self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; +#endif self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init]; self.lock = [[NSLock alloc] init]; self.lock.name = AFURLSessionManagerLockName; - + [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { for (NSURLSessionDataTask *task in dataTasks) { - [self addDelegateForDataTask:task completionHandler:nil]; + [self addDelegateForDataTask:task uploadProgress:nil downloadProgress:nil completionHandler:nil]; } - + for (NSURLSessionUploadTask *uploadTask in uploadTasks) { [self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil]; } - + for (NSURLSessionDownloadTask *downloadTask in downloadTasks) { [self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil]; } @@ -329,6 +555,38 @@ - (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)config return self; } +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +#pragma mark - + +- (NSString *)taskDescriptionForSessionTasks { + return [NSString stringWithFormat:@"%p", self]; +} + +- (void)taskDidResume:(NSNotification *)notification { + NSURLSessionTask *task = notification.object; + if ([task respondsToSelector:@selector(taskDescription)]) { + if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidResumeNotification object:task]; + }); + } + } +} + +- (void)taskDidSuspend:(NSNotification *)notification { + NSURLSessionTask *task = notification.object; + if ([task respondsToSelector:@selector(taskDescription)]) { + if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidSuspendNotification object:task]; + }); + } + } +} + #pragma mark - - (AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task { @@ -348,55 +606,46 @@ - (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate NSParameterAssert(task); NSParameterAssert(delegate); - [task addObserver:self forKeyPath:NSStringFromSelector(@selector(state)) options:(NSKeyValueObservingOptions)(NSKeyValueObservingOptionOld |NSKeyValueObservingOptionNew) context:AFTaskStateChangedContext]; [self.lock lock]; self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate; + [delegate setupProgressForTask:task]; + [self addNotificationObserverForTask:task]; [self.lock unlock]; } - (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler { AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; delegate.manager = self; delegate.completionHandler = completionHandler; + dataTask.taskDescription = self.taskDescriptionForSessionTasks; [self setDelegate:delegate forTask:dataTask]; + + delegate.uploadProgressBlock = uploadProgressBlock; + delegate.downloadProgressBlock = downloadProgressBlock; } - (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask - progress:(NSProgress * __autoreleasing *)progress + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler { AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; delegate.manager = self; delegate.completionHandler = completionHandler; - int64_t totalUnitCount = uploadTask.countOfBytesExpectedToSend; - if(totalUnitCount == NSURLSessionTransferSizeUnknown) { - NSString *contentLength = [uploadTask.originalRequest valueForHTTPHeaderField:@"Content-Length"]; - if(contentLength) { - totalUnitCount = (int64_t) [contentLength longLongValue]; - } - } - - delegate.progress = [NSProgress progressWithTotalUnitCount:totalUnitCount]; - delegate.progress.pausingHandler = ^{ - [uploadTask suspend]; - }; - delegate.progress.cancellationHandler = ^{ - [uploadTask cancel]; - }; - - if (progress) { - *progress = delegate.progress; - } + uploadTask.taskDescription = self.taskDescriptionForSessionTasks; [self setDelegate:delegate forTask:uploadTask]; + + delegate.uploadProgressBlock = uploadProgressBlock; } - (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask - progress:(NSProgress * __autoreleasing *)progress + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler { @@ -410,28 +659,24 @@ - (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask }; } - if (progress) { - *progress = delegate.progress; - } + downloadTask.taskDescription = self.taskDescriptionForSessionTasks; [self setDelegate:delegate forTask:downloadTask]; + + delegate.downloadProgressBlock = downloadProgressBlock; } - (void)removeDelegateForTask:(NSURLSessionTask *)task { NSParameterAssert(task); - [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(state)) context:AFTaskStateChangedContext]; + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; [self.lock lock]; + [delegate cleanUpProgressForTask:task]; + [self removeNotificationObserverForTask:task]; [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)]; [self.lock unlock]; } -- (void)removeAllDelegates { - [self.lock lock]; - [self.mutableTaskDelegatesKeyedByTaskIdentifier removeAllObjects]; - [self.lock unlock]; -} - #pragma mark - - (NSArray *)tasksForKeyPath:(NSString *)keyPath { @@ -492,17 +737,36 @@ - (void)setResponseSerializer:(id )responseSerialize _responseSerializer = responseSerializer; } +#pragma mark - +- (void)addNotificationObserverForTask:(NSURLSessionTask *)task { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:task]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:task]; +} + +- (void)removeNotificationObserverForTask:(NSURLSessionTask *)task { + [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidSuspendNotification object:task]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidResumeNotification object:task]; +} + #pragma mark - - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler { + return [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:completionHandler]; +} + +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler { + __block NSURLSessionDataTask *dataTask = nil; - dispatch_sync(url_session_manager_creation_queue(), ^{ + url_session_manager_create_task_safely(^{ dataTask = [self.session dataTaskWithRequest:request]; }); - [self addDelegateForDataTask:dataTask completionHandler:completionHandler]; + [self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler]; return dataTask; } @@ -511,11 +775,11 @@ - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL - progress:(NSProgress * __autoreleasing *)progress + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler { __block NSURLSessionUploadTask *uploadTask = nil; - dispatch_sync(url_session_manager_creation_queue(), ^{ + url_session_manager_create_task_safely(^{ uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; }); @@ -525,36 +789,36 @@ - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request } } - [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler]; + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; return uploadTask; } - (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromData:(NSData *)bodyData - progress:(NSProgress * __autoreleasing *)progress + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler { __block NSURLSessionUploadTask *uploadTask = nil; - dispatch_sync(url_session_manager_creation_queue(), ^{ + url_session_manager_create_task_safely(^{ uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData]; }); - [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler]; + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; return uploadTask; } - (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request - progress:(NSProgress * __autoreleasing *)progress + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler { __block NSURLSessionUploadTask *uploadTask = nil; - dispatch_sync(url_session_manager_creation_queue(), ^{ + url_session_manager_create_task_safely(^{ uploadTask = [self.session uploadTaskWithStreamedRequest:request]; }); - [self addDelegateForUploadTask:uploadTask progress:progress completionHandler:completionHandler]; + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; return uploadTask; } @@ -562,43 +826,42 @@ - (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)reques #pragma mark - - (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request - progress:(NSProgress * __autoreleasing *)progress + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler { __block NSURLSessionDownloadTask *downloadTask = nil; - dispatch_sync(url_session_manager_creation_queue(), ^{ + url_session_manager_create_task_safely(^{ downloadTask = [self.session downloadTaskWithRequest:request]; }); - [self addDelegateForDownloadTask:downloadTask progress:progress destination:destination completionHandler:completionHandler]; + [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler]; return downloadTask; } - (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData - progress:(NSProgress * __autoreleasing *)progress + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler { __block NSURLSessionDownloadTask *downloadTask = nil; - dispatch_sync(url_session_manager_creation_queue(), ^{ + url_session_manager_create_task_safely(^{ downloadTask = [self.session downloadTaskWithResumeData:resumeData]; }); - [self addDelegateForDownloadTask:downloadTask progress:progress destination:destination completionHandler:completionHandler]; + [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler]; return downloadTask; } #pragma mark - - -- (NSProgress *)uploadProgressForTask:(NSURLSessionUploadTask *)uploadTask { - return [[self delegateForTask:uploadTask] progress]; +- (NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task { + return [[self delegateForTask:task] uploadProgress]; } -- (NSProgress *)downloadProgressForTask:(NSURLSessionDownloadTask *)downloadTask { - return [[self delegateForTask:downloadTask] progress]; +- (NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task { + return [[self delegateForTask:task] downloadProgress]; } #pragma mark - @@ -689,42 +952,6 @@ - (BOOL)respondsToSelector:(SEL)selector { return [[self class] instancesRespondToSelector:selector]; } -#pragma mark - NSKeyValueObserving - -- (void)observeValueForKeyPath:(NSString *)keyPath - ofObject:(id)object - change:(NSDictionary *)change - context:(void *)context -{ - if (context == AFTaskStateChangedContext && [keyPath isEqualToString:@"state"]) { - if (change[NSKeyValueChangeOldKey] && change[NSKeyValueChangeNewKey] && [change[NSKeyValueChangeNewKey] isEqual:change[NSKeyValueChangeOldKey]]) { - return; - } - - NSString *notificationName = nil; - switch ([(NSURLSessionTask *)object state]) { - case NSURLSessionTaskStateRunning: - notificationName = AFNetworkingTaskDidResumeNotification; - break; - case NSURLSessionTaskStateSuspended: - notificationName = AFNetworkingTaskDidSuspendNotification; - break; - case NSURLSessionTaskStateCompleted: - // AFNetworkingTaskDidFinishNotification posted by task completion handlers - default: - break; - } - - if (notificationName) { - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:object]; - }); - } - } else { - [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; - } -} - #pragma mark - NSURLSessionDelegate - (void)URLSession:(NSURLSession *)session @@ -734,15 +961,6 @@ - (void)URLSession:(NSURLSession *)session self.sessionDidBecomeInvalid(session, error); } - [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { - NSArray *tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"]; - for (NSURLSessionTask *task in tasks) { - [task removeObserver:self forKeyPath:NSStringFromSelector(@selector(state)) context:AFTaskStateChangedContext]; - } - - [self removeAllDelegates]; - }]; - [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session]; } @@ -765,7 +983,7 @@ - (void)URLSession:(NSURLSession *)session disposition = NSURLSessionAuthChallengePerformDefaultHandling; } } else { - disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; + disposition = NSURLSessionAuthChallengeRejectProtectionSpace; } } else { disposition = NSURLSessionAuthChallengePerformDefaultHandling; @@ -812,7 +1030,7 @@ - (void)URLSession:(NSURLSession *)session disposition = NSURLSessionAuthChallengeUseCredential; credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; } else { - disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; + disposition = NSURLSessionAuthChallengeRejectProtectionSpace; } } else { disposition = NSURLSessionAuthChallengePerformDefaultHandling; @@ -829,7 +1047,7 @@ - (void)URLSession:(NSURLSession *)session needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler { NSInputStream *inputStream = nil; - + if (self.taskNeedNewBodyStream) { inputStream = self.taskNeedNewBodyStream(session, task); } else if (task.originalRequest.HTTPBodyStream && [task.originalRequest.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) { @@ -847,7 +1065,7 @@ - (void)URLSession:(NSURLSession *)session totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { - + int64_t totalUnitCount = totalBytesExpectedToSend; if(totalUnitCount == NSURLSessionTransferSizeUnknown) { NSString *contentLength = [task.originalRequest valueForHTTPHeaderField:@"Content-Length"]; @@ -855,9 +1073,6 @@ - (void)URLSession:(NSURLSession *)session totalUnitCount = (int64_t) [contentLength longLongValue]; } } - - AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; - [delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalUnitCount]; if (self.taskDidSendBodyData) { self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalUnitCount); @@ -880,7 +1095,6 @@ - (void)URLSession:(NSURLSession *)session if (self.taskDidComplete) { self.taskDidComplete(session, task, error); } - } #pragma mark - NSURLSessionDataDelegate @@ -920,6 +1134,7 @@ - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; [delegate URLSession:session dataTask:dataTask didReceiveData:data]; @@ -958,9 +1173,11 @@ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; if (self.downloadTaskDidFinishDownloading) { NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); if (fileURL) { + delegate.downloadFileURL = fileURL; NSError *error = nil; [[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error]; if (error) { @@ -970,8 +1187,7 @@ - (void)URLSession:(NSURLSession *)session return; } } - - AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; + if (delegate) { [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location]; } @@ -983,9 +1199,6 @@ - (void)URLSession:(NSURLSession *)session totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { - AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; - [delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite]; - if (self.downloadTaskDidWriteData) { self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); } @@ -996,9 +1209,6 @@ - (void)URLSession:(NSURLSession *)session didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes { - AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; - [delegate URLSession:session downloadTask:downloadTask didResumeAtOffset:fileOffset expectedTotalBytes:expectedTotalBytes]; - if (self.downloadTaskDidResume) { self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes); } @@ -1010,7 +1220,7 @@ + (BOOL)supportsSecureCoding { return YES; } -- (id)initWithCoder:(NSCoder *)decoder { +- (instancetype)initWithCoder:(NSCoder *)decoder { NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; self = [self initWithSessionConfiguration:configuration]; @@ -1027,10 +1237,8 @@ - (void)encodeWithCoder:(NSCoder *)coder { #pragma mark - NSCopying -- (id)copyWithZone:(NSZone *)zone { +- (instancetype)copyWithZone:(NSZone *)zone { return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration]; } @end - -#endif diff --git a/src/ios/CordovaHttpPlugin.h b/src/ios/CordovaHttpPlugin.h index 445bc8ad..917349a2 100644 --- a/src/ios/CordovaHttpPlugin.h +++ b/src/ios/CordovaHttpPlugin.h @@ -1,14 +1,12 @@ #import #import -#import @interface CordovaHttpPlugin : CDVPlugin -- (void)useBasicAuth:(CDVInvokedUrlCommand*)command; -- (void)setHeader:(CDVInvokedUrlCommand*)command; - (void)enableSSLPinning:(CDVInvokedUrlCommand*)command; - (void)acceptAllCerts:(CDVInvokedUrlCommand*)command; +- (void)validateDomainName:(CDVInvokedUrlCommand*)command; - (void)post:(CDVInvokedUrlCommand*)command; - (void)get:(CDVInvokedUrlCommand*)command; - (void)uploadFile:(CDVInvokedUrlCommand*)command; diff --git a/src/ios/CordovaHttpPlugin.m b/src/ios/CordovaHttpPlugin.m index 54de660d..cc0ef243 100644 --- a/src/ios/CordovaHttpPlugin.m +++ b/src/ios/CordovaHttpPlugin.m @@ -1,60 +1,45 @@ #import "CordovaHttpPlugin.h" #import "CDVFile.h" #import "TextResponseSerializer.h" -#import "HttpManager.h" +#import "AFHTTPSessionManager.h" @interface CordovaHttpPlugin() -- (void)setRequestHeaders:(NSDictionary*)headers; +- (void)setRequestHeaders:(NSDictionary*)headers forManager:(AFHTTPSessionManager*)manager; +- (void)setResults:(NSMutableDictionary*)dictionary withTask:(NSURLSessionTask*)task; @end @implementation CordovaHttpPlugin { - AFHTTPRequestSerializer *requestSerializer; + AFSecurityPolicy *securityPolicy; } - (void)pluginInitialize { - requestSerializer = [AFHTTPRequestSerializer serializer]; + securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; } -- (void)setRequestHeaders:(NSDictionary*)headers { - [HttpManager sharedClient].requestSerializer = [AFHTTPRequestSerializer serializer]; - [requestSerializer.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - [[HttpManager sharedClient].requestSerializer setValue:obj forHTTPHeaderField:key]; - }]; +- (void)setRequestHeaders:(NSDictionary*)headers forManager:(AFHTTPSessionManager*)manager { + manager.requestSerializer = [AFHTTPRequestSerializer serializer]; [headers enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - [[HttpManager sharedClient].requestSerializer setValue:obj forHTTPHeaderField:key]; + [manager.requestSerializer setValue:obj forHTTPHeaderField:key]; }]; } -- (void)useBasicAuth:(CDVInvokedUrlCommand*)command { - NSString *username = [command.arguments objectAtIndex:0]; - NSString *password = [command.arguments objectAtIndex:1]; - - [requestSerializer setAuthorizationHeaderFieldWithUsername:username password:password]; - - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; -} - -- (void)setHeader:(CDVInvokedUrlCommand*)command { - NSString *header = [command.arguments objectAtIndex:0]; - NSString *value = [command.arguments objectAtIndex:1]; - - [requestSerializer setValue:value forHTTPHeaderField: header]; - - CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; +- (void)setResults:(NSMutableDictionary*)dictionary withTask:(NSURLSessionTask*)task { + if (task.response != nil) { + NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response; + [dictionary setObject:[NSNumber numberWithInt:response.statusCode] forKey:@"status"]; + [dictionary setObject:response.allHeaderFields forKey:@"headers"]; + } } - (void)enableSSLPinning:(CDVInvokedUrlCommand*)command { bool enable = [[command.arguments objectAtIndex:0] boolValue]; if (enable) { - [HttpManager sharedClient].securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; - [HttpManager sharedClient].securityPolicy.validatesCertificateChain = NO; + securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate]; } else { - [HttpManager sharedClient].securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; + securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; } CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; @@ -65,72 +50,111 @@ - (void)acceptAllCerts:(CDVInvokedUrlCommand*)command { CDVPluginResult* pluginResult = nil; bool allow = [[command.arguments objectAtIndex:0] boolValue]; - [HttpManager sharedClient].securityPolicy.allowInvalidCertificates = allow; + securityPolicy.allowInvalidCertificates = allow; + + pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; + [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; +} + +- (void)validateDomainName:(CDVInvokedUrlCommand*)command { + CDVPluginResult* pluginResult = nil; + bool validate = [[command.arguments objectAtIndex:0] boolValue]; + + securityPolicy.validatesDomainName = validate; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } - (void)post:(CDVInvokedUrlCommand*)command { - HttpManager *manager = [HttpManager sharedClient]; - NSString *url = [command.arguments objectAtIndex:0]; - NSDictionary *parameters = [command.arguments objectAtIndex:1]; - NSDictionary *headers = [command.arguments objectAtIndex:2]; - [self setRequestHeaders: headers]; + AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; + manager.securityPolicy = securityPolicy; + NSString *url = [command.arguments objectAtIndex:0]; + NSDictionary *parameters = [command.arguments objectAtIndex:1]; + NSDictionary *headers = [command.arguments objectAtIndex:2]; + [self setRequestHeaders: headers forManager: manager]; - CordovaHttpPlugin* __weak weakSelf = self; - manager.responseSerializer = [TextResponseSerializer serializer]; - [manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { - NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"]; - [dictionary setObject:responseObject forKey:@"data"]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary]; - [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"]; - [dictionary setObject:[error localizedDescription] forKey:@"error"]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary]; - [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }]; + CordovaHttpPlugin* __weak weakSelf = self; + manager.responseSerializer = [TextResponseSerializer serializer]; + [manager POST:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) { + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + [self setResults: dictionary withTask: task]; + [dictionary setObject:responseObject forKey:@"data"]; + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary]; + [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + } failure:^(NSURLSessionTask *task, NSError *error) { + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + [self setResults: dictionary withTask: task]; + [dictionary setObject:[error localizedDescription] forKey:@"error"]; + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary]; + [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }]; } - (void)get:(CDVInvokedUrlCommand*)command { - HttpManager *manager = [HttpManager sharedClient]; - NSString *url = [command.arguments objectAtIndex:0]; - NSDictionary *parameters = [command.arguments objectAtIndex:1]; - NSDictionary *headers = [command.arguments objectAtIndex:2]; - [self setRequestHeaders: headers]; + AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; + manager.securityPolicy = securityPolicy; + NSString *url = [command.arguments objectAtIndex:0]; + NSDictionary *parameters = [command.arguments objectAtIndex:1]; + NSDictionary *headers = [command.arguments objectAtIndex:2]; + [self setRequestHeaders: headers forManager: manager]; - CordovaHttpPlugin* __weak weakSelf = self; + CordovaHttpPlugin* __weak weakSelf = self; - manager.responseSerializer = [TextResponseSerializer serializer]; - [manager GET:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { - NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"]; - [dictionary setObject:responseObject forKey:@"data"]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary]; - [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"]; - [dictionary setObject:[error localizedDescription] forKey:@"error"]; - CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary]; - [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - }]; + manager.responseSerializer = [TextResponseSerializer serializer]; + [manager GET:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) { + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + [self setResults: dictionary withTask: task]; + [dictionary setObject:responseObject forKey:@"data"]; + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary]; + [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + } failure:^(NSURLSessionTask *task, NSError *error) { + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + [self setResults: dictionary withTask: task]; + [dictionary setObject:[error localizedDescription] forKey:@"error"]; + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary]; + [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }]; +} + +- (void)head:(CDVInvokedUrlCommand*)command { + AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; + manager.securityPolicy = securityPolicy; + NSString *url = [command.arguments objectAtIndex:0]; + NSDictionary *parameters = [command.arguments objectAtIndex:1]; + NSDictionary *headers = [command.arguments objectAtIndex:2]; + [self setRequestHeaders: headers forManager: manager]; + + CordovaHttpPlugin* __weak weakSelf = self; + + manager.responseSerializer = [AFHTTPResponseSerializer serializer]; + [manager HEAD:url parameters:parameters success:^(NSURLSessionTask *task) { + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + [self setResults: dictionary withTask: task]; + // no 'body' for HEAD request, omitting 'data' + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary]; + [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + } failure:^(NSURLSessionTask *task, NSError *error) { + NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; + [self setResults: dictionary withTask: task]; + [dictionary setObject:[error localizedDescription] forKey:@"error"]; + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary]; + [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; + }]; } - (void)uploadFile:(CDVInvokedUrlCommand*)command { - HttpManager *manager = [HttpManager sharedClient]; + AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; + manager.securityPolicy = securityPolicy; NSString *url = [command.arguments objectAtIndex:0]; NSDictionary *parameters = [command.arguments objectAtIndex:1]; NSDictionary *headers = [command.arguments objectAtIndex:2]; NSString *filePath = [command.arguments objectAtIndex: 3]; NSString *name = [command.arguments objectAtIndex: 4]; - NSURL *fileURL = [NSURL fileURLWithPath: filePath]; + NSURL *fileURL = [NSURL URLWithString: filePath]; - [self setRequestHeaders: headers]; + [self setRequestHeaders: headers forManager: manager]; CordovaHttpPlugin* __weak weakSelf = self; manager.responseSerializer = [TextResponseSerializer serializer]; @@ -140,19 +164,19 @@ - (void)uploadFile:(CDVInvokedUrlCommand*)command { if (error) { NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; [dictionary setObject:[NSNumber numberWithInt:500] forKey:@"status"]; - [dictionary setObject:@"Could not add image to post body." forKey:@"error"]; + [dictionary setObject:@"Could not add file to post body." forKey:@"error"]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary]; [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; return; } - } success:^(AFHTTPRequestOperation *operation, id responseObject) { + } progress:nil success:^(NSURLSessionTask *task, id responseObject) { NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"]; + [self setResults: dictionary withTask: task]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary]; [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + } failure:^(NSURLSessionTask *task, NSError *error) { NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"]; + [self setResults: dictionary withTask: task]; [dictionary setObject:[error localizedDescription] forKey:@"error"]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary]; [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; @@ -161,17 +185,22 @@ - (void)uploadFile:(CDVInvokedUrlCommand*)command { - (void)downloadFile:(CDVInvokedUrlCommand*)command { - HttpManager *manager = [HttpManager sharedClient]; + AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; + manager.securityPolicy = securityPolicy; NSString *url = [command.arguments objectAtIndex:0]; NSDictionary *parameters = [command.arguments objectAtIndex:1]; NSDictionary *headers = [command.arguments objectAtIndex:2]; NSString *filePath = [command.arguments objectAtIndex: 3]; - [self setRequestHeaders: headers]; + [self setRequestHeaders: headers forManager: manager]; + + if ([filePath hasPrefix:@"file://"]) { + filePath = [filePath substringFromIndex:7]; + } CordovaHttpPlugin* __weak weakSelf = self; manager.responseSerializer = [AFHTTPResponseSerializer serializer]; - [manager GET:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) { + [manager GET:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) { /* * * Licensed to the Apache Software Foundation (ASF) under one @@ -221,15 +250,15 @@ - (void)downloadFile:(CDVInvokedUrlCommand*)command { return; } - CDVFile *file = [[CDVFile alloc] init]; + id filePlugin = [self.commandDelegate getCommandInstance:@"File"]; NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"]; - [dictionary setObject:[file getDirectoryEntry:filePath isDirectory:NO] forKey:@"file"]; + [self setResults: dictionary withTask: task]; + [dictionary setObject:[filePlugin getDirectoryEntry:filePath isDirectory:NO] forKey:@"file"]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary]; [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + } failure:^(NSURLSessionTask *task, NSError *error) { NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; - [dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"]; + [self setResults: dictionary withTask: task]; [dictionary setObject:[error localizedDescription] forKey:@"error"]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary]; [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; diff --git a/src/ios/HTTPManager.h b/src/ios/HTTPManager.h deleted file mode 100644 index e4633d2f..00000000 --- a/src/ios/HTTPManager.h +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) 2012 Mattt Thompson (http://mattt.me/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// Modified by Andrew Stephan -#import -#import "AFHTTPRequestOperationManager.h" - -@interface HttpManager : AFHTTPRequestOperationManager - -+ (instancetype)sharedClient; - -@end \ No newline at end of file diff --git a/src/ios/HTTPManager.m b/src/ios/HTTPManager.m deleted file mode 100644 index 5d2b2944..00000000 --- a/src/ios/HTTPManager.m +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2012 Mattt Thompson (http://mattt.me/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// Modified by Andrew Stephan -#import "HttpManager.h" - -@implementation HttpManager - -+ (instancetype)sharedClient { - static HttpManager *_sharedClient = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - _sharedClient = [HttpManager manager]; - }); - - return _sharedClient; -} - -@end \ No newline at end of file diff --git a/www/cordovaHTTP.js b/www/cordovaHTTP.js index a879e208..92942c26 100644 --- a/www/cordovaHTTP.js +++ b/www/cordovaHTTP.js @@ -6,12 +6,36 @@ var exec = require('cordova/exec'); +// Thanks Mozilla: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_.22Unicode_Problem.22 +function b64EncodeUnicode(str) { + return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) { + return String.fromCharCode('0x' + p1); + })); +} + +function mergeHeaders(globalHeaders, localHeaders) { + var globalKeys = Object.keys(globalHeaders); + var key; + for (var i = 0; i < globalKeys.length; i++) { + key = globalKeys[i]; + if (!localHeaders.hasOwnProperty(key)) { + localHeaders[key] = globalHeaders[key]; + } + } + return localHeaders; +} + var http = { - useBasicAuth: function(username, password, success, failure) { - return exec(success, failure, "CordovaHttpPlugin", "useBasicAuth", [username, password]); + headers: {}, + sslPinning: false, + getBasicAuthHeader: function(username, password) { + return {'Authorization': 'Basic ' + b64EncodeUnicode(username + ':' + password)}; + }, + useBasicAuth: function(username, password) { + this.headers.Authorization = 'Basic ' + b64EncodeUnicode(username + ':' + password); }, - setHeader: function(header, value, success, failure) { - return exec(success, failure, "CordovaHttpPlugin", "setHeader", [header, value]); + setHeader: function(header, value) { + this.headers[header] = value; }, enableSSLPinning: function(enable, success, failure) { return exec(success, failure, "CordovaHttpPlugin", "enableSSLPinning", [enable]); @@ -19,13 +43,23 @@ var http = { acceptAllCerts: function(allow, success, failure) { return exec(success, failure, "CordovaHttpPlugin", "acceptAllCerts", [allow]); }, + validateDomainName: function(validate, success, failure) { + return exec(success, failure, "CordovaHttpPlugin", "validateDomainName", [validate]); + }, post: function(url, params, headers, success, failure) { + headers = mergeHeaders(this.headers, headers); return exec(success, failure, "CordovaHttpPlugin", "post", [url, params, headers]); }, get: function(url, params, headers, success, failure) { + headers = mergeHeaders(this.headers, headers); return exec(success, failure, "CordovaHttpPlugin", "get", [url, params, headers]); }, + head: function(url, params, headers, success, failure) { + headers = mergeHeaders(this.headers, headers); + return exec(success, failure, "CordovaHttpPlugin", "head", [url, params, headers]); + }, uploadFile: function(url, params, headers, filePath, name, success, failure) { + headers = mergeHeaders(this.headers, headers); return exec(success, failure, "CordovaHttpPlugin", "uploadFile", [url, params, headers, filePath, name]); }, downloadFile: function(url, params, headers, filePath, success, failure) { @@ -51,12 +85,15 @@ var http = { * Modified by Andrew Stephan for Sync OnSet * */ + headers = mergeHeaders(this.headers, headers); var win = function(result) { - var entry = new (require('org.apache.cordova.file.FileEntry'))(); + var entry = new (require('cordova-plugin-file.FileEntry'))(); entry.isDirectory = false; entry.isFile = true; entry.name = result.file.name; entry.fullPath = result.file.fullPath; + entry.filesystem = new FileSystem(result.file.filesystemName || (result.file.filesystem == window.PERSISTENT ? 'persistent' : 'temporary')); + entry.nativeURL = result.file.nativeURL; success(entry); }; return exec(win, failure, "CordovaHttpPlugin", "downloadFile", [url, params, headers, filePath]); @@ -99,24 +136,27 @@ if (typeof angular !== "undefined") { } var cordovaHTTP = { - useBasicAuth: function(username, password) { - return makePromise(http.useBasicAuth, [username, password]); - }, - setHeader: function(header, value) { - return makePromise(http.setHeader, [header, value]); - }, + getBasicAuthHeader: http.getBasicAuthHeader, + useBasicAuth: http.useBasicAuth, + setHeader: http.setHeader, enableSSLPinning: function(enable) { return makePromise(http.enableSSLPinning, [enable]); }, acceptAllCerts: function(allow) { return makePromise(http.acceptAllCerts, [allow]); }, + validateDomainName: function(validate) { + return makePromise(http.validateDomainName, [validate]); + }, post: function(url, params, headers) { return makePromise(http.post, [url, params, headers], true); }, get: function(url, params, headers) { return makePromise(http.get, [url, params, headers], true); }, + head: function(url, params, headers) { + return makePromise(http.head, [url, params, headers], true); + }, uploadFile: function(url, params, headers, filePath, name) { return makePromise(http.uploadFile, [url, params, headers, filePath, name], true); }, diff --git a/zedconfig.json b/zedconfig.json new file mode 100644 index 00000000..3f52390a --- /dev/null +++ b/zedconfig.json @@ -0,0 +1,33 @@ +{ + "preferences": { + "tabSize": 4, + "wordWrap": true, + "useSoftTabs": true, + "gotoExclude": [] + }, + "packages": [ + "gh:wymsee/zed-tools/mobile" + ], + "modes": { + "javascript": { + "commands": { + "Tools:Check": { + "options": { + "globals": { + "angular": true, + "$": true, + "device": true, + "persistence": true, + "moment": true, + "sos": true, + "LocalFileSystem": true, + "Hammer": true, + "AnimationFrame": true, + "Bloodhound": true + } + } + } + } + } + } +} \ No newline at end of file