diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..95571f6 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @studyplus/client diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..3e0be03 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,18 @@ +version: 2 +updates: + # workflow の action(SHA 固定)を更新する。SHA と末尾の # vX.Y.Z コメントを合わせて書き換えた PR が作られる + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" + time: "10:00" + timezone: "Asia/Tokyo" + cooldown: + default-days: 10 + open-pull-requests-limit: 10 + groups: + github-actions: + patterns: + - "*" + commit-message: + prefix: "chore(deps)" diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml new file mode 100644 index 0000000..52dded6 --- /dev/null +++ b/.github/workflows/pr.yml @@ -0,0 +1,22 @@ +name: PR check + +on: pull_request + +permissions: + contents: read + +jobs: + danger: + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write # Danger が PR にコメントするため + issues: read # Danger が PR の情報(ラベル等)を issues API で読むため + statuses: write # Danger が結果をコミットステータスに付けるため + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Danger(SwiftLint) + uses: docker://ghcr.io/danger/danger-swift-with-swiftlint@sha256:2ad66810ba60c21eacae54e698e690ddd9fa61073253b19dc68dadc3b8f2a71b # 3.8.0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore index a5f5a4a..31a1d3f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,29 @@ -build/archives -build/**/working -xcuserdata -Pods -xcshareddata -nowbuilding.lock -Podfile.lock -.DS_Store +## Build generated +build/ +DerivedData/ + +# Swift Package Manager +.build/ + +## Various settings +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata/ + +## Obj-C/Swift specific +*.hmap +*.ipa +*.dSYM.zip +*.dSYM + +## Other +*.moved-aside +*.xccheckout +*.xcscmblueprint +*.DS_Store diff --git a/.swiftlint.yml b/.swiftlint.yml new file mode 100644 index 0000000..cad2be7 --- /dev/null +++ b/.swiftlint.yml @@ -0,0 +1,2 @@ +excluded: +- .build/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..1a0147e --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,17 @@ +4.0.0 Release notes (2021-04-01) +============================================================= + +### API Breaking Changes + +* Change supported OS to iOS 11 or above. +* Renewed public API. See StudyplusAPI, StudypusRecord, StudyplusLoginDelegate, StudyplusError. + +### Enhancements + +* Supports Swift Package Manager. +* Code format. +* Update README. + +### Bugfixes + +* None. diff --git a/Dangerfile.swift b/Dangerfile.swift new file mode 100644 index 0000000..6acbddc --- /dev/null +++ b/Dangerfile.swift @@ -0,0 +1,6 @@ +import Danger +import Foundation + +let danger = Danger() + +SwiftLint.lint(.modifiedAndCreatedFiles(directory: nil), inline: true, configFile: ".swiftlint.yml") diff --git a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFHTTPSessionManager.h b/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFHTTPSessionManager.h deleted file mode 100644 index 5ce279a..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFHTTPSessionManager.h +++ /dev/null @@ -1,295 +0,0 @@ -// AFHTTPSessionManager.h -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#if !TARGET_OS_WATCH -#import -#endif -#import - -#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV -#import -#else -#import -#endif - -#import "AFURLSessionManager.h" - -/** - `AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths. - - ## Subclassing Notes - - Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application. - - For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect. - - ## Methods to Override - - To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:completionHandler:`. - - ## Serialization - - Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to ``. - - Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `` - - ## URL Construction Using Relative Paths - - For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`. - - Below are a few examples of how `baseURL` and relative paths interact: - - NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]; - [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo - [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz - [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo - [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo - [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/ - [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/ - - Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash. - - @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. - */ - -NS_ASSUME_NONNULL_BEGIN - -@interface AFHTTPSessionManager : AFURLSessionManager - -/** - The URL used to construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. - */ -@property (readonly, nonatomic, strong, nullable) NSURL *baseURL; - -/** - Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies. - - @warning `requestSerializer` must not be `nil`. - */ -@property (nonatomic, strong) AFHTTPRequestSerializer * requestSerializer; - -/** - Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`. - - @warning `responseSerializer` must not be `nil`. - */ -@property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; - -///--------------------- -/// @name Initialization -///--------------------- - -/** - Creates and returns an `AFHTTPSessionManager` object. - */ -+ (instancetype)manager; - -/** - Initializes an `AFHTTPSessionManager` object with the specified base URL. - - @param url The base URL for the HTTP client. - - @return The newly-initialized HTTP client - */ -- (instancetype)initWithBaseURL:(nullable NSURL *)url; - -/** - Initializes an `AFHTTPSessionManager` object with the specified base URL. - - This is the designated initializer. - - @param url The base URL for the HTTP client. - @param configuration The configuration used to create the managed session. - - @return The newly-initialized HTTP client - */ -- (instancetype)initWithBaseURL:(nullable NSURL *)url - sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; - -///--------------------------- -/// @name Making HTTP Requests -///--------------------------- - -/** - Creates and runs an `NSURLSessionDataTask` with a `GET` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. - @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. - - @see -dataTaskWithRequest:completionHandler: - */ -- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString - parameters:(nullable id)parameters - success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success - failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; - - -/** - Creates and runs an `NSURLSessionDataTask` with a `GET` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. - @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. - @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. - - @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: - */ -- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString - parameters:(nullable id)parameters - progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress - success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success - failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; - -/** - Creates and runs an `NSURLSessionDataTask` with a `HEAD` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the task finishes successfully. This block has no return value and takes a single arguments: the data task. - @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. - - @see -dataTaskWithRequest:completionHandler: - */ -- (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString - parameters:(nullable id)parameters - success:(nullable void (^)(NSURLSessionDataTask *task))success - failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; - -/** - Creates and runs an `NSURLSessionDataTask` with a `POST` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. - @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. - - @see -dataTaskWithRequest:completionHandler: - */ -- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString - parameters:(nullable id)parameters - success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success - failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; - -/** - Creates and runs an `NSURLSessionDataTask` with a `POST` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. - @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. - @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. - - @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: - */ -- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString - parameters:(nullable id)parameters - progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress - success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success - failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; - -/** - Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. - @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. - @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. - - @see -dataTaskWithRequest:completionHandler: - */ -- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString - parameters:(nullable id)parameters - constructingBodyWithBlock:(nullable void (^)(id formData))block - success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success - failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure DEPRECATED_ATTRIBUTE; - -/** - Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. - @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. - @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. - @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. - - @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: - */ -- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString - parameters:(nullable id)parameters - constructingBodyWithBlock:(nullable void (^)(id formData))block - progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress - success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success - failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; - -/** - Creates and runs an `NSURLSessionDataTask` with a `PUT` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. - @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. - - @see -dataTaskWithRequest:completionHandler: - */ -- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString - parameters:(nullable id)parameters - success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success - failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; - -/** - Creates and runs an `NSURLSessionDataTask` with a `PATCH` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. - @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. - - @see -dataTaskWithRequest:completionHandler: - */ -- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString - parameters:(nullable id)parameters - success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success - failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; - -/** - Creates and runs an `NSURLSessionDataTask` with a `DELETE` request. - - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded according to the client request serializer. - @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. - @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. - - @see -dataTaskWithRequest:completionHandler: - */ -- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString - parameters:(nullable id)parameters - success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success - failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFHTTPSessionManager.m b/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFHTTPSessionManager.m deleted file mode 100644 index 2591070..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFHTTPSessionManager.m +++ /dev/null @@ -1,361 +0,0 @@ -// AFHTTPSessionManager.m -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFHTTPSessionManager.h" - -#import "AFURLRequestSerialization.h" -#import "AFURLResponseSerialization.h" - -#import -#import -#import - -#import -#import -#import -#import -#import - -#if TARGET_OS_IOS || TARGET_OS_TV -#import -#elif TARGET_OS_WATCH -#import -#endif - -@interface AFHTTPSessionManager () -@property (readwrite, nonatomic, strong) NSURL *baseURL; -@end - -@implementation AFHTTPSessionManager -@dynamic responseSerializer; - -+ (instancetype)manager { - return [[[self class] alloc] initWithBaseURL:nil]; -} - -- (instancetype)init { - return [self initWithBaseURL:nil]; -} - -- (instancetype)initWithBaseURL:(NSURL *)url { - return [self initWithBaseURL:url sessionConfiguration:nil]; -} - -- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { - return [self initWithBaseURL:nil sessionConfiguration:configuration]; -} - -- (instancetype)initWithBaseURL:(NSURL *)url - sessionConfiguration:(NSURLSessionConfiguration *)configuration -{ - self = [super initWithSessionConfiguration:configuration]; - if (!self) { - return nil; - } - - // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected - if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { - url = [url URLByAppendingPathComponent:@""]; - } - - self.baseURL = url; - - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - self.responseSerializer = [AFJSONResponseSerializer serializer]; - - return self; -} - -#pragma mark - - -- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { - NSParameterAssert(requestSerializer); - - _requestSerializer = requestSerializer; -} - -- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { - NSParameterAssert(responseSerializer); - - [super setResponseSerializer:responseSerializer]; -} - -#pragma mark - - -- (NSURLSessionDataTask *)GET:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure -{ - - return [self GET:URLString parameters:parameters progress:nil success:success failure:failure]; -} - -- (NSURLSessionDataTask *)GET:(NSString *)URLString - parameters:(id)parameters - progress:(void (^)(NSProgress * _Nonnull))downloadProgress - success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success - failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure -{ - - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" - URLString:URLString - parameters:parameters - uploadProgress:nil - downloadProgress:downloadProgress - success:success - failure:failure]; - - [dataTask resume]; - - return dataTask; -} - -- (NSURLSessionDataTask *)HEAD:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure -{ - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) { - if (success) { - success(task); - } - } failure:failure]; - - [dataTask resume]; - - return dataTask; -} - -- (NSURLSessionDataTask *)POST:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure -{ - return [self POST:URLString parameters:parameters progress:nil success:success failure:failure]; -} - -- (NSURLSessionDataTask *)POST:(NSString *)URLString - parameters:(id)parameters - progress:(void (^)(NSProgress * _Nonnull))uploadProgress - success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success - failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure -{ - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure]; - - [dataTask resume]; - - return dataTask; -} - -- (NSURLSessionDataTask *)POST:(NSString *)URLString - parameters:(nullable id)parameters - constructingBodyWithBlock:(nullable void (^)(id _Nonnull))block - success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success - failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure -{ - return [self POST:URLString parameters:parameters constructingBodyWithBlock:block progress:nil success:success failure:failure]; -} - -- (NSURLSessionDataTask *)POST:(NSString *)URLString - parameters:(id)parameters - constructingBodyWithBlock:(void (^)(id formData))block - progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure -{ - NSError *serializationError = nil; - NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError]; - if (serializationError) { - if (failure) { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ - failure(nil, serializationError); - }); -#pragma clang diagnostic pop - } - - return nil; - } - - __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { - if (error) { - if (failure) { - failure(task, error); - } - } else { - if (success) { - success(task, responseObject); - } - } - }]; - - [task resume]; - - return task; -} - -- (NSURLSessionDataTask *)PUT:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure -{ - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; - - [dataTask resume]; - - return dataTask; -} - -- (NSURLSessionDataTask *)PATCH:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure -{ - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; - - [dataTask resume]; - - return dataTask; -} - -- (NSURLSessionDataTask *)DELETE:(NSString *)URLString - parameters:(id)parameters - success:(void (^)(NSURLSessionDataTask *task, id responseObject))success - failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure -{ - NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure]; - - [dataTask resume]; - - return dataTask; -} - -- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(id)parameters - uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress - downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress - success:(void (^)(NSURLSessionDataTask *, id))success - failure:(void (^)(NSURLSessionDataTask *, NSError *))failure -{ - NSError *serializationError = nil; - NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError]; - if (serializationError) { - if (failure) { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ - failure(nil, serializationError); - }); -#pragma clang diagnostic pop - } - - return nil; - } - - __block NSURLSessionDataTask *dataTask = nil; - dataTask = [self dataTaskWithRequest:request - uploadProgress:uploadProgress - downloadProgress:downloadProgress - completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { - if (error) { - if (failure) { - failure(dataTask, error); - } - } else { - if (success) { - success(dataTask, responseObject); - } - } - }]; - - return dataTask; -} - -#pragma mark - NSObject - -- (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue]; -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (instancetype)initWithCoder:(NSCoder *)decoder { - NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))]; - NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; - if (!configuration) { - NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"]; - if (configurationIdentifier) { -#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1100) - configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier]; -#else - configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier]; -#endif - } - } - - self = [self initWithBaseURL:baseURL sessionConfiguration:configuration]; - if (!self) { - return nil; - } - - self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; - self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; - AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))]; - if (decodedPolicy) { - self.securityPolicy = decodedPolicy; - } - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))]; - if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) { - [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; - } else { - [coder encodeObject:self.session.configuration.identifier forKey:@"identifier"]; - } - [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; - [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; - [coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))]; -} - -#pragma mark - NSCopying - -- (instancetype)copyWithZone:(NSZone *)zone { - AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration]; - - HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; - HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; - HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone]; - return HTTPClient; -} - -@end diff --git a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h b/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h deleted file mode 100644 index 0feb18d..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h +++ /dev/null @@ -1,206 +0,0 @@ -// AFNetworkReachabilityManager.h -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#if !TARGET_OS_WATCH -#import - -typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { - AFNetworkReachabilityStatusUnknown = -1, - AFNetworkReachabilityStatusNotReachable = 0, - AFNetworkReachabilityStatusReachableViaWWAN = 1, - AFNetworkReachabilityStatusReachableViaWiFi = 2, -}; - -NS_ASSUME_NONNULL_BEGIN - -/** - `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. - - Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability. - - See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ ) - - @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined. - */ -@interface AFNetworkReachabilityManager : NSObject - -/** - The current network reachability status. - */ -@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; - -/** - Whether or not the network is currently reachable. - */ -@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable; - -/** - Whether or not the network is currently reachable via WWAN. - */ -@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN; - -/** - Whether or not the network is currently reachable via WiFi. - */ -@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi; - -///--------------------- -/// @name Initialization -///--------------------- - -/** - Returns the shared network reachability manager. - */ -+ (instancetype)sharedManager; - -/** - Creates and returns a network reachability manager with the default socket address. - - @return An initialized network reachability manager, actively monitoring the default socket address. - */ -+ (instancetype)manager; - -/** - Creates and returns a network reachability manager for the specified domain. - - @param domain The domain used to evaluate network reachability. - - @return An initialized network reachability manager, actively monitoring the specified domain. - */ -+ (instancetype)managerForDomain:(NSString *)domain; - -/** - Creates and returns a network reachability manager for the socket address. - - @param address The socket address (`sockaddr_in6`) used to evaluate network reachability. - - @return An initialized network reachability manager, actively monitoring the specified socket address. - */ -+ (instancetype)managerForAddress:(const void *)address; - -/** - Initializes an instance of a network reachability manager from the specified reachability object. - - @param reachability The reachability object to monitor. - - @return An initialized network reachability manager, actively monitoring the specified reachability. - */ -- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER; - -///-------------------------------------------------- -/// @name Starting & Stopping Reachability Monitoring -///-------------------------------------------------- - -/** - Starts monitoring for changes in network reachability status. - */ -- (void)startMonitoring; - -/** - Stops monitoring for changes in network reachability status. - */ -- (void)stopMonitoring; - -///------------------------------------------------- -/// @name Getting Localized Reachability Description -///------------------------------------------------- - -/** - Returns a localized string representation of the current network reachability status. - */ -- (NSString *)localizedNetworkReachabilityStatusString; - -///--------------------------------------------------- -/// @name Setting Network Reachability Change Callback -///--------------------------------------------------- - -/** - Sets a callback to be executed when the network availability of the `baseURL` host changes. - - @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`. - */ -- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block; - -@end - -///---------------- -/// @name Constants -///---------------- - -/** - ## Network Reachability - - The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses. - - enum { - AFNetworkReachabilityStatusUnknown, - AFNetworkReachabilityStatusNotReachable, - AFNetworkReachabilityStatusReachableViaWWAN, - AFNetworkReachabilityStatusReachableViaWiFi, - } - - `AFNetworkReachabilityStatusUnknown` - The `baseURL` host reachability is not known. - - `AFNetworkReachabilityStatusNotReachable` - The `baseURL` host cannot be reached. - - `AFNetworkReachabilityStatusReachableViaWWAN` - The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS. - - `AFNetworkReachabilityStatusReachableViaWiFi` - The `baseURL` host can be reached via a Wi-Fi connection. - - ### Keys for Notification UserInfo Dictionary - - Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification. - - `AFNetworkingReachabilityNotificationStatusItem` - A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification. - The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status. - */ - -///-------------------- -/// @name Notifications -///-------------------- - -/** - Posted when network reachability changes. - This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability. - - @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import ` to the header prefix of the project (`Prefix.pch`). - */ -FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification; -FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem; - -///-------------------- -/// @name Functions -///-------------------- - -/** - Returns a localized string representation of an `AFNetworkReachabilityStatus` value. - */ -FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); - -NS_ASSUME_NONNULL_END -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m b/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m deleted file mode 100644 index d458364..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m +++ /dev/null @@ -1,263 +0,0 @@ -// AFNetworkReachabilityManager.m -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFNetworkReachabilityManager.h" -#if !TARGET_OS_WATCH - -#import -#import -#import -#import -#import - -NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change"; -NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem"; - -typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status); - -NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) { - switch (status) { - case AFNetworkReachabilityStatusNotReachable: - return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil); - case AFNetworkReachabilityStatusReachableViaWWAN: - return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil); - case AFNetworkReachabilityStatusReachableViaWiFi: - return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil); - case AFNetworkReachabilityStatusUnknown: - default: - return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil); - } -} - -static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) { - BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0); - BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0); - BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)); - BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0); - BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction)); - - AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown; - if (isNetworkReachable == NO) { - status = AFNetworkReachabilityStatusNotReachable; - } -#if TARGET_OS_IPHONE - else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) { - status = AFNetworkReachabilityStatusReachableViaWWAN; - } -#endif - else { - status = AFNetworkReachabilityStatusReachableViaWiFi; - } - - return status; -} - -/** - * Queue a status change notification for the main thread. - * - * This is done to ensure that the notifications are received in the same order - * as they are sent. If notifications are sent directly, it is possible that - * a queued notification (for an earlier status condition) is processed after - * the later update, resulting in the listener being left in the wrong state. - */ -static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusBlock block) { - AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); - dispatch_async(dispatch_get_main_queue(), ^{ - if (block) { - block(status); - } - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) }; - [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:userInfo]; - }); -} - -static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { - AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusBlock)info); -} - - -static const void * AFNetworkReachabilityRetainCallback(const void *info) { - return Block_copy(info); -} - -static void AFNetworkReachabilityReleaseCallback(const void *info) { - if (info) { - Block_release(info); - } -} - -@interface AFNetworkReachabilityManager () -@property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability; -@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; -@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; -@end - -@implementation AFNetworkReachabilityManager - -+ (instancetype)sharedManager { - static AFNetworkReachabilityManager *_sharedManager = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - _sharedManager = [self manager]; - }); - - return _sharedManager; -} - -+ (instancetype)managerForDomain:(NSString *)domain { - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); - - AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; - - CFRelease(reachability); - - return manager; -} - -+ (instancetype)managerForAddress:(const void *)address { - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address); - AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; - - CFRelease(reachability); - - return manager; -} - -+ (instancetype)manager -{ -#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) - struct sockaddr_in6 address; - bzero(&address, sizeof(address)); - address.sin6_len = sizeof(address); - address.sin6_family = AF_INET6; -#else - struct sockaddr_in address; - bzero(&address, sizeof(address)); - address.sin_len = sizeof(address); - address.sin_family = AF_INET; -#endif - return [self managerForAddress:&address]; -} - -- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { - self = [super init]; - if (!self) { - return nil; - } - - _networkReachability = CFRetain(reachability); - self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; - - return self; -} - -- (instancetype)init NS_UNAVAILABLE -{ - return nil; -} - -- (void)dealloc { - [self stopMonitoring]; - - if (_networkReachability != NULL) { - CFRelease(_networkReachability); - } -} - -#pragma mark - - -- (BOOL)isReachable { - return [self isReachableViaWWAN] || [self isReachableViaWiFi]; -} - -- (BOOL)isReachableViaWWAN { - return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN; -} - -- (BOOL)isReachableViaWiFi { - return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi; -} - -#pragma mark - - -- (void)startMonitoring { - [self stopMonitoring]; - - if (!self.networkReachability) { - return; - } - - __weak __typeof(self)weakSelf = self; - AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - - strongSelf.networkReachabilityStatus = status; - if (strongSelf.networkReachabilityStatusBlock) { - strongSelf.networkReachabilityStatusBlock(status); - } - - }; - - SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; - SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); - SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); - - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ - SCNetworkReachabilityFlags flags; - if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) { - AFPostReachabilityStatusChange(flags, callback); - } - }); -} - -- (void)stopMonitoring { - if (!self.networkReachability) { - return; - } - - SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); -} - -#pragma mark - - -- (NSString *)localizedNetworkReachabilityStatusString { - return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus); -} - -#pragma mark - - -- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block { - self.networkReachabilityStatusBlock = block; -} - -#pragma mark - NSKeyValueObserving - -+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { - if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) { - return [NSSet setWithObject:@"networkReachabilityStatus"]; - } - - return [super keyPathsForValuesAffectingValueForKey:key]; -} - -@end -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFNetworking.h b/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFNetworking.h deleted file mode 100644 index e2fb2f4..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFNetworking.h +++ /dev/null @@ -1,41 +0,0 @@ -// AFNetworking.h -// -// Copyright (c) 2013 AFNetworking (http://afnetworking.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#import -#import - -#ifndef _AFNETWORKING_ - #define _AFNETWORKING_ - - #import "AFURLRequestSerialization.h" - #import "AFURLResponseSerialization.h" - #import "AFSecurityPolicy.h" - -#if !TARGET_OS_WATCH - #import "AFNetworkReachabilityManager.h" -#endif - - #import "AFURLSessionManager.h" - #import "AFHTTPSessionManager.h" - -#endif /* _AFNETWORKING_ */ diff --git a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFSecurityPolicy.h b/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFSecurityPolicy.h deleted file mode 100644 index c005efa..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFSecurityPolicy.h +++ /dev/null @@ -1,154 +0,0 @@ -// AFSecurityPolicy.h -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#import - -typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { - AFSSLPinningModeNone, - AFSSLPinningModePublicKey, - AFSSLPinningModeCertificate, -}; - -/** - `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. - - Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled. - */ - -NS_ASSUME_NONNULL_BEGIN - -@interface AFSecurityPolicy : NSObject - -/** - The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. - */ -@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode; - -/** - The certificates used to evaluate server trust according to the SSL pinning mode. - - By default, this property is set to any (`.cer`) certificates included in the target compiling AFNetworking. Note that if you are using AFNetworking as embedded framework, no certificates will be pinned by default. Use `certificatesInBundle` to load certificates from your target, and then create a new policy by calling `policyWithPinningMode:withPinnedCertificates`. - - Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches. - */ -@property (nonatomic, strong, nullable) NSSet *pinnedCertificates; - -/** - Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. - */ -@property (nonatomic, assign) BOOL allowInvalidCertificates; - -/** - Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`. - */ -@property (nonatomic, assign) BOOL validatesDomainName; - -///----------------------------------------- -/// @name Getting Certificates from the Bundle -///----------------------------------------- - -/** - Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`. - - @return The certificates included in the given bundle. - */ -+ (NSSet *)certificatesInBundle:(NSBundle *)bundle; - -///----------------------------------------- -/// @name Getting Specific Security Policies -///----------------------------------------- - -/** - Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys. - - @return The default security policy. - */ -+ (instancetype)defaultPolicy; - -///--------------------- -/// @name Initialization -///--------------------- - -/** - Creates and returns a security policy with the specified pinning mode. - - @param pinningMode The SSL pinning mode. - - @return A new security policy. - */ -+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; - -/** - Creates and returns a security policy with the specified pinning mode. - - @param pinningMode The SSL pinning mode. - @param pinnedCertificates The certificates to pin against. - - @return A new security policy. - */ -+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates; - -///------------------------------ -/// @name Evaluating Server Trust -///------------------------------ - -/** - Whether or not the specified server trust should be accepted, based on the security policy. - - This method should be used when responding to an authentication challenge from a server. - - @param serverTrust The X.509 certificate trust of the server. - @param domain The domain of serverTrust. If `nil`, the domain will not be validated. - - @return Whether or not to trust the server. - */ -- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust - forDomain:(nullable NSString *)domain; - -@end - -NS_ASSUME_NONNULL_END - -///---------------- -/// @name Constants -///---------------- - -/** - ## SSL Pinning Modes - - The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes. - - enum { - AFSSLPinningModeNone, - AFSSLPinningModePublicKey, - AFSSLPinningModeCertificate, - } - - `AFSSLPinningModeNone` - Do not used pinned certificates to validate servers. - - `AFSSLPinningModePublicKey` - Validate host certificates against public keys of pinned certificates. - - `AFSSLPinningModeCertificate` - Validate host certificates against pinned certificates. -*/ diff --git a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFSecurityPolicy.m b/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFSecurityPolicy.m deleted file mode 100644 index ec81d37..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFSecurityPolicy.m +++ /dev/null @@ -1,353 +0,0 @@ -// AFSecurityPolicy.m -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFSecurityPolicy.h" - -#import - -#if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV -static NSData * AFSecKeyGetData(SecKeyRef key) { - CFDataRef data = NULL; - - __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out); - - return (__bridge_transfer NSData *)data; - -_out: - if (data) { - CFRelease(data); - } - - return nil; -} -#endif - -static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { -#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV - return [(__bridge id)key1 isEqual:(__bridge id)key2]; -#else - return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)]; -#endif -} - -static id AFPublicKeyForCertificate(NSData *certificate) { - id allowedPublicKey = nil; - SecCertificateRef allowedCertificate; - SecCertificateRef allowedCertificates[1]; - CFArrayRef tempCertificates = nil; - SecPolicyRef policy = nil; - SecTrustRef allowedTrust = nil; - SecTrustResultType result; - - allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); - __Require_Quiet(allowedCertificate != NULL, _out); - - allowedCertificates[0] = allowedCertificate; - tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); - - policy = SecPolicyCreateBasicX509(); - __Require_noErr_Quiet(SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust), _out); - __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out); - - allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); - -_out: - if (allowedTrust) { - CFRelease(allowedTrust); - } - - if (policy) { - CFRelease(policy); - } - - if (tempCertificates) { - CFRelease(tempCertificates); - } - - if (allowedCertificate) { - CFRelease(allowedCertificate); - } - - return allowedPublicKey; -} - -static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { - BOOL isValid = NO; - SecTrustResultType result; - __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out); - - isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed); - -_out: - return isValid; -} - -static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) { - CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); - NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; - - for (CFIndex i = 0; i < certificateCount; i++) { - SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); - [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; - } - - return [NSArray arrayWithArray:trustChain]; -} - -static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { - SecPolicyRef policy = SecPolicyCreateBasicX509(); - CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); - NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; - for (CFIndex i = 0; i < certificateCount; i++) { - SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); - - SecCertificateRef someCertificates[] = {certificate}; - CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); - - SecTrustRef trust; - __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); - - SecTrustResultType result; - __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out); - - [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; - - _out: - if (trust) { - CFRelease(trust); - } - - if (certificates) { - CFRelease(certificates); - } - - continue; - } - CFRelease(policy); - - return [NSArray arrayWithArray:trustChain]; -} - -#pragma mark - - -@interface AFSecurityPolicy() -@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode; -@property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys; -@end - -@implementation AFSecurityPolicy - -+ (NSSet *)certificatesInBundle:(NSBundle *)bundle { - NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; - - NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]]; - for (NSString *path in paths) { - NSData *certificateData = [NSData dataWithContentsOfFile:path]; - [certificates addObject:certificateData]; - } - - return [NSSet setWithSet:certificates]; -} - -+ (NSSet *)defaultPinnedCertificates { - static NSSet *_defaultPinnedCertificates = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - NSBundle *bundle = [NSBundle bundleForClass:[self class]]; - _defaultPinnedCertificates = [self certificatesInBundle:bundle]; - }); - - return _defaultPinnedCertificates; -} - -+ (instancetype)defaultPolicy { - AFSecurityPolicy *securityPolicy = [[self alloc] init]; - securityPolicy.SSLPinningMode = AFSSLPinningModeNone; - - return securityPolicy; -} - -+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { - return [self policyWithPinningMode:pinningMode withPinnedCertificates:[self defaultPinnedCertificates]]; -} - -+ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates { - AFSecurityPolicy *securityPolicy = [[self alloc] init]; - securityPolicy.SSLPinningMode = pinningMode; - - [securityPolicy setPinnedCertificates:pinnedCertificates]; - - return securityPolicy; -} - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.validatesDomainName = YES; - - return self; -} - -- (void)setPinnedCertificates:(NSSet *)pinnedCertificates { - _pinnedCertificates = pinnedCertificates; - - if (self.pinnedCertificates) { - NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]]; - for (NSData *certificate in self.pinnedCertificates) { - id publicKey = AFPublicKeyForCertificate(certificate); - if (!publicKey) { - continue; - } - [mutablePinnedPublicKeys addObject:publicKey]; - } - self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys]; - } else { - self.pinnedPublicKeys = nil; - } -} - -#pragma mark - - -- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust - forDomain:(NSString *)domain -{ - if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) { - // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html - // According to the docs, you should only trust your provided certs for evaluation. - // Pinned certificates are added to the trust. Without pinned certificates, - // there is nothing to evaluate against. - // - // From Apple Docs: - // "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors). - // Instead, add your own (self-signed) CA certificate to the list of trusted anchors." - NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning."); - return NO; - } - - NSMutableArray *policies = [NSMutableArray array]; - if (self.validatesDomainName) { - [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)]; - } else { - [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()]; - } - - SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies); - - if (self.SSLPinningMode == AFSSLPinningModeNone) { - return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust); - } else if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) { - return NO; - } - - switch (self.SSLPinningMode) { - case AFSSLPinningModeNone: - default: - return NO; - case AFSSLPinningModeCertificate: { - NSMutableArray *pinnedCertificates = [NSMutableArray array]; - for (NSData *certificateData in self.pinnedCertificates) { - [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)]; - } - SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates); - - if (!AFServerTrustIsValid(serverTrust)) { - return NO; - } - - // obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA) - NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); - - for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) { - if ([self.pinnedCertificates containsObject:trustChainCertificate]) { - return YES; - } - } - - return NO; - } - case AFSSLPinningModePublicKey: { - NSUInteger trustedPublicKeyCount = 0; - NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust); - - for (id trustChainPublicKey in publicKeys) { - for (id pinnedPublicKey in self.pinnedPublicKeys) { - if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) { - trustedPublicKeyCount += 1; - } - } - } - return trustedPublicKeyCount > 0; - } - } - - return NO; -} - -#pragma mark - NSKeyValueObserving - -+ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys { - return [NSSet setWithObject:@"pinnedCertificates"]; -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (instancetype)initWithCoder:(NSCoder *)decoder { - - self = [self init]; - if (!self) { - return nil; - } - - self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue]; - self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; - self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))]; - self.pinnedCertificates = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(pinnedCertificates))]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))]; - [coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; - [coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))]; - [coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))]; -} - -#pragma mark - NSCopying - -- (instancetype)copyWithZone:(NSZone *)zone { - AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init]; - securityPolicy.SSLPinningMode = self.SSLPinningMode; - securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates; - securityPolicy.validatesDomainName = self.validatesDomainName; - securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone]; - - return securityPolicy; -} - -@end diff --git a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLRequestSerialization.h b/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLRequestSerialization.h deleted file mode 100644 index 694696b..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLRequestSerialization.h +++ /dev/null @@ -1,479 +0,0 @@ -// AFURLRequestSerialization.h -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#import - -#if TARGET_OS_IOS || TARGET_OS_TV -#import -#elif TARGET_OS_WATCH -#import -#endif - -NS_ASSUME_NONNULL_BEGIN - -/** - Returns a percent-escaped string following RFC 3986 for a query string key or value. - RFC 3986 states that the following characters are "reserved" characters. - - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" - - In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow - query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" - should be percent-escaped in the query string. - - @param string The string to be percent-escaped. - - @return The percent-escaped string. - */ -FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string); - -/** - A helper method to generate encoded url query parameters for appending to the end of a URL. - - @param parameters A dictionary of key/values to be encoded. - - @return A url encoded query string - */ -FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters); - -/** - The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary. - - For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`. - */ -@protocol AFURLRequestSerialization - -/** - Returns a request with the specified parameters encoded into a copy of the original request. - - @param request The original request. - @param parameters The parameters to be encoded. - @param error The error that occurred while attempting to encode the request parameters. - - @return A serialized request. - */ -- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request - withParameters:(nullable id)parameters - error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; - -@end - -#pragma mark - - -/** - - */ -typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) { - AFHTTPRequestQueryStringDefaultStyle = 0, -}; - -@protocol AFMultipartFormData; - -/** - `AFHTTPRequestSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. - - Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior. - */ -@interface AFHTTPRequestSerializer : NSObject - -/** - The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default. - */ -@property (nonatomic, assign) NSStringEncoding stringEncoding; - -/** - Whether created requests can use the device’s cellular radio (if present). `YES` by default. - - @see NSMutableURLRequest -setAllowsCellularAccess: - */ -@property (nonatomic, assign) BOOL allowsCellularAccess; - -/** - The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default. - - @see NSMutableURLRequest -setCachePolicy: - */ -@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy; - -/** - Whether created requests should use the default cookie handling. `YES` by default. - - @see NSMutableURLRequest -setHTTPShouldHandleCookies: - */ -@property (nonatomic, assign) BOOL HTTPShouldHandleCookies; - -/** - Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default - - @see NSMutableURLRequest -setHTTPShouldUsePipelining: - */ -@property (nonatomic, assign) BOOL HTTPShouldUsePipelining; - -/** - The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default. - - @see NSMutableURLRequest -setNetworkServiceType: - */ -@property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType; - -/** - The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds. - - @see NSMutableURLRequest -setTimeoutInterval: - */ -@property (nonatomic, assign) NSTimeInterval timeoutInterval; - -///--------------------------------------- -/// @name Configuring HTTP Request Headers -///--------------------------------------- - -/** - Default HTTP header field values to be applied to serialized requests. By default, these include the following: - - - `Accept-Language` with the contents of `NSLocale +preferredLanguages` - - `User-Agent` with the contents of various bundle identifiers and OS designations - - @discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`. - */ -@property (readonly, nonatomic, strong) NSDictionary *HTTPRequestHeaders; - -/** - Creates and returns a serializer with default configuration. - */ -+ (instancetype)serializer; - -/** - Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header. - - @param field The HTTP header to set a default value for - @param value The value set as default for the specified header, or `nil` - */ -- (void)setValue:(nullable NSString *)value -forHTTPHeaderField:(NSString *)field; - -/** - Returns the value for the HTTP headers set in the request serializer. - - @param field The HTTP header to retrieve the default value for - - @return The value set as default for the specified header, or `nil` - */ -- (nullable NSString *)valueForHTTPHeaderField:(NSString *)field; - -/** - Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header. - - @param username The HTTP basic auth username - @param password The HTTP basic auth password - */ -- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username - password:(NSString *)password; - -/** - Clears any existing value for the "Authorization" HTTP header. - */ -- (void)clearAuthorizationHeader; - -///------------------------------------------------------- -/// @name Configuring Query String Parameter Serialization -///------------------------------------------------------- - -/** - HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default. - */ -@property (nonatomic, strong) NSSet *HTTPMethodsEncodingParametersInURI; - -/** - Set the method of query string serialization according to one of the pre-defined styles. - - @param style The serialization style. - - @see AFHTTPRequestQueryStringSerializationStyle - */ -- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style; - -/** - Set the a custom method of query string serialization according to the specified block. - - @param block A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occurred when attempting to encode parameters for the given request. - */ -- (void)setQueryStringSerializationWithBlock:(nullable NSString * (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block; - -///------------------------------- -/// @name Creating Request Objects -///------------------------------- - -/** - Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string. - - If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body. - - @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`. - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body. - @param error The error that occurred while constructing the request. - - @return An `NSMutableURLRequest` object. - */ -- (NSMutableURLRequest *)requestWithMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(nullable id)parameters - error:(NSError * _Nullable __autoreleasing *)error; - -/** - Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2 - - Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream. - - @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`. - @param URLString The URL string used to create the request URL. - @param parameters The parameters to be encoded and set in the request HTTP body. - @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. - @param error The error that occurred while constructing the request. - - @return An `NSMutableURLRequest` object - */ -- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(nullable NSDictionary *)parameters - constructingBodyWithBlock:(nullable void (^)(id formData))block - error:(NSError * _Nullable __autoreleasing *)error; - -/** - Creates an `NSMutableURLRequest` by removing the `HTTPBodyStream` from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished. - - @param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`. - @param fileURL The file URL to write multipart form contents to. - @param handler A handler block to execute. - - @discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request. - - @see https://github.com/AFNetworking/AFNetworking/issues/1398 - */ -- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request - writingStreamContentsToFile:(NSURL *)fileURL - completionHandler:(nullable void (^)(NSError * _Nullable error))handler; - -@end - -#pragma mark - - -/** - The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`. - */ -@protocol AFMultipartFormData - -/** - Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary. - - The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively. - - @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. - @param name The name to be associated with the specified data. This parameter must not be `nil`. - @param error If an error occurs, upon return contains an `NSError` object that describes the problem. - - @return `YES` if the file data was successfully appended, otherwise `NO`. - */ -- (BOOL)appendPartWithFileURL:(NSURL *)fileURL - name:(NSString *)name - error:(NSError * _Nullable __autoreleasing *)error; - -/** - Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. - - @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. - @param name The name to be associated with the specified data. This parameter must not be `nil`. - @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`. - @param mimeType The declared MIME type of the file data. This parameter must not be `nil`. - @param error If an error occurs, upon return contains an `NSError` object that describes the problem. - - @return `YES` if the file data was successfully appended otherwise `NO`. - */ -- (BOOL)appendPartWithFileURL:(NSURL *)fileURL - name:(NSString *)name - fileName:(NSString *)fileName - mimeType:(NSString *)mimeType - error:(NSError * _Nullable __autoreleasing *)error; - -/** - Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary. - - @param inputStream The input stream to be appended to the form data - @param name The name to be associated with the specified input stream. This parameter must not be `nil`. - @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`. - @param length The length of the specified input stream in bytes. - @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. - */ -- (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream - name:(NSString *)name - fileName:(NSString *)fileName - length:(int64_t)length - mimeType:(NSString *)mimeType; - -/** - Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. - - @param data The data to be encoded and appended to the form data. - @param name The name to be associated with the specified data. This parameter must not be `nil`. - @param fileName The filename to be associated with the specified data. This parameter must not be `nil`. - @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. - */ -- (void)appendPartWithFileData:(NSData *)data - name:(NSString *)name - fileName:(NSString *)fileName - mimeType:(NSString *)mimeType; - -/** - Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary. - - @param data The data to be encoded and appended to the form data. - @param name The name to be associated with the specified data. This parameter must not be `nil`. - */ - -- (void)appendPartWithFormData:(NSData *)data - name:(NSString *)name; - - -/** - Appends HTTP headers, followed by the encoded data and the multipart form boundary. - - @param headers The HTTP headers to be appended to the form data. - @param body The data to be encoded and appended to the form data. This parameter must not be `nil`. - */ -- (void)appendPartWithHeaders:(nullable NSDictionary *)headers - body:(NSData *)body; - -/** - Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream. - - When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth. - - @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb. - @param delay Duration of delay each time a packet is read. By default, no delay is set. - */ -- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes - delay:(NSTimeInterval)delay; - -@end - -#pragma mark - - -/** - `AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`. - */ -@interface AFJSONRequestSerializer : AFHTTPRequestSerializer - -/** - Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default. - */ -@property (nonatomic, assign) NSJSONWritingOptions writingOptions; - -/** - Creates and returns a JSON serializer with specified reading and writing options. - - @param writingOptions The specified JSON writing options. - */ -+ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions; - -@end - -#pragma mark - - -/** - `AFPropertyListRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`. - */ -@interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer - -/** - The property list format. Possible values are described in "NSPropertyListFormat". - */ -@property (nonatomic, assign) NSPropertyListFormat format; - -/** - @warning The `writeOptions` property is currently unused. - */ -@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions; - -/** - Creates and returns a property list serializer with a specified format, read options, and write options. - - @param format The property list format. - @param writeOptions The property list write options. - - @warning The `writeOptions` property is currently unused. - */ -+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format - writeOptions:(NSPropertyListWriteOptions)writeOptions; - -@end - -#pragma mark - - -///---------------- -/// @name Constants -///---------------- - -/** - ## Error Domains - - The following error domain is predefined. - - - `NSString * const AFURLRequestSerializationErrorDomain` - - ### Constants - - `AFURLRequestSerializationErrorDomain` - AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. - */ -FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain; - -/** - ## User info dictionary keys - - These keys may exist in the user info dictionary, in addition to those defined for NSError. - - - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey` - - ### Constants - - `AFNetworkingOperationFailingURLRequestErrorKey` - The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`. - */ -FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey; - -/** - ## Throttling Bandwidth for HTTP Request Input Streams - - @see -throttleBandwidthWithPacketSize:delay: - - ### Constants - - `kAFUploadStream3GSuggestedPacketSize` - Maximum packet size, in number of bytes. Equal to 16kb. - - `kAFUploadStream3GSuggestedDelay` - Duration of delay each time a packet is read. Equal to 0.2 seconds. - */ -FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize; -FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay; - -NS_ASSUME_NONNULL_END diff --git a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLRequestSerialization.m b/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLRequestSerialization.m deleted file mode 100644 index 9a2ac98..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLRequestSerialization.m +++ /dev/null @@ -1,1376 +0,0 @@ -// AFURLRequestSerialization.m -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFURLRequestSerialization.h" - -#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV -#import -#else -#import -#endif - -NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request"; -NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response"; - -typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error); - -/** - Returns a percent-escaped string following RFC 3986 for a query string key or value. - RFC 3986 states that the following characters are "reserved" characters. - - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" - - In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow - query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" - should be percent-escaped in the query string. - - parameter string: The string to be percent-escaped. - - returns: The percent-escaped string. - */ -NSString * AFPercentEscapedStringFromString(NSString *string) { - static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4 - static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;="; - - NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; - [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]]; - - // FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028 - // return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; - - static NSUInteger const batchSize = 50; - - NSUInteger index = 0; - NSMutableString *escaped = @"".mutableCopy; - - while (index < string.length) { -#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); - - // To avoid breaking up character sequences such as 👴🏻👮🏽 - range = [string rangeOfComposedCharacterSequencesForRange:range]; - - NSString *substring = [string substringWithRange:range]; - NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; - [escaped appendString:encoded]; - - index += range.length; - } - - return escaped; -} - -#pragma mark - - -@interface AFQueryStringPair : NSObject -@property (readwrite, nonatomic, strong) id field; -@property (readwrite, nonatomic, strong) id value; - -- (instancetype)initWithField:(id)field value:(id)value; - -- (NSString *)URLEncodedStringValue; -@end - -@implementation AFQueryStringPair - -- (instancetype)initWithField:(id)field value:(id)value { - self = [super init]; - if (!self) { - return nil; - } - - self.field = field; - self.value = value; - - return self; -} - -- (NSString *)URLEncodedStringValue { - if (!self.value || [self.value isEqual:[NSNull null]]) { - return AFPercentEscapedStringFromString([self.field description]); - } else { - return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedStringFromString([self.field description]), AFPercentEscapedStringFromString([self.value description])]; - } -} - -@end - -#pragma mark - - -FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); -FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); - -NSString * AFQueryStringFromParameters(NSDictionary *parameters) { - NSMutableArray *mutablePairs = [NSMutableArray array]; - for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { - [mutablePairs addObject:[pair URLEncodedStringValue]]; - } - - return [mutablePairs componentsJoinedByString:@"&"]; -} - -NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) { - return AFQueryStringPairsFromKeyAndValue(nil, dictionary); -} - -NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) { - NSMutableArray *mutableQueryStringComponents = [NSMutableArray array]; - - NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)]; - - if ([value isKindOfClass:[NSDictionary class]]) { - NSDictionary *dictionary = value; - // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries - for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { - id nestedValue = dictionary[nestedKey]; - if (nestedValue) { - [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)]; - } - } - } else if ([value isKindOfClass:[NSArray class]]) { - NSArray *array = value; - for (id nestedValue in array) { - [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)]; - } - } else if ([value isKindOfClass:[NSSet class]]) { - NSSet *set = value; - for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { - [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)]; - } - } else { - [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]]; - } - - return mutableQueryStringComponents; -} - -#pragma mark - - -@interface AFStreamingMultipartFormData : NSObject -- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest - stringEncoding:(NSStringEncoding)encoding; - -- (NSMutableURLRequest *)requestByFinalizingMultipartFormData; -@end - -#pragma mark - - -static NSArray * AFHTTPRequestSerializerObservedKeyPaths() { - static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - _AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))]; - }); - - return _AFHTTPRequestSerializerObservedKeyPaths; -} - -static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerObserverContext; - -@interface AFHTTPRequestSerializer () -@property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths; -@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders; -@property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle; -@property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization; -@end - -@implementation AFHTTPRequestSerializer - -+ (instancetype)serializer { - return [[self alloc] init]; -} - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.stringEncoding = NSUTF8StringEncoding; - - self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary]; - - // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 - NSMutableArray *acceptLanguagesComponents = [NSMutableArray array]; - [[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - float q = 1.0f - (idx * 0.1f); - [acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]]; - *stop = q <= 0.5f; - }]; - [self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"]; - - NSString *userAgent = nil; -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" -#if TARGET_OS_IOS - // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 - userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; -#elif TARGET_OS_WATCH - // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 - userAgent = [NSString stringWithFormat:@"%@/%@ (%@; watchOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[WKInterfaceDevice currentDevice] model], [[WKInterfaceDevice currentDevice] systemVersion], [[WKInterfaceDevice currentDevice] screenScale]]; -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) - userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]; -#endif -#pragma clang diagnostic pop - if (userAgent) { - if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) { - NSMutableString *mutableUserAgent = [userAgent mutableCopy]; - if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) { - userAgent = mutableUserAgent; - } - } - [self setValue:userAgent forHTTPHeaderField:@"User-Agent"]; - } - - // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html - self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil]; - - self.mutableObservedChangedKeyPaths = [NSMutableSet set]; - for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { - if ([self respondsToSelector:NSSelectorFromString(keyPath)]) { - [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext]; - } - } - - return self; -} - -- (void)dealloc { - for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { - if ([self respondsToSelector:NSSelectorFromString(keyPath)]) { - [self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext]; - } - } -} - -#pragma mark - - -// Workarounds for crashing behavior using Key-Value Observing with XCTest -// See https://github.com/AFNetworking/AFNetworking/issues/2523 - -- (void)setAllowsCellularAccess:(BOOL)allowsCellularAccess { - [self willChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))]; - _allowsCellularAccess = allowsCellularAccess; - [self didChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))]; -} - -- (void)setCachePolicy:(NSURLRequestCachePolicy)cachePolicy { - [self willChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))]; - _cachePolicy = cachePolicy; - [self didChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))]; -} - -- (void)setHTTPShouldHandleCookies:(BOOL)HTTPShouldHandleCookies { - [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))]; - _HTTPShouldHandleCookies = HTTPShouldHandleCookies; - [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))]; -} - -- (void)setHTTPShouldUsePipelining:(BOOL)HTTPShouldUsePipelining { - [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))]; - _HTTPShouldUsePipelining = HTTPShouldUsePipelining; - [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))]; -} - -- (void)setNetworkServiceType:(NSURLRequestNetworkServiceType)networkServiceType { - [self willChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))]; - _networkServiceType = networkServiceType; - [self didChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))]; -} - -- (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval { - [self willChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))]; - _timeoutInterval = timeoutInterval; - [self didChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))]; -} - -#pragma mark - - -- (NSDictionary *)HTTPRequestHeaders { - return [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders]; -} - -- (void)setValue:(NSString *)value -forHTTPHeaderField:(NSString *)field -{ - [self.mutableHTTPRequestHeaders setValue:value forKey:field]; -} - -- (NSString *)valueForHTTPHeaderField:(NSString *)field { - return [self.mutableHTTPRequestHeaders valueForKey:field]; -} - -- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username - password:(NSString *)password -{ - NSData *basicAuthCredentials = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding]; - NSString *base64AuthCredentials = [basicAuthCredentials base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0]; - [self setValue:[NSString stringWithFormat:@"Basic %@", base64AuthCredentials] forHTTPHeaderField:@"Authorization"]; -} - -- (void)clearAuthorizationHeader { - [self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"]; -} - -#pragma mark - - -- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style { - self.queryStringSerializationStyle = style; - self.queryStringSerialization = nil; -} - -- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, id, NSError *__autoreleasing *))block { - self.queryStringSerialization = block; -} - -#pragma mark - - -- (NSMutableURLRequest *)requestWithMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(id)parameters - error:(NSError *__autoreleasing *)error -{ - NSParameterAssert(method); - NSParameterAssert(URLString); - - NSURL *url = [NSURL URLWithString:URLString]; - - NSParameterAssert(url); - - NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url]; - mutableRequest.HTTPMethod = method; - - for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { - if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) { - [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath]; - } - } - - mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy]; - - return mutableRequest; -} - -- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method - URLString:(NSString *)URLString - parameters:(NSDictionary *)parameters - constructingBodyWithBlock:(void (^)(id formData))block - error:(NSError *__autoreleasing *)error -{ - NSParameterAssert(method); - NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]); - - NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error]; - - __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding]; - - if (parameters) { - for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { - NSData *data = nil; - if ([pair.value isKindOfClass:[NSData class]]) { - data = pair.value; - } else if ([pair.value isEqual:[NSNull null]]) { - data = [NSData data]; - } else { - data = [[pair.value description] dataUsingEncoding:self.stringEncoding]; - } - - if (data) { - [formData appendPartWithFormData:data name:[pair.field description]]; - } - } - } - - if (block) { - block(formData); - } - - return [formData requestByFinalizingMultipartFormData]; -} - -- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request - writingStreamContentsToFile:(NSURL *)fileURL - completionHandler:(void (^)(NSError *error))handler -{ - NSParameterAssert(request.HTTPBodyStream); - NSParameterAssert([fileURL isFileURL]); - - NSInputStream *inputStream = request.HTTPBodyStream; - NSOutputStream *outputStream = [[NSOutputStream alloc] initWithURL:fileURL append:NO]; - __block NSError *error = nil; - - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; - [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; - - [inputStream open]; - [outputStream open]; - - while ([inputStream hasBytesAvailable] && [outputStream hasSpaceAvailable]) { - uint8_t buffer[1024]; - - NSInteger bytesRead = [inputStream read:buffer maxLength:1024]; - if (inputStream.streamError || bytesRead < 0) { - error = inputStream.streamError; - break; - } - - NSInteger bytesWritten = [outputStream write:buffer maxLength:(NSUInteger)bytesRead]; - if (outputStream.streamError || bytesWritten < 0) { - error = outputStream.streamError; - break; - } - - if (bytesRead == 0 && bytesWritten == 0) { - break; - } - } - - [outputStream close]; - [inputStream close]; - - if (handler) { - dispatch_async(dispatch_get_main_queue(), ^{ - handler(error); - }); - } - }); - - NSMutableURLRequest *mutableRequest = [request mutableCopy]; - mutableRequest.HTTPBodyStream = nil; - - return mutableRequest; -} - -#pragma mark - AFURLRequestSerialization - -- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request - withParameters:(id)parameters - error:(NSError *__autoreleasing *)error -{ - NSParameterAssert(request); - - NSMutableURLRequest *mutableRequest = [request mutableCopy]; - - [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { - if (![request valueForHTTPHeaderField:field]) { - [mutableRequest setValue:value forHTTPHeaderField:field]; - } - }]; - - NSString *query = nil; - if (parameters) { - if (self.queryStringSerialization) { - NSError *serializationError; - query = self.queryStringSerialization(request, parameters, &serializationError); - - if (serializationError) { - if (error) { - *error = serializationError; - } - - return nil; - } - } else { - switch (self.queryStringSerializationStyle) { - case AFHTTPRequestQueryStringDefaultStyle: - query = AFQueryStringFromParameters(parameters); - break; - } - } - } - - if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { - if (query && query.length > 0) { - mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]]; - } - } else { - // #2864: an empty string is a valid x-www-form-urlencoded payload - if (!query) { - query = @""; - } - if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { - [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; - } - [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]]; - } - - return mutableRequest; -} - -#pragma mark - NSKeyValueObserving - -+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key { - if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) { - return NO; - } - - return [super automaticallyNotifiesObserversForKey:key]; -} - -- (void)observeValueForKeyPath:(NSString *)keyPath - ofObject:(__unused id)object - change:(NSDictionary *)change - context:(void *)context -{ - if (context == AFHTTPRequestSerializerObserverContext) { - if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) { - [self.mutableObservedChangedKeyPaths removeObject:keyPath]; - } else { - [self.mutableObservedChangedKeyPaths addObject:keyPath]; - } - } -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (instancetype)initWithCoder:(NSCoder *)decoder { - self = [self init]; - if (!self) { - return nil; - } - - self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy]; - self.queryStringSerializationStyle = (AFHTTPRequestQueryStringSerializationStyle)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))]; - [coder encodeInteger:self.queryStringSerializationStyle forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))]; -} - -#pragma mark - NSCopying - -- (instancetype)copyWithZone:(NSZone *)zone { - AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init]; - serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone]; - serializer.queryStringSerializationStyle = self.queryStringSerializationStyle; - serializer.queryStringSerialization = self.queryStringSerialization; - - return serializer; -} - -@end - -#pragma mark - - -static NSString * AFCreateMultipartFormBoundary() { - return [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()]; -} - -static NSString * const kAFMultipartFormCRLF = @"\r\n"; - -static inline NSString * AFMultipartFormInitialBoundary(NSString *boundary) { - return [NSString stringWithFormat:@"--%@%@", boundary, kAFMultipartFormCRLF]; -} - -static inline NSString * AFMultipartFormEncapsulationBoundary(NSString *boundary) { - return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF]; -} - -static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) { - return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF]; -} - -static inline NSString * AFContentTypeForPathExtension(NSString *extension) { - NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL); - NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType); - if (!contentType) { - return @"application/octet-stream"; - } else { - return contentType; - } -} - -NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16; -NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; - -@interface AFHTTPBodyPart : NSObject -@property (nonatomic, assign) NSStringEncoding stringEncoding; -@property (nonatomic, strong) NSDictionary *headers; -@property (nonatomic, copy) NSString *boundary; -@property (nonatomic, strong) id body; -@property (nonatomic, assign) unsigned long long bodyContentLength; -@property (nonatomic, strong) NSInputStream *inputStream; - -@property (nonatomic, assign) BOOL hasInitialBoundary; -@property (nonatomic, assign) BOOL hasFinalBoundary; - -@property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable; -@property (readonly, nonatomic, assign) unsigned long long contentLength; - -- (NSInteger)read:(uint8_t *)buffer - maxLength:(NSUInteger)length; -@end - -@interface AFMultipartBodyStream : NSInputStream -@property (nonatomic, assign) NSUInteger numberOfBytesInPacket; -@property (nonatomic, assign) NSTimeInterval delay; -@property (nonatomic, strong) NSInputStream *inputStream; -@property (readonly, nonatomic, assign) unsigned long long contentLength; -@property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty; - -- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding; -- (void)setInitialAndFinalBoundaries; -- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart; -@end - -#pragma mark - - -@interface AFStreamingMultipartFormData () -@property (readwrite, nonatomic, copy) NSMutableURLRequest *request; -@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; -@property (readwrite, nonatomic, copy) NSString *boundary; -@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream; -@end - -@implementation AFStreamingMultipartFormData - -- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest - stringEncoding:(NSStringEncoding)encoding -{ - self = [super init]; - if (!self) { - return nil; - } - - self.request = urlRequest; - self.stringEncoding = encoding; - self.boundary = AFCreateMultipartFormBoundary(); - self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding]; - - return self; -} - -- (BOOL)appendPartWithFileURL:(NSURL *)fileURL - name:(NSString *)name - error:(NSError * __autoreleasing *)error -{ - NSParameterAssert(fileURL); - NSParameterAssert(name); - - NSString *fileName = [fileURL lastPathComponent]; - NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]); - - return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error]; -} - -- (BOOL)appendPartWithFileURL:(NSURL *)fileURL - name:(NSString *)name - fileName:(NSString *)fileName - mimeType:(NSString *)mimeType - error:(NSError * __autoreleasing *)error -{ - NSParameterAssert(fileURL); - NSParameterAssert(name); - NSParameterAssert(fileName); - NSParameterAssert(mimeType); - - if (![fileURL isFileURL]) { - NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil)}; - if (error) { - *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; - } - - return NO; - } else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) { - NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil)}; - if (error) { - *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; - } - - return NO; - } - - NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:error]; - if (!fileAttributes) { - return NO; - } - - NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; - [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; - [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; - - AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; - bodyPart.stringEncoding = self.stringEncoding; - bodyPart.headers = mutableHeaders; - bodyPart.boundary = self.boundary; - bodyPart.body = fileURL; - bodyPart.bodyContentLength = [fileAttributes[NSFileSize] unsignedLongLongValue]; - [self.bodyStream appendHTTPBodyPart:bodyPart]; - - return YES; -} - -- (void)appendPartWithInputStream:(NSInputStream *)inputStream - name:(NSString *)name - fileName:(NSString *)fileName - length:(int64_t)length - mimeType:(NSString *)mimeType -{ - NSParameterAssert(name); - NSParameterAssert(fileName); - NSParameterAssert(mimeType); - - NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; - [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; - [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; - - AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; - bodyPart.stringEncoding = self.stringEncoding; - bodyPart.headers = mutableHeaders; - bodyPart.boundary = self.boundary; - bodyPart.body = inputStream; - - bodyPart.bodyContentLength = (unsigned long long)length; - - [self.bodyStream appendHTTPBodyPart:bodyPart]; -} - -- (void)appendPartWithFileData:(NSData *)data - name:(NSString *)name - fileName:(NSString *)fileName - mimeType:(NSString *)mimeType -{ - NSParameterAssert(name); - NSParameterAssert(fileName); - NSParameterAssert(mimeType); - - NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; - [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; - [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; - - [self appendPartWithHeaders:mutableHeaders body:data]; -} - -- (void)appendPartWithFormData:(NSData *)data - name:(NSString *)name -{ - NSParameterAssert(name); - - NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; - [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"]; - - [self appendPartWithHeaders:mutableHeaders body:data]; -} - -- (void)appendPartWithHeaders:(NSDictionary *)headers - body:(NSData *)body -{ - NSParameterAssert(body); - - AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; - bodyPart.stringEncoding = self.stringEncoding; - bodyPart.headers = headers; - bodyPart.boundary = self.boundary; - bodyPart.bodyContentLength = [body length]; - bodyPart.body = body; - - [self.bodyStream appendHTTPBodyPart:bodyPart]; -} - -- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes - delay:(NSTimeInterval)delay -{ - self.bodyStream.numberOfBytesInPacket = numberOfBytes; - self.bodyStream.delay = delay; -} - -- (NSMutableURLRequest *)requestByFinalizingMultipartFormData { - if ([self.bodyStream isEmpty]) { - return self.request; - } - - // Reset the initial and final boundaries to ensure correct Content-Length - [self.bodyStream setInitialAndFinalBoundaries]; - [self.request setHTTPBodyStream:self.bodyStream]; - - [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"]; - [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"]; - - return self.request; -} - -@end - -#pragma mark - - -@interface NSStream () -@property (readwrite) NSStreamStatus streamStatus; -@property (readwrite, copy) NSError *streamError; -@end - -@interface AFMultipartBodyStream () -@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; -@property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts; -@property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator; -@property (readwrite, nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart; -@property (readwrite, nonatomic, strong) NSOutputStream *outputStream; -@property (readwrite, nonatomic, strong) NSMutableData *buffer; -@end - -@implementation AFMultipartBodyStream -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wimplicit-atomic-properties" -#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1100) -@synthesize delegate; -#endif -@synthesize streamStatus; -@synthesize streamError; -#pragma clang diagnostic pop - -- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding { - self = [super init]; - if (!self) { - return nil; - } - - self.stringEncoding = encoding; - self.HTTPBodyParts = [NSMutableArray array]; - self.numberOfBytesInPacket = NSIntegerMax; - - return self; -} - -- (void)setInitialAndFinalBoundaries { - if ([self.HTTPBodyParts count] > 0) { - for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { - bodyPart.hasInitialBoundary = NO; - bodyPart.hasFinalBoundary = NO; - } - - [[self.HTTPBodyParts firstObject] setHasInitialBoundary:YES]; - [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES]; - } -} - -- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart { - [self.HTTPBodyParts addObject:bodyPart]; -} - -- (BOOL)isEmpty { - return [self.HTTPBodyParts count] == 0; -} - -#pragma mark - NSInputStream - -- (NSInteger)read:(uint8_t *)buffer - maxLength:(NSUInteger)length -{ - if ([self streamStatus] == NSStreamStatusClosed) { - return 0; - } - - NSInteger totalNumberOfBytesRead = 0; - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) { - if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) { - if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) { - break; - } - } else { - NSUInteger maxLength = MIN(length, self.numberOfBytesInPacket) - (NSUInteger)totalNumberOfBytesRead; - NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength]; - if (numberOfBytesRead == -1) { - self.streamError = self.currentHTTPBodyPart.inputStream.streamError; - break; - } else { - totalNumberOfBytesRead += numberOfBytesRead; - - if (self.delay > 0.0f) { - [NSThread sleepForTimeInterval:self.delay]; - } - } - } - } -#pragma clang diagnostic pop - - return totalNumberOfBytesRead; -} - -- (BOOL)getBuffer:(__unused uint8_t **)buffer - length:(__unused NSUInteger *)len -{ - return NO; -} - -- (BOOL)hasBytesAvailable { - return [self streamStatus] == NSStreamStatusOpen; -} - -#pragma mark - NSStream - -- (void)open { - if (self.streamStatus == NSStreamStatusOpen) { - return; - } - - self.streamStatus = NSStreamStatusOpen; - - [self setInitialAndFinalBoundaries]; - self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator]; -} - -- (void)close { - self.streamStatus = NSStreamStatusClosed; -} - -- (id)propertyForKey:(__unused NSString *)key { - return nil; -} - -- (BOOL)setProperty:(__unused id)property - forKey:(__unused NSString *)key -{ - return NO; -} - -- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop - forMode:(__unused NSString *)mode -{} - -- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop - forMode:(__unused NSString *)mode -{} - -- (unsigned long long)contentLength { - unsigned long long length = 0; - for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { - length += [bodyPart contentLength]; - } - - return length; -} - -#pragma mark - Undocumented CFReadStream Bridged Methods - -- (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop - forMode:(__unused CFStringRef)aMode -{} - -- (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop - forMode:(__unused CFStringRef)aMode -{} - -- (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags - callback:(__unused CFReadStreamClientCallBack)inCallback - context:(__unused CFStreamClientContext *)inContext { - return NO; -} - -#pragma mark - NSCopying - -- (instancetype)copyWithZone:(NSZone *)zone { - AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding]; - - for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { - [bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]]; - } - - [bodyStreamCopy setInitialAndFinalBoundaries]; - - return bodyStreamCopy; -} - -@end - -#pragma mark - - -typedef enum { - AFEncapsulationBoundaryPhase = 1, - AFHeaderPhase = 2, - AFBodyPhase = 3, - AFFinalBoundaryPhase = 4, -} AFHTTPBodyPartReadPhase; - -@interface AFHTTPBodyPart () { - AFHTTPBodyPartReadPhase _phase; - NSInputStream *_inputStream; - unsigned long long _phaseReadOffset; -} - -- (BOOL)transitionToNextPhase; -- (NSInteger)readData:(NSData *)data - intoBuffer:(uint8_t *)buffer - maxLength:(NSUInteger)length; -@end - -@implementation AFHTTPBodyPart - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - [self transitionToNextPhase]; - - return self; -} - -- (void)dealloc { - if (_inputStream) { - [_inputStream close]; - _inputStream = nil; - } -} - -- (NSInputStream *)inputStream { - if (!_inputStream) { - if ([self.body isKindOfClass:[NSData class]]) { - _inputStream = [NSInputStream inputStreamWithData:self.body]; - } else if ([self.body isKindOfClass:[NSURL class]]) { - _inputStream = [NSInputStream inputStreamWithURL:self.body]; - } else if ([self.body isKindOfClass:[NSInputStream class]]) { - _inputStream = self.body; - } else { - _inputStream = [NSInputStream inputStreamWithData:[NSData data]]; - } - } - - return _inputStream; -} - -- (NSString *)stringForHeaders { - NSMutableString *headerString = [NSMutableString string]; - for (NSString *field in [self.headers allKeys]) { - [headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]]; - } - [headerString appendString:kAFMultipartFormCRLF]; - - return [NSString stringWithString:headerString]; -} - -- (unsigned long long)contentLength { - unsigned long long length = 0; - - NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding]; - length += [encapsulationBoundaryData length]; - - NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; - length += [headersData length]; - - length += _bodyContentLength; - - NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]); - length += [closingBoundaryData length]; - - return length; -} - -- (BOOL)hasBytesAvailable { - // Allows `read:maxLength:` to be called again if `AFMultipartFormFinalBoundary` doesn't fit into the available buffer - if (_phase == AFFinalBoundaryPhase) { - return YES; - } - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wcovered-switch-default" - switch (self.inputStream.streamStatus) { - case NSStreamStatusNotOpen: - case NSStreamStatusOpening: - case NSStreamStatusOpen: - case NSStreamStatusReading: - case NSStreamStatusWriting: - return YES; - case NSStreamStatusAtEnd: - case NSStreamStatusClosed: - case NSStreamStatusError: - default: - return NO; - } -#pragma clang diagnostic pop -} - -- (NSInteger)read:(uint8_t *)buffer - maxLength:(NSUInteger)length -{ - NSInteger totalNumberOfBytesRead = 0; - - if (_phase == AFEncapsulationBoundaryPhase) { - NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding]; - totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; - } - - if (_phase == AFHeaderPhase) { - NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; - totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; - } - - if (_phase == AFBodyPhase) { - NSInteger numberOfBytesRead = 0; - - numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; - if (numberOfBytesRead == -1) { - return -1; - } else { - totalNumberOfBytesRead += numberOfBytesRead; - - if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) { - [self transitionToNextPhase]; - } - } - } - - if (_phase == AFFinalBoundaryPhase) { - NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]); - totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; - } - - return totalNumberOfBytesRead; -} - -- (NSInteger)readData:(NSData *)data - intoBuffer:(uint8_t *)buffer - maxLength:(NSUInteger)length -{ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length)); - [data getBytes:buffer range:range]; -#pragma clang diagnostic pop - - _phaseReadOffset += range.length; - - if (((NSUInteger)_phaseReadOffset) >= [data length]) { - [self transitionToNextPhase]; - } - - return (NSInteger)range.length; -} - -- (BOOL)transitionToNextPhase { - if (![[NSThread currentThread] isMainThread]) { - dispatch_sync(dispatch_get_main_queue(), ^{ - [self transitionToNextPhase]; - }); - return YES; - } - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wcovered-switch-default" - switch (_phase) { - case AFEncapsulationBoundaryPhase: - _phase = AFHeaderPhase; - break; - case AFHeaderPhase: - [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; - [self.inputStream open]; - _phase = AFBodyPhase; - break; - case AFBodyPhase: - [self.inputStream close]; - _phase = AFFinalBoundaryPhase; - break; - case AFFinalBoundaryPhase: - default: - _phase = AFEncapsulationBoundaryPhase; - break; - } - _phaseReadOffset = 0; -#pragma clang diagnostic pop - - return YES; -} - -#pragma mark - NSCopying - -- (instancetype)copyWithZone:(NSZone *)zone { - AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init]; - - bodyPart.stringEncoding = self.stringEncoding; - bodyPart.headers = self.headers; - bodyPart.bodyContentLength = self.bodyContentLength; - bodyPart.body = self.body; - bodyPart.boundary = self.boundary; - - return bodyPart; -} - -@end - -#pragma mark - - -@implementation AFJSONRequestSerializer - -+ (instancetype)serializer { - return [self serializerWithWritingOptions:(NSJSONWritingOptions)0]; -} - -+ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions -{ - AFJSONRequestSerializer *serializer = [[self alloc] init]; - serializer.writingOptions = writingOptions; - - return serializer; -} - -#pragma mark - AFURLRequestSerialization - -- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request - withParameters:(id)parameters - error:(NSError *__autoreleasing *)error -{ - NSParameterAssert(request); - - if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { - return [super requestBySerializingRequest:request withParameters:parameters error:error]; - } - - NSMutableURLRequest *mutableRequest = [request mutableCopy]; - - [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { - if (![request valueForHTTPHeaderField:field]) { - [mutableRequest setValue:value forHTTPHeaderField:field]; - } - }]; - - if (parameters) { - if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { - [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; - } - - [mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]]; - } - - return mutableRequest; -} - -#pragma mark - NSSecureCoding - -- (instancetype)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - - self.writingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writingOptions))] unsignedIntegerValue]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeInteger:self.writingOptions forKey:NSStringFromSelector(@selector(writingOptions))]; -} - -#pragma mark - NSCopying - -- (instancetype)copyWithZone:(NSZone *)zone { - AFJSONRequestSerializer *serializer = [super copyWithZone:zone]; - serializer.writingOptions = self.writingOptions; - - return serializer; -} - -@end - -#pragma mark - - -@implementation AFPropertyListRequestSerializer - -+ (instancetype)serializer { - return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0]; -} - -+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format - writeOptions:(NSPropertyListWriteOptions)writeOptions -{ - AFPropertyListRequestSerializer *serializer = [[self alloc] init]; - serializer.format = format; - serializer.writeOptions = writeOptions; - - return serializer; -} - -#pragma mark - AFURLRequestSerializer - -- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request - withParameters:(id)parameters - error:(NSError *__autoreleasing *)error -{ - NSParameterAssert(request); - - if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { - return [super requestBySerializingRequest:request withParameters:parameters error:error]; - } - - NSMutableURLRequest *mutableRequest = [request mutableCopy]; - - [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { - if (![request valueForHTTPHeaderField:field]) { - [mutableRequest setValue:value forHTTPHeaderField:field]; - } - }]; - - if (parameters) { - if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { - [mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"]; - } - - [mutableRequest setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error]]; - } - - return mutableRequest; -} - -#pragma mark - NSSecureCoding - -- (instancetype)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - - self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; - self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeInteger:self.format forKey:NSStringFromSelector(@selector(format))]; - [coder encodeObject:@(self.writeOptions) forKey:NSStringFromSelector(@selector(writeOptions))]; -} - -#pragma mark - NSCopying - -- (instancetype)copyWithZone:(NSZone *)zone { - AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone]; - serializer.format = self.format; - serializer.writeOptions = self.writeOptions; - - return serializer; -} - -@end diff --git a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLResponseSerialization.h b/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLResponseSerialization.h deleted file mode 100644 index a9430ad..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLResponseSerialization.h +++ /dev/null @@ -1,311 +0,0 @@ -// AFURLResponseSerialization.h -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#import - -NS_ASSUME_NONNULL_BEGIN - -/** - The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data. - - For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object. - */ -@protocol AFURLResponseSerialization - -/** - The response object decoded from the data associated with a specified response. - - @param response The response to be processed. - @param data The response data to be decoded. - @param error The error that occurred while attempting to decode the response data. - - @return The object decoded from the specified response data. - */ -- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response - data:(nullable NSData *)data - error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; - -@end - -#pragma mark - - -/** - `AFHTTPResponseSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. - - Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior. - */ -@interface AFHTTPResponseSerializer : NSObject - -- (instancetype)init; - -/** - 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; - -/** - Creates and returns a serializer with default configuration. - */ -+ (instancetype)serializer; - -///----------------------------------------- -/// @name Configuring Response Serialization -///----------------------------------------- - -/** - The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation. - - See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html - */ -@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes; - -/** - The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation. - */ -@property (nonatomic, copy, nullable) NSSet *acceptableContentTypes; - -/** - Validates the specified response and data. - - In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks. - - @param response The response to be validated. - @param data The data associated with the response. - @param error The error that occurred while attempting to validate the response. - - @return `YES` if the response is valid, otherwise `NO`. - */ -- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response - data:(nullable NSData *)data - error:(NSError * _Nullable __autoreleasing *)error; - -@end - -#pragma mark - - - -/** - `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses. - - By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types: - - - `application/json` - - `text/json` - - `text/javascript` - */ -@interface AFJSONResponseSerializer : AFHTTPResponseSerializer - -- (instancetype)init; - -/** - Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. - */ -@property (nonatomic, assign) NSJSONReadingOptions readingOptions; - -/** - Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`. - */ -@property (nonatomic, assign) BOOL removesKeysWithNullValues; - -/** - Creates and returns a JSON serializer with specified reading and writing options. - - @param readingOptions The specified JSON reading options. - */ -+ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions; - -@end - -#pragma mark - - -/** - `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects. - - By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: - - - `application/xml` - - `text/xml` - */ -@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer - -@end - -#pragma mark - - -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED - -/** - `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. - - By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: - - - `application/xml` - - `text/xml` - */ -@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer - -- (instancetype)init; - -/** - Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. - */ -@property (nonatomic, assign) NSUInteger options; - -/** - Creates and returns an XML document serializer with the specified options. - - @param mask The XML document options. - */ -+ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask; - -@end - -#endif - -#pragma mark - - -/** - `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. - - By default, `AFPropertyListResponseSerializer` accepts the following MIME types: - - - `application/x-plist` - */ -@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer - -- (instancetype)init; - -/** - The property list format. Possible values are described in "NSPropertyListFormat". - */ -@property (nonatomic, assign) NSPropertyListFormat format; - -/** - The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions." - */ -@property (nonatomic, assign) NSPropertyListReadOptions readOptions; - -/** - Creates and returns a property list serializer with a specified format, read options, and write options. - - @param format The property list format. - @param readOptions The property list reading options. - */ -+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format - readOptions:(NSPropertyListReadOptions)readOptions; - -@end - -#pragma mark - - -/** - `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses. - - By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: - - - `image/tiff` - - `image/jpeg` - - `image/gif` - - `image/png` - - `image/ico` - - `image/x-icon` - - `image/bmp` - - `image/x-bmp` - - `image/x-xbitmap` - - `image/x-win-bitmap` - */ -@interface AFImageResponseSerializer : AFHTTPResponseSerializer - -#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH -/** - The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. - */ -@property (nonatomic, assign) CGFloat imageScale; - -/** - Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default. - */ -@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage; -#endif - -@end - -#pragma mark - - -/** - `AFCompoundSerializer` is a subclass of `AFHTTPResponseSerializer` that delegates the response serialization to the first `AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer. - */ -@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer - -/** - The component response serializers. - */ -@property (readonly, nonatomic, copy) NSArray > *responseSerializers; - -/** - Creates and returns a compound serializer comprised of the specified response serializers. - - @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`. - */ -+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray > *)responseSerializers; - -@end - -///---------------- -/// @name Constants -///---------------- - -/** - ## Error Domains - - The following error domain is predefined. - - - `NSString * const AFURLResponseSerializationErrorDomain` - - ### Constants - - `AFURLResponseSerializationErrorDomain` - AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. - */ -FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain; - -/** - ## User info dictionary keys - - These keys may exist in the user info dictionary, in addition to those defined for NSError. - - - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` - - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey` - - ### Constants - - `AFNetworkingOperationFailingURLResponseErrorKey` - The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. - - `AFNetworkingOperationFailingURLResponseDataErrorKey` - The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. - */ -FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey; - -FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; - -NS_ASSUME_NONNULL_END diff --git a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLResponseSerialization.m b/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLResponseSerialization.m deleted file mode 100755 index 5e46799..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLResponseSerialization.m +++ /dev/null @@ -1,805 +0,0 @@ -// AFURLResponseSerialization.m -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFURLResponseSerialization.h" - -#import - -#if TARGET_OS_IOS -#import -#elif TARGET_OS_WATCH -#import -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) -#import -#endif - -NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response"; -NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response"; -NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data"; - -static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) { - if (!error) { - return underlyingError; - } - - if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) { - return error; - } - - NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy]; - mutableUserInfo[NSUnderlyingErrorKey] = underlyingError; - - return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo]; -} - -static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) { - if ([error.domain isEqualToString:domain] && error.code == code) { - return YES; - } else if (error.userInfo[NSUnderlyingErrorKey]) { - return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain); - } - - return NO; -} - -static id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) { - if ([JSONObject isKindOfClass:[NSArray class]]) { - NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]]; - for (id value in (NSArray *)JSONObject) { - [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)]; - } - - return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray]; - } else if ([JSONObject isKindOfClass:[NSDictionary class]]) { - NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject]; - for (id key in [(NSDictionary *)JSONObject allKeys]) { - id value = (NSDictionary *)JSONObject[key]; - if (!value || [value isEqual:[NSNull null]]) { - [mutableDictionary removeObjectForKey:key]; - } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) { - mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions); - } - } - - return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary]; - } - - return JSONObject; -} - -@implementation AFHTTPResponseSerializer - -+ (instancetype)serializer { - return [[self alloc] init]; -} - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.stringEncoding = NSUTF8StringEncoding; - - self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; - self.acceptableContentTypes = nil; - - return self; -} - -#pragma mark - - -- (BOOL)validateResponse:(NSHTTPURLResponse *)response - data:(NSData *)data - error:(NSError * __autoreleasing *)error -{ - BOOL responseIsValid = YES; - NSError *validationError = nil; - - if (response && [response isKindOfClass:[NSHTTPURLResponse class]]) { - if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]] && - !([response MIMEType] == nil && [data length] == 0)) { - - if ([data length] > 0 && [response URL]) { - NSMutableDictionary *mutableUserInfo = [@{ - NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]], - NSURLErrorFailingURLErrorKey:[response URL], - AFNetworkingOperationFailingURLResponseErrorKey: response, - } mutableCopy]; - if (data) { - mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; - } - - validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError); - } - - responseIsValid = NO; - } - - if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) { - NSMutableDictionary *mutableUserInfo = [@{ - NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode], - NSURLErrorFailingURLErrorKey:[response URL], - AFNetworkingOperationFailingURLResponseErrorKey: response, - } mutableCopy]; - - if (data) { - mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; - } - - validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError); - - responseIsValid = NO; - } - } - - if (error && !responseIsValid) { - *error = validationError; - } - - return responseIsValid; -} - -#pragma mark - AFURLResponseSerialization - -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error -{ - [self validateResponse:(NSHTTPURLResponse *)response data:data error:error]; - - return data; -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (instancetype)initWithCoder:(NSCoder *)decoder { - self = [self init]; - if (!self) { - return nil; - } - - self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; - self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; - [coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; -} - -#pragma mark - NSCopying - -- (instancetype)copyWithZone:(NSZone *)zone { - AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; - serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone]; - serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone]; - - return serializer; -} - -@end - -#pragma mark - - -@implementation AFJSONResponseSerializer - -+ (instancetype)serializer { - return [self serializerWithReadingOptions:(NSJSONReadingOptions)0]; -} - -+ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions { - AFJSONResponseSerializer *serializer = [[self alloc] init]; - serializer.readingOptions = readingOptions; - - return serializer; -} - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]; - - return self; -} - -#pragma mark - AFURLResponseSerialization - -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error -{ - if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { - if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { - return nil; - } - } - - id responseObject = nil; - NSError *serializationError = nil; - // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization. - // See https://github.com/rails/rails/issues/1742 - BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]]; - if (data.length > 0 && !isSpace) { - 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 - -- (instancetype)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - - self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue]; - self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))]; - [coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))]; -} - -#pragma mark - NSCopying - -- (instancetype)copyWithZone:(NSZone *)zone { - AFJSONResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; - serializer.readingOptions = self.readingOptions; - serializer.removesKeysWithNullValues = self.removesKeysWithNullValues; - - return serializer; -} - -@end - -#pragma mark - - -@implementation AFXMLParserResponseSerializer - -+ (instancetype)serializer { - AFXMLParserResponseSerializer *serializer = [[self alloc] init]; - - return serializer; -} - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; - - return self; -} - -#pragma mark - AFURLResponseSerialization - -- (id)responseObjectForResponse:(NSHTTPURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error -{ - if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { - if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { - return nil; - } - } - - return [[NSXMLParser alloc] initWithData:data]; -} - -@end - -#pragma mark - - -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED - -@implementation AFXMLDocumentResponseSerializer - -+ (instancetype)serializer { - return [self serializerWithXMLDocumentOptions:0]; -} - -+ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask { - AFXMLDocumentResponseSerializer *serializer = [[self alloc] init]; - serializer.options = mask; - - return serializer; -} - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; - - return self; -} - -#pragma mark - AFURLResponseSerialization - -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error -{ - if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { - if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { - return nil; - } - } - - NSError *serializationError = nil; - NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError]; - - if (error) { - *error = AFErrorWithUnderlyingError(serializationError, *error); - } - - return document; -} - -#pragma mark - NSSecureCoding - -- (instancetype)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - - self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))]; -} - -#pragma mark - NSCopying - -- (instancetype)copyWithZone:(NSZone *)zone { - AFXMLDocumentResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; - serializer.options = self.options; - - return serializer; -} - -@end - -#endif - -#pragma mark - - -@implementation AFPropertyListResponseSerializer - -+ (instancetype)serializer { - return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0]; -} - -+ (instancetype)serializerWithFormat:(NSPropertyListFormat)format - readOptions:(NSPropertyListReadOptions)readOptions -{ - AFPropertyListResponseSerializer *serializer = [[self alloc] init]; - serializer.format = format; - serializer.readOptions = readOptions; - - return serializer; -} - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil]; - - return self; -} - -#pragma mark - AFURLResponseSerialization - -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error -{ - if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { - if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { - return nil; - } - } - - id responseObject; - NSError *serializationError = nil; - - if (data) { - responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError]; - } - - if (error) { - *error = AFErrorWithUnderlyingError(serializationError, *error); - } - - return responseObject; -} - -#pragma mark - NSSecureCoding - -- (instancetype)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - - self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; - self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))]; - [coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))]; -} - -#pragma mark - NSCopying - -- (instancetype)copyWithZone:(NSZone *)zone { - AFPropertyListResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; - serializer.format = self.format; - serializer.readOptions = self.readOptions; - - return serializer; -} - -@end - -#pragma mark - - -#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH -#import -#import - -@interface UIImage (AFNetworkingSafeImageLoading) -+ (UIImage *)af_safeImageWithData:(NSData *)data; -@end - -static NSLock* imageLock = nil; - -@implementation UIImage (AFNetworkingSafeImageLoading) - -+ (UIImage *)af_safeImageWithData:(NSData *)data { - UIImage* image = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - imageLock = [[NSLock alloc] init]; - }); - - [imageLock lock]; - image = [UIImage imageWithData:data]; - [imageLock unlock]; - return image; -} - -@end - -static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) { - UIImage *image = [UIImage af_safeImageWithData:data]; - if (image.images) { - return image; - } - - return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation]; -} - -static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) { - if (!data || [data length] == 0) { - return nil; - } - - CGImageRef imageRef = NULL; - CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data); - - if ([response.MIMEType isEqualToString:@"image/png"]) { - imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); - } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) { - imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); - - if (imageRef) { - CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef); - CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace); - - // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale - if (imageColorSpaceModel == kCGColorSpaceModelCMYK) { - CGImageRelease(imageRef); - imageRef = NULL; - } - } - } - - CGDataProviderRelease(dataProvider); - - UIImage *image = AFImageWithDataAtScale(data, scale); - if (!imageRef) { - if (image.images || !image) { - return image; - } - - imageRef = CGImageCreateCopy([image CGImage]); - if (!imageRef) { - return nil; - } - } - - size_t width = CGImageGetWidth(imageRef); - size_t height = CGImageGetHeight(imageRef); - size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef); - - if (width * height > 1024 * 1024 || bitsPerComponent > 8) { - CGImageRelease(imageRef); - - return image; - } - - // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate - size_t bytesPerRow = 0; - CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); - CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace); - CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); - - if (colorSpaceModel == kCGColorSpaceModelRGB) { - uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask); -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wassign-enum" - if (alpha == kCGImageAlphaNone) { - bitmapInfo &= ~kCGBitmapAlphaInfoMask; - bitmapInfo |= kCGImageAlphaNoneSkipFirst; - } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) { - bitmapInfo &= ~kCGBitmapAlphaInfoMask; - bitmapInfo |= kCGImageAlphaPremultipliedFirst; - } -#pragma clang diagnostic pop - } - - CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo); - - CGColorSpaceRelease(colorSpace); - - if (!context) { - CGImageRelease(imageRef); - - return image; - } - - CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef); - CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context); - - CGContextRelease(context); - - UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation]; - - CGImageRelease(inflatedImageRef); - CGImageRelease(imageRef); - - return inflatedImage; -} -#endif - - -@implementation AFImageResponseSerializer - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; - -#if TARGET_OS_IOS || TARGET_OS_TV - self.imageScale = [[UIScreen mainScreen] scale]; - self.automaticallyInflatesResponseImage = YES; -#elif TARGET_OS_WATCH - self.imageScale = [[WKInterfaceDevice currentDevice] screenScale]; - self.automaticallyInflatesResponseImage = YES; -#endif - - return self; -} - -#pragma mark - AFURLResponseSerializer - -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error -{ - if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { - if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { - return nil; - } - } - -#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH - if (self.automaticallyInflatesResponseImage) { - return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale); - } else { - return AFImageWithDataAtScale(data, self.imageScale); - } -#else - // Ensure that the image is set to it's correct pixel width and height - NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data]; - NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])]; - [image addRepresentation:bitimage]; - - return image; -#endif - - return nil; -} - -#pragma mark - NSSecureCoding - -- (instancetype)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - -#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH - NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))]; -#if CGFLOAT_IS_DOUBLE - self.imageScale = [imageScale doubleValue]; -#else - self.imageScale = [imageScale floatValue]; -#endif - - self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; -#endif - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - -#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH - [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))]; - [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; -#endif -} - -#pragma mark - NSCopying - -- (instancetype)copyWithZone:(NSZone *)zone { - AFImageResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; - -#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH - serializer.imageScale = self.imageScale; - serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage; -#endif - - return serializer; -} - -@end - -#pragma mark - - -@interface AFCompoundResponseSerializer () -@property (readwrite, nonatomic, copy) NSArray *responseSerializers; -@end - -@implementation AFCompoundResponseSerializer - -+ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers { - AFCompoundResponseSerializer *serializer = [[self alloc] init]; - serializer.responseSerializers = responseSerializers; - - return serializer; -} - -#pragma mark - AFURLResponseSerialization - -- (id)responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error -{ - for (id serializer in self.responseSerializers) { - if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) { - continue; - } - - NSError *serializerError = nil; - id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError]; - if (responseObject) { - if (error) { - *error = AFErrorWithUnderlyingError(serializerError, *error); - } - - return responseObject; - } - } - - return [super responseObjectForResponse:response data:data error:error]; -} - -#pragma mark - NSSecureCoding - -- (instancetype)initWithCoder:(NSCoder *)decoder { - self = [super initWithCoder:decoder]; - if (!self) { - return nil; - } - - self.responseSerializers = [decoder decodeObjectOfClass:[NSArray class] forKey:NSStringFromSelector(@selector(responseSerializers))]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [super encodeWithCoder:coder]; - - [coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))]; -} - -#pragma mark - NSCopying - -- (instancetype)copyWithZone:(NSZone *)zone { - AFCompoundResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; - serializer.responseSerializers = self.responseSerializers; - - return serializer; -} - -@end diff --git a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLSessionManager.h b/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLSessionManager.h deleted file mode 100644 index 89909fe..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLSessionManager.h +++ /dev/null @@ -1,500 +0,0 @@ -// AFURLSessionManager.h -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - - -#import - -#import "AFURLResponseSerialization.h" -#import "AFURLRequestSerialization.h" -#import "AFSecurityPolicy.h" -#if !TARGET_OS_WATCH -#import "AFNetworkReachabilityManager.h" -#endif - -/** - `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. - - ## Subclassing Notes - - This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead. - - ## NSURLSession & NSURLSessionTask Delegate Methods - - `AFURLSessionManager` implements the following delegate methods: - - ### `NSURLSessionDelegate` - - - `URLSession:didBecomeInvalidWithError:` - - `URLSession:didReceiveChallenge:completionHandler:` - - `URLSessionDidFinishEventsForBackgroundURLSession:` - - ### `NSURLSessionTaskDelegate` - - - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:` - - `URLSession:task:didReceiveChallenge:completionHandler:` - - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:` - - `URLSession:task:needNewBodyStream:` - - `URLSession:task:didCompleteWithError:` - - ### `NSURLSessionDataDelegate` - - - `URLSession:dataTask:didReceiveResponse:completionHandler:` - - `URLSession:dataTask:didBecomeDownloadTask:` - - `URLSession:dataTask:didReceiveData:` - - `URLSession:dataTask:willCacheResponse:completionHandler:` - - ### `NSURLSessionDownloadDelegate` - - - `URLSession:downloadTask:didFinishDownloadingToURL:` - - `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:` - - `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:` - - If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. - - ## Network Reachability Monitoring - - Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details. - - ## NSCoding Caveats - - - Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`. - - ## NSCopying Caveats - - - `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original. - - Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied. - - @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. - */ - -NS_ASSUME_NONNULL_BEGIN - -@interface AFURLSessionManager : NSObject - -/** - The managed session. - */ -@property (readonly, nonatomic, strong) NSURLSession *session; - -/** - The operation queue on which delegate callbacks are run. - */ -@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue; - -/** - Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`. - - @warning `responseSerializer` must not be `nil`. - */ -@property (nonatomic, strong) id responseSerializer; - -///------------------------------- -/// @name Managing Security Policy -///------------------------------- - -/** - The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. - */ -@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; - -#if !TARGET_OS_WATCH -///-------------------------------------- -/// @name Monitoring Network Reachability -///-------------------------------------- - -/** - The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default. - */ -@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; -#endif - -///---------------------------- -/// @name Getting Session Tasks -///---------------------------- - -/** - The data, upload, and download tasks currently run by the managed session. - */ -@property (readonly, nonatomic, strong) NSArray *tasks; - -/** - The data tasks currently run by the managed session. - */ -@property (readonly, nonatomic, strong) NSArray *dataTasks; - -/** - The upload tasks currently run by the managed session. - */ -@property (readonly, nonatomic, strong) NSArray *uploadTasks; - -/** - The download tasks currently run by the managed session. - */ -@property (readonly, nonatomic, strong) NSArray *downloadTasks; - -///------------------------------- -/// @name Managing Callback Queues -///------------------------------- - -/** - The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. - */ -@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; - -/** - The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. - */ -@property (nonatomic, strong, nullable) dispatch_group_t completionGroup; - -///--------------------------------- -/// @name Working Around System Bugs -///--------------------------------- - -/** - Whether to attempt to retry creation of upload tasks for background sessions when initial call returns `nil`. `NO` by default. - - @bug As of iOS 7.0, there is a bug where upload tasks created for background tasks are sometimes `nil`. As a workaround, if this property is `YES`, AFNetworking will follow Apple's recommendation to try creating the task again. - - @see https://github.com/AFNetworking/AFNetworking/issues/1675 - */ -@property (nonatomic, assign) BOOL attemptsToRecreateUploadTasksForBackgroundSessions; - -///--------------------- -/// @name Initialization -///--------------------- - -/** - Creates and returns a manager for a session created with the specified configuration. This is the designated initializer. - - @param configuration The configuration used to create the managed session. - - @return A manager for a newly-created session. - */ -- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; - -/** - Invalidates the managed session, optionally canceling pending tasks. - - @param cancelPendingTasks Whether or not to cancel pending tasks. - */ -- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks; - -///------------------------- -/// @name Running Data Tasks -///------------------------- - -/** - Creates an `NSURLSessionDataTask` with the specified request. - - @param request The HTTP request for the request. - @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. - */ -- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request - completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; - -/** - Creates an `NSURLSessionDataTask` with the specified request. - - @param request The HTTP request for the request. - @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. - @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. - @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. - */ -- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request - uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock - downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock - completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; - -///--------------------------- -/// @name Running Upload Tasks -///--------------------------- - -/** - Creates an `NSURLSessionUploadTask` with the specified request for a local file. - - @param request The HTTP request for the request. - @param fileURL A URL to the local file to be uploaded. - @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. - @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. - - @see `attemptsToRecreateUploadTasksForBackgroundSessions` - */ -- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request - fromFile:(NSURL *)fileURL - progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock - completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; - -/** - Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body. - - @param request The HTTP request for the request. - @param bodyData A data object containing the HTTP body to be uploaded. - @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. - @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. - */ -- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request - fromData:(nullable NSData *)bodyData - progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock - completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; - -/** - Creates an `NSURLSessionUploadTask` with the specified streaming request. - - @param request The HTTP request for the request. - @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. - @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. - */ -- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request - progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock - completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; - -///----------------------------- -/// @name Running Download Tasks -///----------------------------- - -/** - Creates an `NSURLSessionDownloadTask` with the specified request. - - @param request The HTTP request for the request. - @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. - @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. - @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. - - @warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method. - */ -- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request - progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock - destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination - completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; - -/** - Creates an `NSURLSessionDownloadTask` with the specified resume data. - - @param resumeData The data used to resume downloading. - @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. - @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. - @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. - */ -- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData - progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock - destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination - completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; - -///--------------------------------- -/// @name Getting Progress for Tasks -///--------------------------------- - -/** - Returns the upload progress of the specified task. - - @param task The session task. Must not be `nil`. - - @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable. - */ -- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task; - -/** - Returns the download progress of the specified task. - - @param task The session task. Must not be `nil`. - - @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable. - */ -- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task; - -///----------------------------------------- -/// @name Setting Session Delegate Callbacks -///----------------------------------------- - -/** - Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`. - - @param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation. - */ -- (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block; - -/** - Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`. - - @param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. - */ -- (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; - -///-------------------------------------- -/// @name Setting Task Delegate Callbacks -///-------------------------------------- - -/** - Sets a block to be executed when a task requires a new request body stream to send to the remote server, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:needNewBodyStream:`. - - @param block A block object to be executed when a task requires a new request body stream. - */ -- (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block; - -/** - Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`. - - @param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response. - */ -- (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block; - -/** - Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`. - - @param block A block object to be executed when a session task has received a request specific authentication challenge. The block returns the disposition of the authentication challenge, and takes four arguments: the session, the task, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. - */ -- (void)setTaskDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; - -/** - Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. - - @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes five arguments: the session, the task, the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread. - */ -- (void)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block; - -/** - Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`. - - @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task. - */ -- (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block; - -///------------------------------------------- -/// @name Setting Data Task Delegate Callbacks -///------------------------------------------- - -/** - Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`. - - @param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response. - */ -- (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block; - -/** - Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`. - - @param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become. - */ -- (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block; - -/** - Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`. - - @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue. - */ -- (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block; - -/** - Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`. - - @param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response. - */ -- (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block; - -/** - Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`. - - @param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session. - */ -- (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block; - -///----------------------------------------------- -/// @name Setting Download Task Delegate Callbacks -///----------------------------------------------- - -/** - Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`. - - @param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error. - */ -- (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block; - -/** - Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesWritten:totalBytesExpectedToWrite:`. - - @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue. - */ -- (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block; - -/** - Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. - - @param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded. - */ -- (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block; - -@end - -///-------------------- -/// @name Notifications -///-------------------- - -/** - Posted when a task resumes. - */ -FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification; - -/** - Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. - */ -FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification; - -/** - Posted when a task suspends its execution. - */ -FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification; - -/** - Posted when a session is invalidated. - */ -FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification; - -/** - Posted when a session download task encountered an error when moving the temporary download file to a specified destination. - */ -FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification; - -/** - The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task. - */ -FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey; - -/** - The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized. - */ -FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey; - -/** - The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer. - */ -FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey; - -/** - The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an the response data has been stored directly to disk. - */ -FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey; - -/** - Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists. - */ -FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey; - -NS_ASSUME_NONNULL_END diff --git a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLSessionManager.m b/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLSessionManager.m deleted file mode 100644 index ef2108c..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/AFURLSessionManager.m +++ /dev/null @@ -1,1244 +0,0 @@ -// AFURLSessionManager.m -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFURLSessionManager.h" -#import - -#ifndef NSFoundationVersionNumber_iOS_8_0 -#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug 1140.11 -#else -#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug NSFoundationVersionNumber_iOS_8_0 -#endif - -static dispatch_queue_t url_session_manager_creation_queue() { - static dispatch_queue_t af_url_session_manager_creation_queue; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_url_session_manager_creation_queue = dispatch_queue_create("com.alamofire.networking.session.manager.creation", DISPATCH_QUEUE_SERIAL); - }); - - return af_url_session_manager_creation_queue; -} - -static void url_session_manager_create_task_safely(dispatch_block_t block) { - if (NSFoundationVersionNumber < NSFoundationVersionNumber_With_Fixed_5871104061079552_bug) { - // Fix of bug - // Open Radar:http://openradar.appspot.com/radar?id=5871104061079552 (status: Fixed in iOS8) - // Issue about:https://github.com/AFNetworking/AFNetworking/issues/2093 - dispatch_sync(url_session_manager_creation_queue(), block); - } else { - block(); - } -} - -static dispatch_queue_t url_session_manager_processing_queue() { - static dispatch_queue_t af_url_session_manager_processing_queue; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_url_session_manager_processing_queue = dispatch_queue_create("com.alamofire.networking.session.manager.processing", DISPATCH_QUEUE_CONCURRENT); - }); - - return af_url_session_manager_processing_queue; -} - -static dispatch_group_t url_session_manager_completion_group() { - static dispatch_group_t af_url_session_manager_completion_group; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_url_session_manager_completion_group = dispatch_group_create(); - }); - - return af_url_session_manager_completion_group; -} - -NSString * const AFNetworkingTaskDidResumeNotification = @"com.alamofire.networking.task.resume"; -NSString * const AFNetworkingTaskDidCompleteNotification = @"com.alamofire.networking.task.complete"; -NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend"; -NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate"; -NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error"; - -NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; -NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; -NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; -NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error"; -NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; - -static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock"; - -static NSUInteger const AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask = 3; - -static void * AFTaskStateChangedContext = &AFTaskStateChangedContext; - -typedef void (^AFURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error); -typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); - -typedef NSURLRequest * (^AFURLSessionTaskWillPerformHTTPRedirectionBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request); -typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionTaskDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); -typedef void (^AFURLSessionDidFinishEventsForBackgroundURLSessionBlock)(NSURLSession *session); - -typedef NSInputStream * (^AFURLSessionTaskNeedNewBodyStreamBlock)(NSURLSession *session, NSURLSessionTask *task); -typedef void (^AFURLSessionTaskDidSendBodyDataBlock)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend); -typedef void (^AFURLSessionTaskDidCompleteBlock)(NSURLSession *session, NSURLSessionTask *task, NSError *error); - -typedef NSURLSessionResponseDisposition (^AFURLSessionDataTaskDidReceiveResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response); -typedef void (^AFURLSessionDataTaskDidBecomeDownloadTaskBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask); -typedef void (^AFURLSessionDataTaskDidReceiveDataBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data); -typedef NSCachedURLResponse * (^AFURLSessionDataTaskWillCacheResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse); - -typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location); -typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite); -typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes); -typedef void (^AFURLSessionTaskProgressBlock)(NSProgress *); - -typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error); - - -#pragma mark - - -@interface AFURLSessionManagerTaskDelegate : NSObject -@property (nonatomic, weak) AFURLSessionManager *manager; -@property (nonatomic, strong) NSMutableData *mutableData; -@property (nonatomic, strong) NSProgress *uploadProgress; -@property (nonatomic, strong) NSProgress *downloadProgress; -@property (nonatomic, copy) NSURL *downloadFileURL; -@property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; -@property (nonatomic, copy) AFURLSessionTaskProgressBlock uploadProgressBlock; -@property (nonatomic, copy) AFURLSessionTaskProgressBlock downloadProgressBlock; -@property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler; -@end - -@implementation AFURLSessionManagerTaskDelegate - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - - self.mutableData = [NSMutableData data]; - self.uploadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; - self.uploadProgress.totalUnitCount = NSURLSessionTransferSizeUnknown; - - self.downloadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; - self.downloadProgress.totalUnitCount = NSURLSessionTransferSizeUnknown; - return self; -} - -#pragma mark - NSProgress Tracking - -- (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[NSKeyValueChangeNewKey] longLongValue]; - } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesExpectedToReceive))]) { - self.downloadProgress.totalUnitCount = [change[NSKeyValueChangeNewKey] longLongValue]; - } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) { - self.uploadProgress.completedUnitCount = [change[NSKeyValueChangeNewKey] longLongValue]; - } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesExpectedToSend))]) { - self.uploadProgress.totalUnitCount = [change[NSKeyValueChangeNewKey] 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 -{ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - __strong AFURLSessionManager *manager = self.manager; - - __block id responseObject = nil; - - __block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; - userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer; - - //Performance Improvement from #2672 - NSData *data = nil; - if (self.mutableData) { - data = [self.mutableData copy]; - //We no longer need the reference, so nil it out to gain back some memory. - self.mutableData = nil; - } - - if (self.downloadFileURL) { - userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL; - } else if (data) { - userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data; - } - - if (error) { - userInfo[AFNetworkingTaskDidCompleteErrorKey] = error; - - dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{ - if (self.completionHandler) { - self.completionHandler(task.response, responseObject, error); - } - - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; - }); - }); - } else { - dispatch_async(url_session_manager_processing_queue(), ^{ - NSError *serializationError = nil; - responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError]; - - if (self.downloadFileURL) { - responseObject = self.downloadFileURL; - } - - if (responseObject) { - userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject; - } - - if (serializationError) { - userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError; - } - - dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{ - if (self.completionHandler) { - self.completionHandler(task.response, responseObject, serializationError); - } - - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; - }); - }); - }); - } -#pragma clang diagnostic pop -} - -#pragma mark - NSURLSessionDataTaskDelegate - -- (void)URLSession:(__unused NSURLSession *)session - dataTask:(__unused NSURLSessionDataTask *)dataTask - didReceiveData:(NSData *)data -{ - [self.mutableData appendData:data]; -} - -#pragma mark - NSURLSessionDownloadTaskDelegate - -- (void)URLSession:(NSURLSession *)session - downloadTask:(NSURLSessionDownloadTask *)downloadTask -didFinishDownloadingToURL:(NSURL *)location -{ - NSError *fileManagerError = nil; - self.downloadFileURL = nil; - - if (self.downloadTaskDidFinishDownloading) { - self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); - if (self.downloadFileURL) { - [[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError]; - - if (fileManagerError) { - [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo]; - } - } - } -} - -@end - -#pragma mark - - -/** - * A workaround for issues related to key-value observing the `state` of an `NSURLSessionTask`. - * - * See: - * - https://github.com/AFNetworking/AFNetworking/issues/1477 - * - https://github.com/AFNetworking/AFNetworking/issues/2638 - * - https://github.com/AFNetworking/AFNetworking/pull/2702 - */ - -static inline void af_swizzleSelector(Class theClass, SEL originalSelector, SEL swizzledSelector) { - Method originalMethod = class_getInstanceMethod(theClass, originalSelector); - Method swizzledMethod = class_getInstanceMethod(theClass, swizzledSelector); - method_exchangeImplementations(originalMethod, swizzledMethod); -} - -static inline BOOL af_addMethod(Class theClass, SEL selector, Method method) { - return class_addMethod(theClass, selector, method_getImplementation(method), method_getTypeEncoding(method)); -} - -static NSString * const AFNSURLSessionTaskDidResumeNotification = @"com.alamofire.networking.nsurlsessiontask.resume"; -static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofire.networking.nsurlsessiontask.suspend"; - -@interface _AFURLSessionTaskSwizzling : NSObject - -@end - -@implementation _AFURLSessionTaskSwizzling - -+ (void)load { - /** - WARNING: Trouble Ahead - https://github.com/AFNetworking/AFNetworking/pull/2702 - */ - - if (NSClassFromString(@"NSURLSessionTask")) { - /** - iOS 7 and iOS 8 differ in NSURLSessionTask implementation, which makes the next bit of code a bit tricky. - Many Unit Tests have been built to validate as much of this behavior has possible. - Here is what we know: - - NSURLSessionTasks are implemented with class clusters, meaning the class you request from the API isn't actually the type of class you will get back. - - Simply referencing `[NSURLSessionTask class]` will not work. You need to ask an `NSURLSession` to actually create an object, and grab the class from there. - - On iOS 7, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `__NSCFURLSessionTask`. - - On iOS 8, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `NSURLSessionTask`. - - On iOS 7, `__NSCFLocalSessionTask` and `__NSCFURLSessionTask` are the only two classes that have their own implementations of `resume` and `suspend`, and `__NSCFLocalSessionTask` DOES NOT CALL SUPER. This means both classes need to be swizzled. - - On iOS 8, `NSURLSessionTask` is the only class that implements `resume` and `suspend`. This means this is the only class that needs to be swizzled. - - Because `NSURLSessionTask` is not involved in the class hierarchy for every version of iOS, its easier to add the swizzled methods to a dummy class and manage them there. - - Some Assumptions: - - No implementations of `resume` or `suspend` call super. If this were to change in a future version of iOS, we'd need to handle it. - - No background task classes override `resume` or `suspend` - - The current solution: - 1) Grab an instance of `__NSCFLocalDataTask` by asking an instance of `NSURLSession` for a data task. - 2) Grab a pointer to the original implementation of `af_resume` - 3) Check to see if the current class has an implementation of resume. If so, continue to step 4. - 4) Grab the super class of the current class. - 5) Grab a pointer for the current class to the current implementation of `resume`. - 6) Grab a pointer for the super class to the current implementation of `resume`. - 7) If the current class implementation of `resume` is not equal to the super class implementation of `resume` AND the current implementation of `resume` is not equal to the original implementation of `af_resume`, THEN swizzle the methods - 8) Set the current class to the super class, and repeat steps 3-8 - */ - NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration]; - NSURLSession * session = [NSURLSession sessionWithConfiguration:configuration]; -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wnonnull" - NSURLSessionDataTask *localDataTask = [session dataTaskWithURL:nil]; -#pragma clang diagnostic pop - IMP originalAFResumeIMP = method_getImplementation(class_getInstanceMethod([self class], @selector(af_resume))); - Class currentClass = [localDataTask class]; - - while (class_getInstanceMethod(currentClass, @selector(resume))) { - Class superClass = [currentClass superclass]; - IMP classResumeIMP = method_getImplementation(class_getInstanceMethod(currentClass, @selector(resume))); - IMP superclassResumeIMP = method_getImplementation(class_getInstanceMethod(superClass, @selector(resume))); - if (classResumeIMP != superclassResumeIMP && - originalAFResumeIMP != classResumeIMP) { - [self swizzleResumeAndSuspendMethodForClass:currentClass]; - } - currentClass = [currentClass superclass]; - } - - [localDataTask cancel]; - [session finishTasksAndInvalidate]; - } -} - -+ (void)swizzleResumeAndSuspendMethodForClass:(Class)theClass { - Method afResumeMethod = class_getInstanceMethod(self, @selector(af_resume)); - Method afSuspendMethod = class_getInstanceMethod(self, @selector(af_suspend)); - - if (af_addMethod(theClass, @selector(af_resume), afResumeMethod)) { - af_swizzleSelector(theClass, @selector(resume), @selector(af_resume)); - } - - if (af_addMethod(theClass, @selector(af_suspend), afSuspendMethod)) { - af_swizzleSelector(theClass, @selector(suspend), @selector(af_suspend)); - } -} - -- (NSURLSessionTaskState)state { - NSAssert(NO, @"State method should never be called in the actual dummy class"); - return NSURLSessionTaskStateCanceling; -} - -- (void)af_resume { - NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state"); - NSURLSessionTaskState state = [self state]; - [self af_resume]; - - if (state != NSURLSessionTaskStateRunning) { - [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidResumeNotification object:self]; - } -} - -- (void)af_suspend { - NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state"); - NSURLSessionTaskState state = [self state]; - [self af_suspend]; - - if (state != NSURLSessionTaskStateSuspended) { - [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidSuspendNotification object:self]; - } -} -@end - -#pragma mark - - -@interface AFURLSessionManager () -@property (readwrite, nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration; -@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue; -@property (readwrite, nonatomic, strong) NSURLSession *session; -@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier; -@property (readonly, nonatomic, copy) NSString *taskDescriptionForSessionTasks; -@property (readwrite, nonatomic, strong) NSLock *lock; -@property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid; -@property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge; -@property (readwrite, nonatomic, copy) AFURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession; -@property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection; -@property (readwrite, nonatomic, copy) AFURLSessionTaskDidReceiveAuthenticationChallengeBlock taskDidReceiveAuthenticationChallenge; -@property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream; -@property (readwrite, nonatomic, copy) AFURLSessionTaskDidSendBodyDataBlock taskDidSendBodyData; -@property (readwrite, nonatomic, copy) AFURLSessionTaskDidCompleteBlock taskDidComplete; -@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveResponseBlock dataTaskDidReceiveResponse; -@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidBecomeDownloadTaskBlock dataTaskDidBecomeDownloadTask; -@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveDataBlock dataTaskDidReceiveData; -@property (readwrite, nonatomic, copy) AFURLSessionDataTaskWillCacheResponseBlock dataTaskWillCacheResponse; -@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; -@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidWriteDataBlock downloadTaskDidWriteData; -@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidResumeBlock downloadTaskDidResume; -@end - -@implementation AFURLSessionManager - -- (instancetype)init { - return [self initWithSessionConfiguration:nil]; -} - -- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { - self = [super init]; - if (!self) { - return nil; - } - - if (!configuration) { - configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; - } - - self.sessionConfiguration = configuration; - - self.operationQueue = [[NSOperationQueue alloc] init]; - self.operationQueue.maxConcurrentOperationCount = 1; - - self.session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue]; - - self.responseSerializer = [AFJSONResponseSerializer serializer]; - - self.securityPolicy = [AFSecurityPolicy defaultPolicy]; - -#if !TARGET_OS_WATCH - self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; -#endif - - self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init]; - - self.lock = [[NSLock alloc] init]; - self.lock.name = AFURLSessionManagerLockName; - - [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { - for (NSURLSessionDataTask *task in dataTasks) { - [self addDelegateForDataTask:task uploadProgress:nil downloadProgress:nil completionHandler:nil]; - } - - for (NSURLSessionUploadTask *uploadTask in uploadTasks) { - [self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil]; - } - - for (NSURLSessionDownloadTask *downloadTask in downloadTasks) { - [self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil]; - } - }]; - - return self; -} - -- (void)dealloc { - [[NSNotificationCenter defaultCenter] removeObserver:self]; -} - -#pragma mark - - -- (NSString *)taskDescriptionForSessionTasks { - return [NSString stringWithFormat:@"%p", self]; -} - -- (void)taskDidResume:(NSNotification *)notification { - NSURLSessionTask *task = notification.object; - if ([task respondsToSelector:@selector(taskDescription)]) { - if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidResumeNotification object:task]; - }); - } - } -} - -- (void)taskDidSuspend:(NSNotification *)notification { - NSURLSessionTask *task = notification.object; - if ([task respondsToSelector:@selector(taskDescription)]) { - if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidSuspendNotification object:task]; - }); - } - } -} - -#pragma mark - - -- (AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task { - NSParameterAssert(task); - - AFURLSessionManagerTaskDelegate *delegate = nil; - [self.lock lock]; - delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)]; - [self.lock unlock]; - - return delegate; -} - -- (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate - forTask:(NSURLSessionTask *)task -{ - NSParameterAssert(task); - NSParameterAssert(delegate); - - [self.lock lock]; - self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate; - [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:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler -{ - AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; - delegate.manager = self; - delegate.completionHandler = completionHandler; - - uploadTask.taskDescription = self.taskDescriptionForSessionTasks; - - [self setDelegate:delegate forTask:uploadTask]; - - delegate.uploadProgressBlock = uploadProgressBlock; -} - -- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask - progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock - destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination - completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler -{ - AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] init]; - delegate.manager = self; - delegate.completionHandler = completionHandler; - - if (destination) { - delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session, NSURLSessionDownloadTask *task, NSURL *location) { - return destination(location, task.response); - }; - } - - downloadTask.taskDescription = self.taskDescriptionForSessionTasks; - - [self setDelegate:delegate forTask:downloadTask]; - - delegate.downloadProgressBlock = downloadProgressBlock; -} - -- (void)removeDelegateForTask:(NSURLSessionTask *)task { - NSParameterAssert(task); - - AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; - [self.lock lock]; - [delegate cleanUpProgressForTask:task]; - [self removeNotificationObserverForTask:task]; - [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)]; - [self.lock unlock]; -} - -#pragma mark - - -- (NSArray *)tasksForKeyPath:(NSString *)keyPath { - __block NSArray *tasks = nil; - dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); - [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { - if ([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) { - tasks = dataTasks; - } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) { - tasks = uploadTasks; - } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) { - tasks = downloadTasks; - } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) { - tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"]; - } - - dispatch_semaphore_signal(semaphore); - }]; - - dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); - - return tasks; -} - -- (NSArray *)tasks { - return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; -} - -- (NSArray *)dataTasks { - return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; -} - -- (NSArray *)uploadTasks { - return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; -} - -- (NSArray *)downloadTasks { - return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; -} - -#pragma mark - - -- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks { - dispatch_async(dispatch_get_main_queue(), ^{ - if (cancelPendingTasks) { - [self.session invalidateAndCancel]; - } else { - [self.session finishTasksAndInvalidate]; - } - }); -} - -#pragma mark - - -- (void)setResponseSerializer:(id )responseSerializer { - NSParameterAssert(responseSerializer); - - _responseSerializer = responseSerializer; -} - -#pragma mark - -- (void)addNotificationObserverForTask:(NSURLSessionTask *)task { - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:task]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:task]; -} - -- (void)removeNotificationObserverForTask:(NSURLSessionTask *)task { - [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidSuspendNotification object:task]; - [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidResumeNotification object:task]; -} - -#pragma mark - - -- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler -{ - return [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:completionHandler]; -} - -- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request - uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock - downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock - completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler { - - __block NSURLSessionDataTask *dataTask = nil; - url_session_manager_create_task_safely(^{ - dataTask = [self.session dataTaskWithRequest:request]; - }); - - [self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler]; - - return dataTask; -} - -#pragma mark - - -- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request - fromFile:(NSURL *)fileURL - progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler -{ - __block NSURLSessionUploadTask *uploadTask = nil; - url_session_manager_create_task_safely(^{ - uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; - }); - - if (!uploadTask && self.attemptsToRecreateUploadTasksForBackgroundSessions && self.session.configuration.identifier) { - for (NSUInteger attempts = 0; !uploadTask && attempts < AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask; attempts++) { - uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; - } - } - - [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; - - return uploadTask; -} - -- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request - fromData:(NSData *)bodyData - progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler -{ - __block NSURLSessionUploadTask *uploadTask = nil; - url_session_manager_create_task_safely(^{ - uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData]; - }); - - [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; - - return uploadTask; -} - -- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request - progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock - completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler -{ - __block NSURLSessionUploadTask *uploadTask = nil; - url_session_manager_create_task_safely(^{ - uploadTask = [self.session uploadTaskWithStreamedRequest:request]; - }); - - [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; - - return uploadTask; -} - -#pragma mark - - -- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request - progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock - destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination - completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler -{ - __block NSURLSessionDownloadTask *downloadTask = nil; - url_session_manager_create_task_safely(^{ - downloadTask = [self.session downloadTaskWithRequest:request]; - }); - - [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler]; - - return downloadTask; -} - -- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData - progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock - destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination - completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler -{ - __block NSURLSessionDownloadTask *downloadTask = nil; - url_session_manager_create_task_safely(^{ - downloadTask = [self.session downloadTaskWithResumeData:resumeData]; - }); - - [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler]; - - return downloadTask; -} - -#pragma mark - -- (NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task { - return [[self delegateForTask:task] uploadProgress]; -} - -- (NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task { - return [[self delegateForTask:task] downloadProgress]; -} - -#pragma mark - - -- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block { - self.sessionDidBecomeInvalid = block; -} - -- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block { - self.sessionDidReceiveAuthenticationChallenge = block; -} - -- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block { - self.didFinishEventsForBackgroundURLSession = block; -} - -#pragma mark - - -- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block { - self.taskNeedNewBodyStream = block; -} - -- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block { - self.taskWillPerformHTTPRedirection = block; -} - -- (void)setTaskDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block { - self.taskDidReceiveAuthenticationChallenge = block; -} - -- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block { - self.taskDidSendBodyData = block; -} - -- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block { - self.taskDidComplete = block; -} - -#pragma mark - - -- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block { - self.dataTaskDidReceiveResponse = block; -} - -- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block { - self.dataTaskDidBecomeDownloadTask = block; -} - -- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block { - self.dataTaskDidReceiveData = block; -} - -- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block { - self.dataTaskWillCacheResponse = block; -} - -#pragma mark - - -- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block { - self.downloadTaskDidFinishDownloading = block; -} - -- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block { - self.downloadTaskDidWriteData = block; -} - -- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block { - self.downloadTaskDidResume = block; -} - -#pragma mark - NSObject - -- (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, self.session, self.operationQueue]; -} - -- (BOOL)respondsToSelector:(SEL)selector { - if (selector == @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)) { - return self.taskWillPerformHTTPRedirection != nil; - } else if (selector == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) { - return self.dataTaskDidReceiveResponse != nil; - } else if (selector == @selector(URLSession:dataTask:willCacheResponse:completionHandler:)) { - return self.dataTaskWillCacheResponse != nil; - } else if (selector == @selector(URLSessionDidFinishEventsForBackgroundURLSession:)) { - return self.didFinishEventsForBackgroundURLSession != nil; - } - - return [[self class] instancesRespondToSelector:selector]; -} - -#pragma mark - NSURLSessionDelegate - -- (void)URLSession:(NSURLSession *)session -didBecomeInvalidWithError:(NSError *)error -{ - if (self.sessionDidBecomeInvalid) { - self.sessionDidBecomeInvalid(session, error); - } - - [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session]; -} - -- (void)URLSession:(NSURLSession *)session -didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge - completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler -{ - NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; - __block NSURLCredential *credential = nil; - - if (self.sessionDidReceiveAuthenticationChallenge) { - disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential); - } else { - if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { - if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { - credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; - if (credential) { - disposition = NSURLSessionAuthChallengeUseCredential; - } else { - disposition = NSURLSessionAuthChallengePerformDefaultHandling; - } - } else { - disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; - } - } else { - disposition = NSURLSessionAuthChallengePerformDefaultHandling; - } - } - - if (completionHandler) { - completionHandler(disposition, credential); - } -} - -#pragma mark - NSURLSessionTaskDelegate - -- (void)URLSession:(NSURLSession *)session - task:(NSURLSessionTask *)task -willPerformHTTPRedirection:(NSHTTPURLResponse *)response - newRequest:(NSURLRequest *)request - completionHandler:(void (^)(NSURLRequest *))completionHandler -{ - NSURLRequest *redirectRequest = request; - - if (self.taskWillPerformHTTPRedirection) { - redirectRequest = self.taskWillPerformHTTPRedirection(session, task, response, request); - } - - if (completionHandler) { - completionHandler(redirectRequest); - } -} - -- (void)URLSession:(NSURLSession *)session - task:(NSURLSessionTask *)task -didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge - completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler -{ - NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; - __block NSURLCredential *credential = nil; - - if (self.taskDidReceiveAuthenticationChallenge) { - disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential); - } else { - if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { - if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { - disposition = NSURLSessionAuthChallengeUseCredential; - credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; - } else { - disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; - } - } else { - disposition = NSURLSessionAuthChallengePerformDefaultHandling; - } - } - - if (completionHandler) { - completionHandler(disposition, credential); - } -} - -- (void)URLSession:(NSURLSession *)session - task:(NSURLSessionTask *)task - needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler -{ - NSInputStream *inputStream = nil; - - if (self.taskNeedNewBodyStream) { - inputStream = self.taskNeedNewBodyStream(session, task); - } else if (task.originalRequest.HTTPBodyStream && [task.originalRequest.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) { - inputStream = [task.originalRequest.HTTPBodyStream copy]; - } - - if (completionHandler) { - completionHandler(inputStream); - } -} - -- (void)URLSession:(NSURLSession *)session - task:(NSURLSessionTask *)task - didSendBodyData:(int64_t)bytesSent - totalBytesSent:(int64_t)totalBytesSent -totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend -{ - - int64_t totalUnitCount = totalBytesExpectedToSend; - if(totalUnitCount == NSURLSessionTransferSizeUnknown) { - NSString *contentLength = [task.originalRequest valueForHTTPHeaderField:@"Content-Length"]; - if(contentLength) { - totalUnitCount = (int64_t) [contentLength longLongValue]; - } - } - - if (self.taskDidSendBodyData) { - self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalUnitCount); - } -} - -- (void)URLSession:(NSURLSession *)session - task:(NSURLSessionTask *)task -didCompleteWithError:(NSError *)error -{ - AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; - - // delegate may be nil when completing a task in the background - if (delegate) { - [delegate URLSession:session task:task didCompleteWithError:error]; - - [self removeDelegateForTask:task]; - } - - if (self.taskDidComplete) { - self.taskDidComplete(session, task, error); - } -} - -#pragma mark - NSURLSessionDataDelegate - -- (void)URLSession:(NSURLSession *)session - dataTask:(NSURLSessionDataTask *)dataTask -didReceiveResponse:(NSURLResponse *)response - completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler -{ - NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow; - - if (self.dataTaskDidReceiveResponse) { - disposition = self.dataTaskDidReceiveResponse(session, dataTask, response); - } - - if (completionHandler) { - completionHandler(disposition); - } -} - -- (void)URLSession:(NSURLSession *)session - dataTask:(NSURLSessionDataTask *)dataTask -didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask -{ - AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; - if (delegate) { - [self removeDelegateForTask:dataTask]; - [self setDelegate:delegate forTask:downloadTask]; - } - - if (self.dataTaskDidBecomeDownloadTask) { - self.dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask); - } -} - -- (void)URLSession:(NSURLSession *)session - dataTask:(NSURLSessionDataTask *)dataTask - didReceiveData:(NSData *)data -{ - - AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; - [delegate URLSession:session dataTask:dataTask didReceiveData:data]; - - if (self.dataTaskDidReceiveData) { - self.dataTaskDidReceiveData(session, dataTask, data); - } -} - -- (void)URLSession:(NSURLSession *)session - dataTask:(NSURLSessionDataTask *)dataTask - willCacheResponse:(NSCachedURLResponse *)proposedResponse - completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler -{ - NSCachedURLResponse *cachedResponse = proposedResponse; - - if (self.dataTaskWillCacheResponse) { - cachedResponse = self.dataTaskWillCacheResponse(session, dataTask, proposedResponse); - } - - if (completionHandler) { - completionHandler(cachedResponse); - } -} - -- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session { - if (self.didFinishEventsForBackgroundURLSession) { - dispatch_async(dispatch_get_main_queue(), ^{ - self.didFinishEventsForBackgroundURLSession(session); - }); - } -} - -#pragma mark - NSURLSessionDownloadDelegate - -- (void)URLSession:(NSURLSession *)session - downloadTask:(NSURLSessionDownloadTask *)downloadTask -didFinishDownloadingToURL:(NSURL *)location -{ - AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; - if (self.downloadTaskDidFinishDownloading) { - NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); - if (fileURL) { - delegate.downloadFileURL = fileURL; - NSError *error = nil; - [[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error]; - if (error) { - [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo]; - } - - return; - } - } - - if (delegate) { - [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location]; - } -} - -- (void)URLSession:(NSURLSession *)session - downloadTask:(NSURLSessionDownloadTask *)downloadTask - didWriteData:(int64_t)bytesWritten - totalBytesWritten:(int64_t)totalBytesWritten -totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite -{ - if (self.downloadTaskDidWriteData) { - self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); - } -} - -- (void)URLSession:(NSURLSession *)session - downloadTask:(NSURLSessionDownloadTask *)downloadTask - didResumeAtOffset:(int64_t)fileOffset -expectedTotalBytes:(int64_t)expectedTotalBytes -{ - if (self.downloadTaskDidResume) { - self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes); - } -} - -#pragma mark - NSSecureCoding - -+ (BOOL)supportsSecureCoding { - return YES; -} - -- (instancetype)initWithCoder:(NSCoder *)decoder { - NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; - - self = [self initWithSessionConfiguration:configuration]; - if (!self) { - return nil; - } - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)coder { - [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; -} - -#pragma mark - NSCopying - -- (instancetype)copyWithZone:(NSZone *)zone { - return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration]; -} - -@end diff --git a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/LICENSE b/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/LICENSE deleted file mode 100644 index 3fbc2c9..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/README.md b/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/README.md deleted file mode 100644 index 53cb202..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/AFNetworking/README.md +++ /dev/null @@ -1,320 +0,0 @@ -

- AFNetworking -

- -[![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.svg)](https://travis-ci.org/AFNetworking/AFNetworking) -[![codecov.io](https://codecov.io/github/AFNetworking/AFNetworking/coverage.svg?branch=master)](https://codecov.io/github/AFNetworking/AFNetworking?branch=master) -[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/AFNetworking.svg)](https://img.shields.io/cocoapods/v/AFNetworking.svg) -[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) -[![Platform](https://img.shields.io/cocoapods/p/AFNetworking.svg?style=flat)](http://cocoadocs.org/docsets/AFNetworking) -[![Twitter](https://img.shields.io/badge/twitter-@AFNetworking-blue.svg?style=flat)](http://twitter.com/AFNetworking) - -AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of the [Foundation URL Loading System](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html), extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. - -Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac. - -Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did! - -## How To Get Started - -- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/archive/master.zip) and try out the included Mac and iPhone example apps -- Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles on the Wiki](https://github.com/AFNetworking/AFNetworking/wiki) -- Check out the [documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at all of the APIs available in AFNetworking -- Read the [AFNetworking 3.0 Migration Guide](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-3.0-Migration-Guide) for an overview of the architectural changes from 2.0. - -## Communication - -- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). (Tag 'afnetworking') -- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). -- If you **found a bug**, _and can provide steps to reliably reproduce it_, open an issue. -- If you **have a feature request**, open an issue. -- If you **want to contribute**, submit a pull request. - -## Installation -AFNetworking supports multiple methods for installing the library in a project. - -## Installation with CocoaPods - -[CocoaPods](http://cocoapods.org) is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries like AFNetworking in your projects. See the ["Getting Started" guide for more information](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking). You can install it with the following command: - -```bash -$ gem install cocoapods -``` - -> CocoaPods 0.39.0+ is required to build AFNetworking 3.0.0+. - -#### Podfile - -To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your `Podfile`: - -```ruby -source 'https://github.com/CocoaPods/Specs.git' -platform :ios, '8.0' - -pod 'AFNetworking', '~> 3.0' -``` - -Then, run the following command: - -```bash -$ pod install -``` - -### Installation with Carthage - -[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. - -You can install Carthage with [Homebrew](http://brew.sh/) using the following command: - -```bash -$ brew update -$ brew install carthage -``` - -To integrate AFNetworking into your Xcode project using Carthage, specify it in your `Cartfile`: - -```ogdl -github "AFNetworking/AFNetworking" ~> 3.0 -``` - -Run `carthage` to build the framework and drag the built `AFNetworking.framework` into your Xcode project. - -## Requirements - -| AFNetworking Version | Minimum iOS Target | Minimum OS X Target | Minimum watchOS Target | Minimum tvOS Target | Notes | -|:--------------------:|:---------------------------:|:----------------------------:|:----------------------------:|:----------------------------:|:-------------------------------------------------------------------------:| -| 3.x | iOS 7 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Xcode 7+ is required. `NSURLConnectionOperation` support has been removed. | -| 2.6 -> 2.6.3 | iOS 7 | OS X 10.9 | watchOS 2.0 | n/a | Xcode 7+ is required. | -| 2.0 -> 2.5.4 | iOS 6 | OS X 10.8 | n/a | n/a | Xcode 5+ is required. `NSURLSession` subspec requires iOS 7 or OS X 10.9. | -| 1.x | iOS 5 | Mac OS X 10.7 | n/a | n/a | -| 0.10.x | iOS 4 | Mac OS X 10.6 | n/a | n/a | - -(OS X projects must support [64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)). - -> Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs. - -## Architecture - -### NSURLSession - -- `AFURLSessionManager` -- `AFHTTPSessionManager` - -### Serialization - -* `` - - `AFHTTPRequestSerializer` - - `AFJSONRequestSerializer` - - `AFPropertyListRequestSerializer` -* `` - - `AFHTTPResponseSerializer` - - `AFJSONResponseSerializer` - - `AFXMLParserResponseSerializer` - - `AFXMLDocumentResponseSerializer` _(Mac OS X)_ - - `AFPropertyListResponseSerializer` - - `AFImageResponseSerializer` - - `AFCompoundResponseSerializer` - -### Additional Functionality - -- `AFSecurityPolicy` -- `AFNetworkReachabilityManager` - -## Usage - -### AFURLSessionManager - -`AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. - -#### Creating a Download Task - -```objective-c -NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; -AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; - -NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"]; -NSURLRequest *request = [NSURLRequest requestWithURL:URL]; - -NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { - NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; - return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; -} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { - NSLog(@"File downloaded to: %@", filePath); -}]; -[downloadTask resume]; -``` - -#### Creating an Upload Task - -```objective-c -NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; -AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; - -NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"]; -NSURLRequest *request = [NSURLRequest requestWithURL:URL]; - -NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"]; -NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { - if (error) { - NSLog(@"Error: %@", error); - } else { - NSLog(@"Success: %@ %@", response, responseObject); - } -}]; -[uploadTask resume]; -``` - -#### Creating an Upload Task for a Multi-Part Request, with Progress - -```objective-c -NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) { - [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil]; - } error:nil]; - -AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; - -NSURLSessionUploadTask *uploadTask; -uploadTask = [manager - uploadTaskWithStreamedRequest:request - progress:^(NSProgress * _Nonnull uploadProgress) { - // This is not called back on the main queue. - // You are responsible for dispatching to the main queue for UI updates - dispatch_async(dispatch_get_main_queue(), ^{ - //Update the progress view - [progressView setProgress:uploadProgress.fractionCompleted]; - }); - } - completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { - if (error) { - NSLog(@"Error: %@", error); - } else { - NSLog(@"%@ %@", response, responseObject); - } - }]; - -[uploadTask resume]; -``` - -#### Creating a Data Task - -```objective-c -NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; -AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; - -NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"]; -NSURLRequest *request = [NSURLRequest requestWithURL:URL]; - -NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { - if (error) { - NSLog(@"Error: %@", error); - } else { - NSLog(@"%@ %@", response, responseObject); - } -}]; -[dataTask resume]; -``` - ---- - -### Request Serialization - -Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body. - -```objective-c -NSString *URLString = @"http://example.com"; -NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]}; -``` - -#### Query String Parameter Encoding - -```objective-c -[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil]; -``` - - GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3 - -#### URL Form Parameter Encoding - -```objective-c -[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; -``` - - POST http://example.com/ - Content-Type: application/x-www-form-urlencoded - - foo=bar&baz[]=1&baz[]=2&baz[]=3 - -#### JSON Parameter Encoding - -```objective-c -[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; -``` - - POST http://example.com/ - Content-Type: application/json - - {"foo": "bar", "baz": [1,2,3]} - ---- - -### Network Reachability Manager - -`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. - -* Do not use Reachability to determine if the original request should be sent. - * You should try to send it. -* You can use Reachability to determine when a request should be automatically retried. - * Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something. -* Network reachability is a useful tool for determining why a request might have failed. - * After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out." - -See also [WWDC 2012 session 706, "Networking Best Practices."](https://developer.apple.com/videos/play/wwdc2012-706/). - -#### Shared Network Reachability - -```objective-c -[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { - NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status)); -}]; - -[[AFNetworkReachabilityManager sharedManager] startMonitoring]; -``` - ---- - -### Security Policy - -`AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. - -Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled. - -#### Allowing Invalid SSL Certificates - -```objective-c -AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; -manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production -``` - ---- - -## Unit Tests - -AFNetworking includes a suite of unit tests within the Tests subdirectory. These tests can be run simply be executed the test action on the platform framework you would like to test. - -## Credits - -AFNetworking is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). - -AFNetworking was originally created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla). - -AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/). - -And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors). - -### Security Disclosure - -If you believe you have identified a security vulnerability with AFNetworking, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. - -## License - -AFNetworking is released under the MIT license. See LICENSE for details. diff --git a/Demo/StudyplusSDKDemo/AFNetworking/LICENSE b/Demo/StudyplusSDKDemo/AFNetworking/LICENSE deleted file mode 100644 index 3fbc2c9..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2011–2016 Alamofire Software Foundation (http://alamofire.org/) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/Demo/StudyplusSDKDemo/AFNetworking/README.md b/Demo/StudyplusSDKDemo/AFNetworking/README.md deleted file mode 100644 index 53cb202..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/README.md +++ /dev/null @@ -1,320 +0,0 @@ -

- AFNetworking -

- -[![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.svg)](https://travis-ci.org/AFNetworking/AFNetworking) -[![codecov.io](https://codecov.io/github/AFNetworking/AFNetworking/coverage.svg?branch=master)](https://codecov.io/github/AFNetworking/AFNetworking?branch=master) -[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/AFNetworking.svg)](https://img.shields.io/cocoapods/v/AFNetworking.svg) -[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) -[![Platform](https://img.shields.io/cocoapods/p/AFNetworking.svg?style=flat)](http://cocoadocs.org/docsets/AFNetworking) -[![Twitter](https://img.shields.io/badge/twitter-@AFNetworking-blue.svg?style=flat)](http://twitter.com/AFNetworking) - -AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of the [Foundation URL Loading System](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html), extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. - -Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac. - -Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did! - -## How To Get Started - -- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/archive/master.zip) and try out the included Mac and iPhone example apps -- Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles on the Wiki](https://github.com/AFNetworking/AFNetworking/wiki) -- Check out the [documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at all of the APIs available in AFNetworking -- Read the [AFNetworking 3.0 Migration Guide](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-3.0-Migration-Guide) for an overview of the architectural changes from 2.0. - -## Communication - -- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). (Tag 'afnetworking') -- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). -- If you **found a bug**, _and can provide steps to reliably reproduce it_, open an issue. -- If you **have a feature request**, open an issue. -- If you **want to contribute**, submit a pull request. - -## Installation -AFNetworking supports multiple methods for installing the library in a project. - -## Installation with CocoaPods - -[CocoaPods](http://cocoapods.org) is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries like AFNetworking in your projects. See the ["Getting Started" guide for more information](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking). You can install it with the following command: - -```bash -$ gem install cocoapods -``` - -> CocoaPods 0.39.0+ is required to build AFNetworking 3.0.0+. - -#### Podfile - -To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your `Podfile`: - -```ruby -source 'https://github.com/CocoaPods/Specs.git' -platform :ios, '8.0' - -pod 'AFNetworking', '~> 3.0' -``` - -Then, run the following command: - -```bash -$ pod install -``` - -### Installation with Carthage - -[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. - -You can install Carthage with [Homebrew](http://brew.sh/) using the following command: - -```bash -$ brew update -$ brew install carthage -``` - -To integrate AFNetworking into your Xcode project using Carthage, specify it in your `Cartfile`: - -```ogdl -github "AFNetworking/AFNetworking" ~> 3.0 -``` - -Run `carthage` to build the framework and drag the built `AFNetworking.framework` into your Xcode project. - -## Requirements - -| AFNetworking Version | Minimum iOS Target | Minimum OS X Target | Minimum watchOS Target | Minimum tvOS Target | Notes | -|:--------------------:|:---------------------------:|:----------------------------:|:----------------------------:|:----------------------------:|:-------------------------------------------------------------------------:| -| 3.x | iOS 7 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Xcode 7+ is required. `NSURLConnectionOperation` support has been removed. | -| 2.6 -> 2.6.3 | iOS 7 | OS X 10.9 | watchOS 2.0 | n/a | Xcode 7+ is required. | -| 2.0 -> 2.5.4 | iOS 6 | OS X 10.8 | n/a | n/a | Xcode 5+ is required. `NSURLSession` subspec requires iOS 7 or OS X 10.9. | -| 1.x | iOS 5 | Mac OS X 10.7 | n/a | n/a | -| 0.10.x | iOS 4 | Mac OS X 10.6 | n/a | n/a | - -(OS X projects must support [64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)). - -> Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs. - -## Architecture - -### NSURLSession - -- `AFURLSessionManager` -- `AFHTTPSessionManager` - -### Serialization - -* `` - - `AFHTTPRequestSerializer` - - `AFJSONRequestSerializer` - - `AFPropertyListRequestSerializer` -* `` - - `AFHTTPResponseSerializer` - - `AFJSONResponseSerializer` - - `AFXMLParserResponseSerializer` - - `AFXMLDocumentResponseSerializer` _(Mac OS X)_ - - `AFPropertyListResponseSerializer` - - `AFImageResponseSerializer` - - `AFCompoundResponseSerializer` - -### Additional Functionality - -- `AFSecurityPolicy` -- `AFNetworkReachabilityManager` - -## Usage - -### AFURLSessionManager - -`AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. - -#### Creating a Download Task - -```objective-c -NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; -AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; - -NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"]; -NSURLRequest *request = [NSURLRequest requestWithURL:URL]; - -NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { - NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; - return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; -} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { - NSLog(@"File downloaded to: %@", filePath); -}]; -[downloadTask resume]; -``` - -#### Creating an Upload Task - -```objective-c -NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; -AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; - -NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"]; -NSURLRequest *request = [NSURLRequest requestWithURL:URL]; - -NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"]; -NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { - if (error) { - NSLog(@"Error: %@", error); - } else { - NSLog(@"Success: %@ %@", response, responseObject); - } -}]; -[uploadTask resume]; -``` - -#### Creating an Upload Task for a Multi-Part Request, with Progress - -```objective-c -NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) { - [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil]; - } error:nil]; - -AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; - -NSURLSessionUploadTask *uploadTask; -uploadTask = [manager - uploadTaskWithStreamedRequest:request - progress:^(NSProgress * _Nonnull uploadProgress) { - // This is not called back on the main queue. - // You are responsible for dispatching to the main queue for UI updates - dispatch_async(dispatch_get_main_queue(), ^{ - //Update the progress view - [progressView setProgress:uploadProgress.fractionCompleted]; - }); - } - completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { - if (error) { - NSLog(@"Error: %@", error); - } else { - NSLog(@"%@ %@", response, responseObject); - } - }]; - -[uploadTask resume]; -``` - -#### Creating a Data Task - -```objective-c -NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; -AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; - -NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"]; -NSURLRequest *request = [NSURLRequest requestWithURL:URL]; - -NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { - if (error) { - NSLog(@"Error: %@", error); - } else { - NSLog(@"%@ %@", response, responseObject); - } -}]; -[dataTask resume]; -``` - ---- - -### Request Serialization - -Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body. - -```objective-c -NSString *URLString = @"http://example.com"; -NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]}; -``` - -#### Query String Parameter Encoding - -```objective-c -[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil]; -``` - - GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3 - -#### URL Form Parameter Encoding - -```objective-c -[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; -``` - - POST http://example.com/ - Content-Type: application/x-www-form-urlencoded - - foo=bar&baz[]=1&baz[]=2&baz[]=3 - -#### JSON Parameter Encoding - -```objective-c -[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; -``` - - POST http://example.com/ - Content-Type: application/json - - {"foo": "bar", "baz": [1,2,3]} - ---- - -### Network Reachability Manager - -`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. - -* Do not use Reachability to determine if the original request should be sent. - * You should try to send it. -* You can use Reachability to determine when a request should be automatically retried. - * Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something. -* Network reachability is a useful tool for determining why a request might have failed. - * After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out." - -See also [WWDC 2012 session 706, "Networking Best Practices."](https://developer.apple.com/videos/play/wwdc2012-706/). - -#### Shared Network Reachability - -```objective-c -[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { - NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status)); -}]; - -[[AFNetworkReachabilityManager sharedManager] startMonitoring]; -``` - ---- - -### Security Policy - -`AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. - -Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled. - -#### Allowing Invalid SSL Certificates - -```objective-c -AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; -manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production -``` - ---- - -## Unit Tests - -AFNetworking includes a suite of unit tests within the Tests subdirectory. These tests can be run simply be executed the test action on the platform framework you would like to test. - -## Credits - -AFNetworking is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). - -AFNetworking was originally created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla). - -AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/). - -And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors). - -### Security Disclosure - -If you believe you have identified a security vulnerability with AFNetworking, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. - -## License - -AFNetworking is released under the MIT license. See LICENSE for details. diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h deleted file mode 100644 index 9bdc15c..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h +++ /dev/null @@ -1,149 +0,0 @@ -// AFAutoPurgingImageCache.h -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#import - -#if TARGET_OS_IOS || TARGET_OS_TV -#import - -NS_ASSUME_NONNULL_BEGIN - -/** - The `AFImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously. - */ -@protocol AFImageCache - -/** - Adds the image to the cache with the given identifier. - - @param image The image to cache. - @param identifier The unique identifier for the image in the cache. - */ -- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier; - -/** - Removes the image from the cache matching the given identifier. - - @param identifier The unique identifier for the image in the cache. - - @return A BOOL indicating whether or not the image was removed from the cache. - */ -- (BOOL)removeImageWithIdentifier:(NSString *)identifier; - -/** - Removes all images from the cache. - - @return A BOOL indicating whether or not all images were removed from the cache. - */ -- (BOOL)removeAllImages; - -/** - Returns the image in the cache associated with the given identifier. - - @param identifier The unique identifier for the image in the cache. - - @return An image for the matching identifier, or nil. - */ -- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier; -@end - - -/** - The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and fetching images from a cache given an `NSURLRequest` and additional identifier. - */ -@protocol AFImageRequestCache - -/** - Adds the image to the cache using an identifier created from the request and additional identifier. - - @param image The image to cache. - @param request The unique URL request identifing the image asset. - @param identifier The additional identifier to apply to the URL request to identify the image. - */ -- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; - -/** - Removes the image from the cache using an identifier created from the request and additional identifier. - - @param request The unique URL request identifing the image asset. - @param identifier The additional identifier to apply to the URL request to identify the image. - - @return A BOOL indicating whether or not all images were removed from the cache. - */ -- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; - -/** - Returns the image from the cache associated with an identifier created from the request and additional identifier. - - @param request The unique URL request identifing the image asset. - @param identifier The additional identifier to apply to the URL request to identify the image. - - @return An image for the matching request and identifier, or nil. - */ -- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; - -@end - -/** - The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated. - */ -@interface AFAutoPurgingImageCache : NSObject - -/** - The total memory capacity of the cache in bytes. - */ -@property (nonatomic, assign) UInt64 memoryCapacity; - -/** - The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit. - */ -@property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge; - -/** - The current total memory usage in bytes of all images stored within the cache. - */ -@property (nonatomic, assign, readonly) UInt64 memoryUsage; - -/** - Initialies the `AutoPurgingImageCache` instance with default values for memory capacity and preferred memory usage after purge limit. `memoryCapcity` defaults to `100 MB`. `preferredMemoryUsageAfterPurge` defaults to `60 MB`. - - @return The new `AutoPurgingImageCache` instance. - */ -- (instancetype)init; - -/** - Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage - after purge limit. - - @param memoryCapacity The total memory capacity of the cache in bytes. - @param preferredMemoryCapacity The preferred memory usage after purge in bytes. - - @return The new `AutoPurgingImageCache` instance. - */ -- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity; - -@end - -NS_ASSUME_NONNULL_END - -#endif - diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m deleted file mode 100644 index 1f40715..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m +++ /dev/null @@ -1,201 +0,0 @@ -// AFAutoPurgingImageCache.m -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#if TARGET_OS_IOS || TARGET_OS_TV - -#import "AFAutoPurgingImageCache.h" - -@interface AFCachedImage : NSObject - -@property (nonatomic, strong) UIImage *image; -@property (nonatomic, strong) NSString *identifier; -@property (nonatomic, assign) UInt64 totalBytes; -@property (nonatomic, strong) NSDate *lastAccessDate; -@property (nonatomic, assign) UInt64 currentMemoryUsage; - -@end - -@implementation AFCachedImage - --(instancetype)initWithImage:(UIImage *)image identifier:(NSString *)identifier { - if (self = [self init]) { - self.image = image; - self.identifier = identifier; - - CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale); - CGFloat bytesPerPixel = 4.0; - CGFloat bytesPerSize = imageSize.width * imageSize.height; - self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerSize; - self.lastAccessDate = [NSDate date]; - } - return self; -} - -- (UIImage*)accessImage { - self.lastAccessDate = [NSDate date]; - return self.image; -} - -- (NSString *)description { - NSString *descriptionString = [NSString stringWithFormat:@"Idenfitier: %@ lastAccessDate: %@ ", self.identifier, self.lastAccessDate]; - return descriptionString; - -} - -@end - -@interface AFAutoPurgingImageCache () -@property (nonatomic, strong) NSMutableDictionary *cachedImages; -@property (nonatomic, assign) UInt64 currentMemoryUsage; -@property (nonatomic, strong) dispatch_queue_t synchronizationQueue; -@end - -@implementation AFAutoPurgingImageCache - -- (instancetype)init { - return [self initWithMemoryCapacity:100 * 1024 * 1024 preferredMemoryCapacity:60 * 1024 * 1024]; -} - -- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity { - if (self = [super init]) { - self.memoryCapacity = memoryCapacity; - self.preferredMemoryUsageAfterPurge = preferredMemoryCapacity; - self.cachedImages = [[NSMutableDictionary alloc] init]; - - NSString *queueName = [NSString stringWithFormat:@"com.alamofire.autopurgingimagecache-%@", [[NSUUID UUID] UUIDString]]; - self.synchronizationQueue = dispatch_queue_create([queueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT); - - [[NSNotificationCenter defaultCenter] - addObserver:self - selector:@selector(removeAllImages) - name:UIApplicationDidReceiveMemoryWarningNotification - object:nil]; - - } - return self; -} - -- (void)dealloc { - [[NSNotificationCenter defaultCenter] removeObserver:self]; -} - -- (UInt64)memoryUsage { - __block UInt64 result = 0; - dispatch_sync(self.synchronizationQueue, ^{ - result = self.currentMemoryUsage; - }); - return result; -} - -- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier { - dispatch_barrier_async(self.synchronizationQueue, ^{ - AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier]; - - AFCachedImage *previousCachedImage = self.cachedImages[identifier]; - if (previousCachedImage != nil) { - self.currentMemoryUsage -= previousCachedImage.totalBytes; - } - - self.cachedImages[identifier] = cacheImage; - self.currentMemoryUsage += cacheImage.totalBytes; - }); - - dispatch_barrier_async(self.synchronizationQueue, ^{ - if (self.currentMemoryUsage > self.memoryCapacity) { - UInt64 bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge; - NSMutableArray *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues]; - NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate" - ascending:YES]; - [sortedImages sortUsingDescriptors:@[sortDescriptor]]; - - UInt64 bytesPurged = 0; - - for (AFCachedImage *cachedImage in sortedImages) { - [self.cachedImages removeObjectForKey:cachedImage.identifier]; - bytesPurged += cachedImage.totalBytes; - if (bytesPurged >= bytesToPurge) { - break ; - } - } - self.currentMemoryUsage -= bytesPurged; - } - }); -} - -- (BOOL)removeImageWithIdentifier:(NSString *)identifier { - __block BOOL removed = NO; - dispatch_barrier_sync(self.synchronizationQueue, ^{ - AFCachedImage *cachedImage = self.cachedImages[identifier]; - if (cachedImage != nil) { - [self.cachedImages removeObjectForKey:identifier]; - self.currentMemoryUsage -= cachedImage.totalBytes; - removed = YES; - } - }); - return removed; -} - -- (BOOL)removeAllImages { - __block BOOL removed = NO; - dispatch_barrier_sync(self.synchronizationQueue, ^{ - if (self.cachedImages.count > 0) { - [self.cachedImages removeAllObjects]; - self.currentMemoryUsage = 0; - removed = YES; - } - }); - return removed; -} - -- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier { - __block UIImage *image = nil; - dispatch_sync(self.synchronizationQueue, ^{ - AFCachedImage *cachedImage = self.cachedImages[identifier]; - image = [cachedImage accessImage]; - }); - return image; -} - -- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { - [self addImage:image withIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; -} - -- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { - return [self removeImageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; -} - -- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { - return [self imageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; -} - -- (NSString *)imageCacheKeyFromURLRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)additionalIdentifier { - NSString *key = request.URL.absoluteString; - if (additionalIdentifier != nil) { - key = [key stringByAppendingString:additionalIdentifier]; - } - return key; -} - -@end - -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h deleted file mode 100644 index 3903eec..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h +++ /dev/null @@ -1,157 +0,0 @@ -// AFImageDownloader.h -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#if TARGET_OS_IOS || TARGET_OS_TV - -#import -#import "AFAutoPurgingImageCache.h" -#import "AFHTTPSessionManager.h" - -NS_ASSUME_NONNULL_BEGIN - -typedef NS_ENUM(NSInteger, AFImageDownloadPrioritization) { - AFImageDownloadPrioritizationFIFO, - AFImageDownloadPrioritizationLIFO -}; - -/** - The `AFImageDownloadReceipt` is an object vended by the `AFImageDownloader` when starting a data task. It can be used to cancel active tasks running on the `AFImageDownloader` session. As a general rule, image data tasks should be cancelled using the `AFImageDownloadReceipt` instead of calling `cancel` directly on the `task` itself. The `AFImageDownloader` is optimized to handle duplicate task scenarios as well as pending versus active downloads. - */ -@interface AFImageDownloadReceipt : NSObject - -/** - The data task created by the `AFImageDownloader`. -*/ -@property (nonatomic, strong) NSURLSessionDataTask *task; - -/** - The unique identifier for the success and failure blocks when duplicate requests are made. - */ -@property (nonatomic, strong) NSUUID *receiptID; -@end - -/** The `AFImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying `NSURLCache` as well as the in-memory image cache. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation. - */ -@interface AFImageDownloader : NSObject - -/** - The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default. - */ -@property (nonatomic, strong, nullable) id imageCache; - -/** - The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads. - */ -@property (nonatomic, strong) AFHTTPSessionManager *sessionManager; - -/** - Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default. - */ -@property (nonatomic, assign) AFImageDownloadPrioritization downloadPrioritizaton; - -/** - The shared default instance of `AFImageDownloader` initialized with default values. - */ -+ (instancetype)defaultInstance; - -/** - Creates a default `NSURLCache` with common usage parameter values. - - @returns The default `NSURLCache` instance. - */ -+ (NSURLCache *)defaultURLCache; - -/** - Default initializer - - @return An instance of `AFImageDownloader` initialized with default values. - */ -- (instancetype)init; - -/** - Initializes the `AFImageDownloader` instance with the given session manager, download prioritization, maximum active download count and image cache. - - @param sessionManager The session manager to use to download images. - @param downloadPrioritization The download prioritization of the download queue. - @param maximumActiveDownloads The maximum number of active downloads allowed at any given time. Recommend `4`. - @param imageCache The image cache used to store all downloaded images in. - - @return The new `AFImageDownloader` instance. - */ -- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager - downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization - maximumActiveDownloads:(NSInteger)maximumActiveDownloads - imageCache:(nullable id )imageCache; - -/** - Creates a data task using the `sessionManager` instance for the specified URL request. - - If the same data task is already in the queue or currently being downloaded, the success and failure blocks are - appended to the already existing task. Once the task completes, all success or failure blocks attached to the - task are executed in the order they were added. - - @param request The URL request. - @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. - @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. - - @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. - cache and the URL request cache policy allows the cache to be used. - */ -- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request - success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success - failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; - -/** - Creates a data task using the `sessionManager` instance for the specified URL request. - - If the same data task is already in the queue or currently being downloaded, the success and failure blocks are - appended to the already existing task. Once the task completes, all success or failure blocks attached to the - task are executed in the order they were added. - - @param request The URL request. - @param receiptID The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request. - @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. - @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. - - @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. - cache and the URL request cache policy allows the cache to be used. - */ -- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request - withReceiptID:(NSUUID *)receiptID - success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success - failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; - -/** - Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary. - - If the data task is pending in the queue, it will be cancelled if no other success and failure blocks are registered with the data task. If the data task is currently executing or is already completed, the success and failure blocks are removed and will not be called when the task finishes. - - @param imageDownloadReceipt The image download receipt to cancel. - */ -- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt; - -@end - -#endif - -NS_ASSUME_NONNULL_END diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m deleted file mode 100644 index 78477bf..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m +++ /dev/null @@ -1,391 +0,0 @@ -// AFImageDownloader.m -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#if TARGET_OS_IOS || TARGET_OS_TV - -#import "AFImageDownloader.h" -#import "AFHTTPSessionManager.h" - -@interface AFImageDownloaderResponseHandler : NSObject -@property (nonatomic, strong) NSUUID *uuid; -@property (nonatomic, copy) void (^successBlock)(NSURLRequest*, NSHTTPURLResponse*, UIImage*); -@property (nonatomic, copy) void (^failureBlock)(NSURLRequest*, NSHTTPURLResponse*, NSError*); -@end - -@implementation AFImageDownloaderResponseHandler - -- (instancetype)initWithUUID:(NSUUID *)uuid - success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success - failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure { - if (self = [self init]) { - self.uuid = uuid; - self.successBlock = success; - self.failureBlock = failure; - } - return self; -} - -- (NSString *)description { - return [NSString stringWithFormat: @"UUID: %@", [self.uuid UUIDString]]; -} - -@end - -@interface AFImageDownloaderMergedTask : NSObject -@property (nonatomic, strong) NSString *URLIdentifier; -@property (nonatomic, strong) NSUUID *identifier; -@property (nonatomic, strong) NSURLSessionDataTask *task; -@property (nonatomic, strong) NSMutableArray *responseHandlers; - -@end - -@implementation AFImageDownloaderMergedTask - -- (instancetype)initWithURLIdentifier:(NSString *)URLIdentifier identifier:(NSUUID *)identifier task:(NSURLSessionDataTask *)task { - if (self = [self init]) { - self.URLIdentifier = URLIdentifier; - self.task = task; - self.identifier = identifier; - self.responseHandlers = [[NSMutableArray alloc] init]; - } - return self; -} - -- (void)addResponseHandler:(AFImageDownloaderResponseHandler*)handler { - [self.responseHandlers addObject:handler]; -} - -- (void)removeResponseHandler:(AFImageDownloaderResponseHandler*)handler { - [self.responseHandlers removeObject:handler]; -} - -@end - -@implementation AFImageDownloadReceipt - -- (instancetype)initWithReceiptID:(NSUUID *)receiptID task:(NSURLSessionDataTask *)task { - if (self = [self init]) { - self.receiptID = receiptID; - self.task = task; - } - return self; -} - -@end - -@interface AFImageDownloader () - -@property (nonatomic, strong) dispatch_queue_t synchronizationQueue; -@property (nonatomic, strong) dispatch_queue_t responseQueue; - -@property (nonatomic, assign) NSInteger maximumActiveDownloads; -@property (nonatomic, assign) NSInteger activeRequestCount; - -@property (nonatomic, strong) NSMutableArray *queuedMergedTasks; -@property (nonatomic, strong) NSMutableDictionary *mergedTasks; - -@end - - -@implementation AFImageDownloader - -+ (NSURLCache *)defaultURLCache { - return [[NSURLCache alloc] initWithMemoryCapacity:20 * 1024 * 1024 - diskCapacity:150 * 1024 * 1024 - diskPath:@"com.alamofire.imagedownloader"]; -} - -+ (NSURLSessionConfiguration *)defaultURLSessionConfiguration { - NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; - - //TODO set the default HTTP headers - - configuration.HTTPShouldSetCookies = YES; - configuration.HTTPShouldUsePipelining = NO; - - configuration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy; - configuration.allowsCellularAccess = YES; - configuration.timeoutIntervalForRequest = 60.0; - configuration.URLCache = [AFImageDownloader defaultURLCache]; - - return configuration; -} - -- (instancetype)init { - NSURLSessionConfiguration *defaultConfiguration = [self.class defaultURLSessionConfiguration]; - AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:defaultConfiguration]; - sessionManager.responseSerializer = [AFImageResponseSerializer serializer]; - - return [self initWithSessionManager:sessionManager - downloadPrioritization:AFImageDownloadPrioritizationFIFO - maximumActiveDownloads:4 - imageCache:[[AFAutoPurgingImageCache alloc] init]]; -} - -- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager - downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization - maximumActiveDownloads:(NSInteger)maximumActiveDownloads - imageCache:(id )imageCache { - if (self = [super init]) { - self.sessionManager = sessionManager; - - self.downloadPrioritizaton = downloadPrioritization; - self.maximumActiveDownloads = maximumActiveDownloads; - self.imageCache = imageCache; - - self.queuedMergedTasks = [[NSMutableArray alloc] init]; - self.mergedTasks = [[NSMutableDictionary alloc] init]; - self.activeRequestCount = 0; - - NSString *name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.synchronizationqueue-%@", [[NSUUID UUID] UUIDString]]; - self.synchronizationQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL); - - name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.responsequeue-%@", [[NSUUID UUID] UUIDString]]; - self.responseQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT); - } - - return self; -} - -+ (instancetype)defaultInstance { - static AFImageDownloader *sharedInstance = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - sharedInstance = [[self alloc] init]; - }); - return sharedInstance; -} - -- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request - success:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, UIImage * _Nonnull))success - failure:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, NSError * _Nonnull))failure { - return [self downloadImageForURLRequest:request withReceiptID:[NSUUID UUID] success:success failure:failure]; -} - -- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request - withReceiptID:(nonnull NSUUID *)receiptID - success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success - failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure { - __block NSURLSessionDataTask *task = nil; - dispatch_sync(self.synchronizationQueue, ^{ - NSString *URLIdentifier = request.URL.absoluteString; - if (URLIdentifier == nil) { - if (failure) { - NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil]; - dispatch_async(dispatch_get_main_queue(), ^{ - failure(request, nil, error); - }); - } - return; - } - - // 1) Append the success and failure blocks to a pre-existing request if it already exists - AFImageDownloaderMergedTask *existingMergedTask = self.mergedTasks[URLIdentifier]; - if (existingMergedTask != nil) { - AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID success:success failure:failure]; - [existingMergedTask addResponseHandler:handler]; - task = existingMergedTask.task; - return; - } - - // 2) Attempt to load the image from the image cache if the cache policy allows it - switch (request.cachePolicy) { - case NSURLRequestUseProtocolCachePolicy: - case NSURLRequestReturnCacheDataElseLoad: - case NSURLRequestReturnCacheDataDontLoad: { - UIImage *cachedImage = [self.imageCache imageforRequest:request withAdditionalIdentifier:nil]; - if (cachedImage != nil) { - if (success) { - dispatch_async(dispatch_get_main_queue(), ^{ - success(request, nil, cachedImage); - }); - } - return; - } - break; - } - default: - break; - } - - // 3) Create the request and set up authentication, validation and response serialization - NSUUID *mergedTaskIdentifier = [NSUUID UUID]; - NSURLSessionDataTask *createdTask; - __weak __typeof__(self) weakSelf = self; - - createdTask = [self.sessionManager - dataTaskWithRequest:request - completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { - dispatch_async(self.responseQueue, ^{ - __strong __typeof__(weakSelf) strongSelf = weakSelf; - AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier]; - if ([mergedTask.identifier isEqual:mergedTaskIdentifier]) { - mergedTask = [strongSelf safelyRemoveMergedTaskWithURLIdentifier:URLIdentifier]; - if (error) { - for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) { - if (handler.failureBlock) { - dispatch_async(dispatch_get_main_queue(), ^{ - handler.failureBlock(request, (NSHTTPURLResponse*)response, error); - }); - } - } - } else { - [strongSelf.imageCache addImage:responseObject forRequest:request withAdditionalIdentifier:nil]; - - for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) { - if (handler.successBlock) { - dispatch_async(dispatch_get_main_queue(), ^{ - handler.successBlock(request, (NSHTTPURLResponse*)response, responseObject); - }); - } - } - - } - } - [strongSelf safelyDecrementActiveTaskCount]; - [strongSelf safelyStartNextTaskIfNecessary]; - }); - }]; - - // 4) Store the response handler for use when the request completes - AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID - success:success - failure:failure]; - AFImageDownloaderMergedTask *mergedTask = [[AFImageDownloaderMergedTask alloc] - initWithURLIdentifier:URLIdentifier - identifier:mergedTaskIdentifier - task:createdTask]; - [mergedTask addResponseHandler:handler]; - self.mergedTasks[URLIdentifier] = mergedTask; - - // 5) Either start the request or enqueue it depending on the current active request count - if ([self isActiveRequestCountBelowMaximumLimit]) { - [self startMergedTask:mergedTask]; - } else { - [self enqueueMergedTask:mergedTask]; - } - - task = mergedTask.task; - }); - if (task) { - return [[AFImageDownloadReceipt alloc] initWithReceiptID:receiptID task:task]; - } else { - return nil; - } -} - -- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt { - dispatch_sync(self.synchronizationQueue, ^{ - NSString *URLIdentifier = imageDownloadReceipt.task.originalRequest.URL.absoluteString; - AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier]; - NSUInteger index = [mergedTask.responseHandlers indexOfObjectPassingTest:^BOOL(AFImageDownloaderResponseHandler * _Nonnull handler, __unused NSUInteger idx, __unused BOOL * _Nonnull stop) { - return handler.uuid == imageDownloadReceipt.receiptID; - }]; - - if (index != NSNotFound) { - AFImageDownloaderResponseHandler *handler = mergedTask.responseHandlers[index]; - [mergedTask removeResponseHandler:handler]; - NSString *failureReason = [NSString stringWithFormat:@"ImageDownloader cancelled URL request: %@",imageDownloadReceipt.task.originalRequest.URL.absoluteString]; - NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey:failureReason}; - NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; - if (handler.failureBlock) { - dispatch_async(dispatch_get_main_queue(), ^{ - handler.failureBlock(imageDownloadReceipt.task.originalRequest, nil, error); - }); - } - } - - if (mergedTask.responseHandlers.count == 0 && mergedTask.task.state == NSURLSessionTaskStateSuspended) { - [mergedTask.task cancel]; - [self removeMergedTaskWithURLIdentifier:URLIdentifier]; - } - }); -} - -- (AFImageDownloaderMergedTask*)safelyRemoveMergedTaskWithURLIdentifier:(NSString *)URLIdentifier { - __block AFImageDownloaderMergedTask *mergedTask = nil; - dispatch_sync(self.synchronizationQueue, ^{ - mergedTask = [self removeMergedTaskWithURLIdentifier:URLIdentifier]; - }); - return mergedTask; -} - -//This method should only be called from safely within the synchronizationQueue -- (AFImageDownloaderMergedTask *)removeMergedTaskWithURLIdentifier:(NSString *)URLIdentifier { - AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier]; - [self.mergedTasks removeObjectForKey:URLIdentifier]; - return mergedTask; -} - -- (void)safelyDecrementActiveTaskCount { - dispatch_sync(self.synchronizationQueue, ^{ - if (self.activeRequestCount > 0) { - self.activeRequestCount -= 1; - } - }); -} - -- (void)safelyStartNextTaskIfNecessary { - dispatch_sync(self.synchronizationQueue, ^{ - if ([self isActiveRequestCountBelowMaximumLimit]) { - while (self.queuedMergedTasks.count > 0) { - AFImageDownloaderMergedTask *mergedTask = [self dequeueMergedTask]; - if (mergedTask.task.state == NSURLSessionTaskStateSuspended) { - [self startMergedTask:mergedTask]; - break; - } - } - } - }); -} - -- (void)startMergedTask:(AFImageDownloaderMergedTask *)mergedTask { - [mergedTask.task resume]; - ++self.activeRequestCount; -} - -- (void)enqueueMergedTask:(AFImageDownloaderMergedTask *)mergedTask { - switch (self.downloadPrioritizaton) { - case AFImageDownloadPrioritizationFIFO: - [self.queuedMergedTasks addObject:mergedTask]; - break; - case AFImageDownloadPrioritizationLIFO: - [self.queuedMergedTasks insertObject:mergedTask atIndex:0]; - break; - } -} - -- (AFImageDownloaderMergedTask *)dequeueMergedTask { - AFImageDownloaderMergedTask *mergedTask = nil; - mergedTask = [self.queuedMergedTasks firstObject]; - [self.queuedMergedTasks removeObject:mergedTask]; - return mergedTask; -} - -- (BOOL)isActiveRequestCountBelowMaximumLimit { - return self.activeRequestCount < self.maximumActiveDownloads; -} - -@end - -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h deleted file mode 100644 index 3bcf289..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h +++ /dev/null @@ -1,103 +0,0 @@ -// AFNetworkActivityIndicatorManager.h -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#import - -#if TARGET_OS_IOS - -#import - -NS_ASSUME_NONNULL_BEGIN - -/** - `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a session task has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero. - - You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code: - - [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; - - By setting `enabled` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself. - - See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information: - http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44 - */ -NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.") -@interface AFNetworkActivityIndicatorManager : NSObject - -/** - A Boolean value indicating whether the manager is enabled. - - If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO. - */ -@property (nonatomic, assign, getter = isEnabled) BOOL enabled; - -/** - A Boolean value indicating whether the network activity indicator manager is currently active. -*/ -@property (readonly, nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; - -/** - A time interval indicating the minimum duration of networking activity that should occur before the activity indicator is displayed. The default value 1 second. If the network activity indicator should be displayed immediately when network activity occurs, this value should be set to 0 seconds. - - Apple's HIG describes the following: - - > Display the network activity indicator to provide feedback when your app accesses the network for more than a couple of seconds. If the operation finishes sooner than that, you don’t have to show the network activity indicator, because the indicator is likely to disappear before users notice its presence. - - */ -@property (nonatomic, assign) NSTimeInterval activationDelay; - -/** - A time interval indicating the duration of time of no networking activity required before the activity indicator is disabled. This allows for continuous display of the network activity indicator across multiple requests. The default value is 0.17 seconds. - */ - -@property (nonatomic, assign) NSTimeInterval completionDelay; - -/** - Returns the shared network activity indicator manager object for the system. - - @return The systemwide network activity indicator manager. - */ -+ (instancetype)sharedManager; - -/** - Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator. - */ -- (void)incrementActivityCount; - -/** - Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator. - */ -- (void)decrementActivityCount; - -/** - Set the a custom method to be executed when the network activity indicator manager should be hidden/shown. By default, this is null, and the UIApplication Network Activity Indicator will be managed automatically. If this block is set, it is the responsiblity of the caller to manager the network activity indicator going forward. - - @param block A block to be executed when the network activity indicator status changes. - */ -- (void)setNetworkingActivityActionWithBlock:(nullable void (^)(BOOL networkActivityIndicatorVisible))block; - -@end - -NS_ASSUME_NONNULL_END - -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m deleted file mode 100644 index e77508e..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m +++ /dev/null @@ -1,261 +0,0 @@ -// AFNetworkActivityIndicatorManager.m -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFNetworkActivityIndicatorManager.h" - -#if TARGET_OS_IOS -#import "AFURLSessionManager.h" - -typedef NS_ENUM(NSInteger, AFNetworkActivityManagerState) { - AFNetworkActivityManagerStateNotActive, - AFNetworkActivityManagerStateDelayingStart, - AFNetworkActivityManagerStateActive, - AFNetworkActivityManagerStateDelayingEnd -}; - -static NSTimeInterval const kDefaultAFNetworkActivityManagerActivationDelay = 1.0; -static NSTimeInterval const kDefaultAFNetworkActivityManagerCompletionDelay = 0.17; - -static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) { - if ([[notification object] respondsToSelector:@selector(originalRequest)]) { - return [(NSURLSessionTask *)[notification object] originalRequest]; - } else { - return nil; - } -} - -typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisible); - -@interface AFNetworkActivityIndicatorManager () -@property (readwrite, nonatomic, assign) NSInteger activityCount; -@property (readwrite, nonatomic, strong) NSTimer *activationDelayTimer; -@property (readwrite, nonatomic, strong) NSTimer *completionDelayTimer; -@property (readonly, nonatomic, getter = isNetworkActivityOccurring) BOOL networkActivityOccurring; -@property (nonatomic, copy) AFNetworkActivityActionBlock networkActivityActionBlock; -@property (nonatomic, assign) AFNetworkActivityManagerState currentState; -@property (nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; - -- (void)updateCurrentStateForNetworkActivityChange; -@end - -@implementation AFNetworkActivityIndicatorManager - -+ (instancetype)sharedManager { - static AFNetworkActivityIndicatorManager *_sharedManager = nil; - static dispatch_once_t oncePredicate; - dispatch_once(&oncePredicate, ^{ - _sharedManager = [[self alloc] init]; - }); - - return _sharedManager; -} - -- (instancetype)init { - self = [super init]; - if (!self) { - return nil; - } - self.currentState = AFNetworkActivityManagerStateNotActive; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil]; - self.activationDelay = kDefaultAFNetworkActivityManagerActivationDelay; - self.completionDelay = kDefaultAFNetworkActivityManagerCompletionDelay; - - return self; -} - -- (void)dealloc { - [[NSNotificationCenter defaultCenter] removeObserver:self]; - - [_activationDelayTimer invalidate]; - [_completionDelayTimer invalidate]; -} - -- (void)setEnabled:(BOOL)enabled { - _enabled = enabled; - if (enabled == NO) { - [self setCurrentState:AFNetworkActivityManagerStateNotActive]; - } -} - -- (void)setNetworkingActivityActionWithBlock:(void (^)(BOOL networkActivityIndicatorVisible))block { - self.networkActivityActionBlock = block; -} - -- (BOOL)isNetworkActivityOccurring { - @synchronized(self) { - return self.activityCount > 0; - } -} - -- (void)setNetworkActivityIndicatorVisible:(BOOL)networkActivityIndicatorVisible { - if (_networkActivityIndicatorVisible != networkActivityIndicatorVisible) { - [self willChangeValueForKey:@"networkActivityIndicatorVisible"]; - @synchronized(self) { - _networkActivityIndicatorVisible = networkActivityIndicatorVisible; - } - [self didChangeValueForKey:@"networkActivityIndicatorVisible"]; - if (self.networkActivityActionBlock) { - self.networkActivityActionBlock(networkActivityIndicatorVisible); - } else { - [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:networkActivityIndicatorVisible]; - } - } -} - -- (void)setActivityCount:(NSInteger)activityCount { - @synchronized(self) { - _activityCount = activityCount; - } - - dispatch_async(dispatch_get_main_queue(), ^{ - [self updateCurrentStateForNetworkActivityChange]; - }); -} - -- (void)incrementActivityCount { - [self willChangeValueForKey:@"activityCount"]; - @synchronized(self) { - _activityCount++; - } - [self didChangeValueForKey:@"activityCount"]; - - dispatch_async(dispatch_get_main_queue(), ^{ - [self updateCurrentStateForNetworkActivityChange]; - }); -} - -- (void)decrementActivityCount { - [self willChangeValueForKey:@"activityCount"]; - @synchronized(self) { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - _activityCount = MAX(_activityCount - 1, 0); -#pragma clang diagnostic pop - } - [self didChangeValueForKey:@"activityCount"]; - - dispatch_async(dispatch_get_main_queue(), ^{ - [self updateCurrentStateForNetworkActivityChange]; - }); -} - -- (void)networkRequestDidStart:(NSNotification *)notification { - if ([AFNetworkRequestFromNotification(notification) URL]) { - [self incrementActivityCount]; - } -} - -- (void)networkRequestDidFinish:(NSNotification *)notification { - if ([AFNetworkRequestFromNotification(notification) URL]) { - [self decrementActivityCount]; - } -} - -#pragma mark - Internal State Management -- (void)setCurrentState:(AFNetworkActivityManagerState)currentState { - @synchronized(self) { - if (_currentState != currentState) { - [self willChangeValueForKey:@"currentState"]; - _currentState = currentState; - switch (currentState) { - case AFNetworkActivityManagerStateNotActive: - [self cancelActivationDelayTimer]; - [self cancelCompletionDelayTimer]; - [self setNetworkActivityIndicatorVisible:NO]; - break; - case AFNetworkActivityManagerStateDelayingStart: - [self startActivationDelayTimer]; - break; - case AFNetworkActivityManagerStateActive: - [self cancelCompletionDelayTimer]; - [self setNetworkActivityIndicatorVisible:YES]; - break; - case AFNetworkActivityManagerStateDelayingEnd: - [self startCompletionDelayTimer]; - break; - } - } - [self didChangeValueForKey:@"currentState"]; - } -} - -- (void)updateCurrentStateForNetworkActivityChange { - if (self.enabled) { - switch (self.currentState) { - case AFNetworkActivityManagerStateNotActive: - if (self.isNetworkActivityOccurring) { - [self setCurrentState:AFNetworkActivityManagerStateDelayingStart]; - } - break; - case AFNetworkActivityManagerStateDelayingStart: - //No op. Let the delay timer finish out. - break; - case AFNetworkActivityManagerStateActive: - if (!self.isNetworkActivityOccurring) { - [self setCurrentState:AFNetworkActivityManagerStateDelayingEnd]; - } - break; - case AFNetworkActivityManagerStateDelayingEnd: - if (self.isNetworkActivityOccurring) { - [self setCurrentState:AFNetworkActivityManagerStateActive]; - } - break; - } - } -} - -- (void)startActivationDelayTimer { - self.activationDelayTimer = [NSTimer - timerWithTimeInterval:self.activationDelay target:self selector:@selector(activationDelayTimerFired) userInfo:nil repeats:NO]; - [[NSRunLoop mainRunLoop] addTimer:self.activationDelayTimer forMode:NSRunLoopCommonModes]; -} - -- (void)activationDelayTimerFired { - if (self.networkActivityOccurring) { - [self setCurrentState:AFNetworkActivityManagerStateActive]; - } else { - [self setCurrentState:AFNetworkActivityManagerStateNotActive]; - } -} - -- (void)startCompletionDelayTimer { - [self.completionDelayTimer invalidate]; - self.completionDelayTimer = [NSTimer timerWithTimeInterval:self.completionDelay target:self selector:@selector(completionDelayTimerFired) userInfo:nil repeats:NO]; - [[NSRunLoop mainRunLoop] addTimer:self.completionDelayTimer forMode:NSRunLoopCommonModes]; -} - -- (void)completionDelayTimerFired { - [self setCurrentState:AFNetworkActivityManagerStateNotActive]; -} - -- (void)cancelActivationDelayTimer { - [self.activationDelayTimer invalidate]; -} - -- (void)cancelCompletionDelayTimer { - [self.completionDelayTimer invalidate]; -} - -@end - -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h deleted file mode 100644 index d424c9b..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h +++ /dev/null @@ -1,48 +0,0 @@ -// UIActivityIndicatorView+AFNetworking.h -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#import - -#if TARGET_OS_IOS || TARGET_OS_TV - -#import - -/** - This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a session task. - */ -@interface UIActivityIndicatorView (AFNetworking) - -///---------------------------------- -/// @name Animating for Session Tasks -///---------------------------------- - -/** - Binds the animating state to the state of the specified task. - - @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. - */ -- (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task; - -@end - -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m deleted file mode 100644 index ed704ed..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m +++ /dev/null @@ -1,124 +0,0 @@ -// UIActivityIndicatorView+AFNetworking.m -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "UIActivityIndicatorView+AFNetworking.h" -#import - -#if TARGET_OS_IOS || TARGET_OS_TV - -#import "AFURLSessionManager.h" - -@interface AFActivityIndicatorViewNotificationObserver : NSObject -@property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView; -- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView; - -- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task; - -@end - -@implementation UIActivityIndicatorView (AFNetworking) - -- (AFActivityIndicatorViewNotificationObserver *)af_notificationObserver { - AFActivityIndicatorViewNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); - if (notificationObserver == nil) { - notificationObserver = [[AFActivityIndicatorViewNotificationObserver alloc] initWithActivityIndicatorView:self]; - objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - } - return notificationObserver; -} - -- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { - [[self af_notificationObserver] setAnimatingWithStateOfTask:task]; -} - -@end - -@implementation AFActivityIndicatorViewNotificationObserver - -- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView -{ - self = [super init]; - if (self) { - _activityIndicatorView = activityIndicatorView; - } - return self; -} - -- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - - [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; - [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; - [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; - - if (task) { - if (task.state != NSURLSessionTaskStateCompleted) { - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wreceiver-is-weak" -#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" - if (task.state == NSURLSessionTaskStateRunning) { - [self.activityIndicatorView startAnimating]; - } else { - [self.activityIndicatorView stopAnimating]; - } -#pragma clang diagnostic pop - - [notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task]; - [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task]; - [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidSuspendNotification object:task]; - } - } -} - -#pragma mark - - -- (void)af_startAnimating { - dispatch_async(dispatch_get_main_queue(), ^{ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wreceiver-is-weak" - [self.activityIndicatorView startAnimating]; -#pragma clang diagnostic pop - }); -} - -- (void)af_stopAnimating { - dispatch_async(dispatch_get_main_queue(), ^{ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wreceiver-is-weak" - [self.activityIndicatorView stopAnimating]; -#pragma clang diagnostic pop - }); -} - -#pragma mark - - -- (void)dealloc { - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - - [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; - [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; - [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; -} - -@end - -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h deleted file mode 100644 index d33e0d4..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h +++ /dev/null @@ -1,175 +0,0 @@ -// UIButton+AFNetworking.h -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#import - -#if TARGET_OS_IOS || TARGET_OS_TV - -#import - -NS_ASSUME_NONNULL_BEGIN - -@class AFImageDownloader; - -/** - This category adds methods to the UIKit framework's `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL. - - @warning Compound values for control `state` (such as `UIControlStateHighlighted | UIControlStateDisabled`) are unsupported. - */ -@interface UIButton (AFNetworking) - -///------------------------------------ -/// @name Accessing the Image Downloader -///------------------------------------ - -/** - Set the shared image downloader used to download images. - - @param imageDownloader The shared image downloader used to download images. -*/ -+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; - -/** - The shared image downloader used to download images. - */ -+ (AFImageDownloader *)sharedImageDownloader; - -///-------------------- -/// @name Setting Image -///-------------------- - -/** - Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. - - If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. - - @param state The control state. - @param url The URL used for the image request. - */ -- (void)setImageForState:(UIControlState)state - withURL:(NSURL *)url; - -/** - Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. - - If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. - - @param state The control state. - @param url The URL used for the image request. - @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. - */ -- (void)setImageForState:(UIControlState)state - withURL:(NSURL *)url - placeholderImage:(nullable UIImage *)placeholderImage; - -/** - Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. - - If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. - - If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setImage:forState:` is applied. - - @param state The control state. - @param urlRequest The URL request used for the image request. - @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. - @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. - @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. - */ -- (void)setImageForState:(UIControlState)state - withURLRequest:(NSURLRequest *)urlRequest - placeholderImage:(nullable UIImage *)placeholderImage - success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success - failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; - - -///------------------------------- -/// @name Setting Background Image -///------------------------------- - -/** - Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous background image request for the receiver will be cancelled. - - If the background image is cached locally, the background image is set immediately, otherwise the specified placeholder background image will be set immediately, and then the remote background image will be set once the request is finished. - - @param state The control state. - @param url The URL used for the background image request. - */ -- (void)setBackgroundImageForState:(UIControlState)state - withURL:(NSURL *)url; - -/** - Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. - - If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. - - @param state The control state. - @param url The URL used for the background image request. - @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. - */ -- (void)setBackgroundImageForState:(UIControlState)state - withURL:(NSURL *)url - placeholderImage:(nullable UIImage *)placeholderImage; - -/** - Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. - - If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. - - If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setBackgroundImage:forState:` is applied. - - @param state The control state. - @param urlRequest The URL request used for the image request. - @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. - @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. - @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. - */ -- (void)setBackgroundImageForState:(UIControlState)state - withURLRequest:(NSURLRequest *)urlRequest - placeholderImage:(nullable UIImage *)placeholderImage - success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success - failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; - - -///------------------------------ -/// @name Canceling Image Loading -///------------------------------ - -/** - Cancels any executing image task for the specified control state of the receiver, if one exists. - - @param state The control state. - */ -- (void)cancelImageDownloadTaskForState:(UIControlState)state; - -/** - Cancels any executing background image task for the specified control state of the receiver, if one exists. - - @param state The control state. - */ -- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state; - -@end - -NS_ASSUME_NONNULL_END - -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m deleted file mode 100644 index 5bc49dd..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m +++ /dev/null @@ -1,305 +0,0 @@ -// UIButton+AFNetworking.m -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "UIButton+AFNetworking.h" - -#import - -#if TARGET_OS_IOS || TARGET_OS_TV - -#import "UIImageView+AFNetworking.h" -#import "AFImageDownloader.h" - -@interface UIButton (_AFNetworking) -@end - -@implementation UIButton (_AFNetworking) - -#pragma mark - - -static char AFImageDownloadReceiptNormal; -static char AFImageDownloadReceiptHighlighted; -static char AFImageDownloadReceiptSelected; -static char AFImageDownloadReceiptDisabled; - -static const char * af_imageDownloadReceiptKeyForState(UIControlState state) { - switch (state) { - case UIControlStateHighlighted: - return &AFImageDownloadReceiptHighlighted; - case UIControlStateSelected: - return &AFImageDownloadReceiptSelected; - case UIControlStateDisabled: - return &AFImageDownloadReceiptDisabled; - case UIControlStateNormal: - default: - return &AFImageDownloadReceiptNormal; - } -} - -- (AFImageDownloadReceipt *)af_imageDownloadReceiptForState:(UIControlState)state { - return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_imageDownloadReceiptKeyForState(state)); -} - -- (void)af_setImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt - forState:(UIControlState)state -{ - objc_setAssociatedObject(self, af_imageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -#pragma mark - - -static char AFBackgroundImageDownloadReceiptNormal; -static char AFBackgroundImageDownloadReceiptHighlighted; -static char AFBackgroundImageDownloadReceiptSelected; -static char AFBackgroundImageDownloadReceiptDisabled; - -static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState state) { - switch (state) { - case UIControlStateHighlighted: - return &AFBackgroundImageDownloadReceiptHighlighted; - case UIControlStateSelected: - return &AFBackgroundImageDownloadReceiptSelected; - case UIControlStateDisabled: - return &AFBackgroundImageDownloadReceiptDisabled; - case UIControlStateNormal: - default: - return &AFBackgroundImageDownloadReceiptNormal; - } -} - -- (AFImageDownloadReceipt *)af_backgroundImageDownloadReceiptForState:(UIControlState)state { - return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state)); -} - -- (void)af_setBackgroundImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt - forState:(UIControlState)state -{ - objc_setAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -@end - -#pragma mark - - -@implementation UIButton (AFNetworking) - -+ (AFImageDownloader *)sharedImageDownloader { - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; -#pragma clang diagnostic pop -} - -+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { - objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -#pragma mark - - -- (void)setImageForState:(UIControlState)state - withURL:(NSURL *)url -{ - [self setImageForState:state withURL:url placeholderImage:nil]; -} - -- (void)setImageForState:(UIControlState)state - withURL:(NSURL *)url - placeholderImage:(UIImage *)placeholderImage -{ - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; - [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; - - [self setImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; -} - -- (void)setImageForState:(UIControlState)state - withURLRequest:(NSURLRequest *)urlRequest - placeholderImage:(nullable UIImage *)placeholderImage - success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success - failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure -{ - if ([self isActiveTaskURLEqualToURLRequest:urlRequest forState:state]) { - return; - } - - [self cancelImageDownloadTaskForState:state]; - - AFImageDownloader *downloader = [[self class] sharedImageDownloader]; - id imageCache = downloader.imageCache; - - //Use the image from the image cache if it exists - UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; - if (cachedImage) { - if (success) { - success(urlRequest, nil, cachedImage); - } else { - [self setImage:cachedImage forState:state]; - } - [self af_setImageDownloadReceipt:nil forState:state]; - } else { - if (placeholderImage) { - [self setImage:placeholderImage forState:state]; - } - - __weak __typeof(self)weakSelf = self; - NSUUID *downloadID = [NSUUID UUID]; - AFImageDownloadReceipt *receipt; - receipt = [downloader - downloadImageForURLRequest:urlRequest - withReceiptID:downloadID - success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { - if (success) { - success(request, response, responseObject); - } else if(responseObject) { - [strongSelf setImage:responseObject forState:state]; - } - [strongSelf af_setImageDownloadReceipt:nil forState:state]; - } - - } - failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { - if (failure) { - failure(request, response, error); - } - [strongSelf af_setImageDownloadReceipt:nil forState:state]; - } - }]; - - [self af_setImageDownloadReceipt:receipt forState:state]; - } -} - -#pragma mark - - -- (void)setBackgroundImageForState:(UIControlState)state - withURL:(NSURL *)url -{ - [self setBackgroundImageForState:state withURL:url placeholderImage:nil]; -} - -- (void)setBackgroundImageForState:(UIControlState)state - withURL:(NSURL *)url - placeholderImage:(nullable UIImage *)placeholderImage -{ - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; - [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; - - [self setBackgroundImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; -} - -- (void)setBackgroundImageForState:(UIControlState)state - withURLRequest:(NSURLRequest *)urlRequest - placeholderImage:(nullable UIImage *)placeholderImage - success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success - failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure -{ - if ([self isActiveBackgroundTaskURLEqualToURLRequest:urlRequest forState:state]) { - return; - } - - [self cancelBackgroundImageDownloadTaskForState:state]; - - AFImageDownloader *downloader = [[self class] sharedImageDownloader]; - id imageCache = downloader.imageCache; - - //Use the image from the image cache if it exists - UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; - if (cachedImage) { - if (success) { - success(urlRequest, nil, cachedImage); - } else { - [self setBackgroundImage:cachedImage forState:state]; - } - [self af_setBackgroundImageDownloadReceipt:nil forState:state]; - } else { - if (placeholderImage) { - [self setBackgroundImage:placeholderImage forState:state]; - } - - __weak __typeof(self)weakSelf = self; - NSUUID *downloadID = [NSUUID UUID]; - AFImageDownloadReceipt *receipt; - receipt = [downloader - downloadImageForURLRequest:urlRequest - withReceiptID:downloadID - success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { - if (success) { - success(request, response, responseObject); - } else if(responseObject) { - [strongSelf setBackgroundImage:responseObject forState:state]; - } - [strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state]; - } - - } - failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { - if (failure) { - failure(request, response, error); - } - [strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state]; - } - }]; - - [self af_setBackgroundImageDownloadReceipt:receipt forState:state]; - } -} - -#pragma mark - - -- (void)cancelImageDownloadTaskForState:(UIControlState)state { - AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state]; - if (receipt != nil) { - [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt]; - [self af_setImageDownloadReceipt:nil forState:state]; - } -} - -- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state { - AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state]; - if (receipt != nil) { - [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt]; - [self af_setBackgroundImageDownloadReceipt:nil forState:state]; - } -} - -- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state { - AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state]; - return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; -} - -- (BOOL)isActiveBackgroundTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state { - AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state]; - return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; -} - - -@end - -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h deleted file mode 100644 index 14744cd..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIImage+AFNetworking.h +++ /dev/null @@ -1,35 +0,0 @@ -// -// UIImage+AFNetworking.h -// -// -// Created by Paulo Ferreira on 08/07/15. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if TARGET_OS_IOS || TARGET_OS_TV - -#import - -@interface UIImage (AFNetworking) - -+ (UIImage*) safeImageWithData:(NSData*)data; - -@end - -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h deleted file mode 100644 index 8929252..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h +++ /dev/null @@ -1,109 +0,0 @@ -// UIImageView+AFNetworking.h -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#import - -#if TARGET_OS_IOS || TARGET_OS_TV - -#import - -NS_ASSUME_NONNULL_BEGIN - -@class AFImageDownloader; - -/** - This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL. - */ -@interface UIImageView (AFNetworking) - -///------------------------------------ -/// @name Accessing the Image Downloader -///------------------------------------ - -/** - Set the shared image downloader used to download images. - - @param imageDownloader The shared image downloader used to download images. - */ -+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; - -/** - The shared image downloader used to download images. - */ -+ (AFImageDownloader *)sharedImageDownloader; - -///-------------------- -/// @name Setting Image -///-------------------- - -/** - Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. - - If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. - - By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` - - @param url The URL used for the image request. - */ -- (void)setImageWithURL:(NSURL *)url; - -/** - Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. - - If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. - - By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` - - @param url The URL used for the image request. - @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. - */ -- (void)setImageWithURL:(NSURL *)url - placeholderImage:(nullable UIImage *)placeholderImage; - -/** - Asynchronously downloads an image from the specified URL request, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. - - If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. - - If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is applied. - - @param urlRequest The URL request used for the image request. - @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. - @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. - @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. - */ -- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest - placeholderImage:(nullable UIImage *)placeholderImage - success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success - failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; - -/** - Cancels any executing image operation for the receiver, if one exists. - */ -- (void)cancelImageDownloadTask; - -@end - -NS_ASSUME_NONNULL_END - -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m deleted file mode 100644 index 5934d68..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m +++ /dev/null @@ -1,161 +0,0 @@ -// UIImageView+AFNetworking.m -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "UIImageView+AFNetworking.h" - -#import - -#if TARGET_OS_IOS || TARGET_OS_TV - -#import "AFImageDownloader.h" - -@interface UIImageView (_AFNetworking) -@property (readwrite, nonatomic, strong, setter = af_setActiveImageDownloadReceipt:) AFImageDownloadReceipt *af_activeImageDownloadReceipt; -@end - -@implementation UIImageView (_AFNetworking) - -- (AFImageDownloadReceipt *)af_activeImageDownloadReceipt { - return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(af_activeImageDownloadReceipt)); -} - -- (void)af_setActiveImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt { - objc_setAssociatedObject(self, @selector(af_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -@end - -#pragma mark - - -@implementation UIImageView (AFNetworking) - -+ (AFImageDownloader *)sharedImageDownloader { - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; -#pragma clang diagnostic pop -} - -+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { - objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -#pragma mark - - -- (void)setImageWithURL:(NSURL *)url { - [self setImageWithURL:url placeholderImage:nil]; -} - -- (void)setImageWithURL:(NSURL *)url - placeholderImage:(UIImage *)placeholderImage -{ - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; - [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; - - [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; -} - -- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest - placeholderImage:(UIImage *)placeholderImage - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure -{ - - if ([urlRequest URL] == nil) { - [self cancelImageDownloadTask]; - self.image = placeholderImage; - return; - } - - if ([self isActiveTaskURLEqualToURLRequest:urlRequest]){ - return; - } - - [self cancelImageDownloadTask]; - - AFImageDownloader *downloader = [[self class] sharedImageDownloader]; - id imageCache = downloader.imageCache; - - //Use the image from the image cache if it exists - UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; - if (cachedImage) { - if (success) { - success(urlRequest, nil, cachedImage); - } else { - self.image = cachedImage; - } - [self clearActiveDownloadInformation]; - } else { - if (placeholderImage) { - self.image = placeholderImage; - } - - __weak __typeof(self)weakSelf = self; - NSUUID *downloadID = [NSUUID UUID]; - AFImageDownloadReceipt *receipt; - receipt = [downloader - downloadImageForURLRequest:urlRequest - withReceiptID:downloadID - success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { - if (success) { - success(request, response, responseObject); - } else if(responseObject) { - strongSelf.image = responseObject; - } - [strongSelf clearActiveDownloadInformation]; - } - - } - failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { - if (failure) { - failure(request, response, error); - } - [strongSelf clearActiveDownloadInformation]; - } - }]; - - self.af_activeImageDownloadReceipt = receipt; - } -} - -- (void)cancelImageDownloadTask { - if (self.af_activeImageDownloadReceipt != nil) { - [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt]; - [self clearActiveDownloadInformation]; - } -} - -- (void)clearActiveDownloadInformation { - self.af_activeImageDownloadReceipt = nil; -} - -- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest { - return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; -} - -@end - -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h deleted file mode 100644 index febacfc..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h +++ /dev/null @@ -1,42 +0,0 @@ -// UIKit+AFNetworking.h -// -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#if TARGET_OS_IOS || TARGET_OS_TV -#import - -#ifndef _UIKIT_AFNETWORKING_ - #define _UIKIT_AFNETWORKING_ - -#if TARGET_OS_IOS - #import "AFAutoPurgingImageCache.h" - #import "AFImageDownloader.h" - #import "AFNetworkActivityIndicatorManager.h" - #import "UIRefreshControl+AFNetworking.h" - #import "UIWebView+AFNetworking.h" -#endif - - #import "UIActivityIndicatorView+AFNetworking.h" - #import "UIButton+AFNetworking.h" - #import "UIImageView+AFNetworking.h" - #import "UIProgressView+AFNetworking.h" -#endif /* _UIKIT_AFNETWORKING_ */ -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h deleted file mode 100644 index 8ea0a73..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h +++ /dev/null @@ -1,64 +0,0 @@ -// UIProgressView+AFNetworking.h -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#import - -#if TARGET_OS_IOS || TARGET_OS_TV - -#import - -NS_ASSUME_NONNULL_BEGIN - - -/** - This category adds methods to the UIKit framework's `UIProgressView` class. The methods in this category provide support for binding the progress to the upload and download progress of a session task. - */ -@interface UIProgressView (AFNetworking) - -///------------------------------------ -/// @name Setting Session Task Progress -///------------------------------------ - -/** - Binds the progress to the upload progress of the specified session task. - - @param task The session task. - @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. - */ -- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task - animated:(BOOL)animated; - -/** - Binds the progress to the download progress of the specified session task. - - @param task The session task. - @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. - */ -- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task - animated:(BOOL)animated; - -@end - -NS_ASSUME_NONNULL_END - -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m deleted file mode 100644 index 058755e..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m +++ /dev/null @@ -1,118 +0,0 @@ -// UIProgressView+AFNetworking.m -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "UIProgressView+AFNetworking.h" - -#import - -#if TARGET_OS_IOS || TARGET_OS_TV - -#import "AFURLSessionManager.h" - -static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext; -static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext; - -#pragma mark - - -@implementation UIProgressView (AFNetworking) - -- (BOOL)af_uploadProgressAnimated { - return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_uploadProgressAnimated)) boolValue]; -} - -- (void)af_setUploadProgressAnimated:(BOOL)animated { - objc_setAssociatedObject(self, @selector(af_uploadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -- (BOOL)af_downloadProgressAnimated { - return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_downloadProgressAnimated)) boolValue]; -} - -- (void)af_setDownloadProgressAnimated:(BOOL)animated { - objc_setAssociatedObject(self, @selector(af_downloadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -#pragma mark - - -- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task - animated:(BOOL)animated -{ - [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; - [task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; - - [self af_setUploadProgressAnimated:animated]; -} - -- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task - animated:(BOOL)animated -{ - [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; - [task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; - - [self af_setDownloadProgressAnimated:animated]; -} - -#pragma mark - NSKeyValueObserving - -- (void)observeValueForKeyPath:(NSString *)keyPath - ofObject:(id)object - change:(__unused NSDictionary *)change - context:(void *)context -{ - if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) { - if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) { - if ([object countOfBytesExpectedToSend] > 0) { - dispatch_async(dispatch_get_main_queue(), ^{ - [self setProgress:[object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f) animated:self.af_uploadProgressAnimated]; - }); - } - } - - if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) { - if ([object countOfBytesExpectedToReceive] > 0) { - dispatch_async(dispatch_get_main_queue(), ^{ - [self setProgress:[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f) animated:self.af_downloadProgressAnimated]; - }); - } - } - - if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) { - if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) { - @try { - [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))]; - - if (context == AFTaskCountOfBytesSentContext) { - [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))]; - } - - if (context == AFTaskCountOfBytesReceivedContext) { - [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))]; - } - } - @catch (NSException * __unused exception) {} - } - } - } -} - -@end - -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h deleted file mode 100644 index 215eafc..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h +++ /dev/null @@ -1,53 +0,0 @@ -// UIRefreshControl+AFNetworking.m -// -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#import - -#if TARGET_OS_IOS - -#import - -NS_ASSUME_NONNULL_BEGIN - -/** - This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically beginning and ending refreshing depending on the loading state of a session task. - */ -@interface UIRefreshControl (AFNetworking) - -///----------------------------------- -/// @name Refreshing for Session Tasks -///----------------------------------- - -/** - Binds the refreshing state to the state of the specified task. - - @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. - */ -- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; - -@end - -NS_ASSUME_NONNULL_END - -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m deleted file mode 100644 index aba6d61..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m +++ /dev/null @@ -1,122 +0,0 @@ -// UIRefreshControl+AFNetworking.m -// -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "UIRefreshControl+AFNetworking.h" -#import - -#if TARGET_OS_IOS - -#import "AFURLSessionManager.h" - -@interface AFRefreshControlNotificationObserver : NSObject -@property (readonly, nonatomic, weak) UIRefreshControl *refreshControl; -- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl; - -- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; - -@end - -@implementation UIRefreshControl (AFNetworking) - -- (AFRefreshControlNotificationObserver *)af_notificationObserver { - AFRefreshControlNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); - if (notificationObserver == nil) { - notificationObserver = [[AFRefreshControlNotificationObserver alloc] initWithActivityRefreshControl:self]; - objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); - } - return notificationObserver; -} - -- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { - [[self af_notificationObserver] setRefreshingWithStateOfTask:task]; -} - -@end - -@implementation AFRefreshControlNotificationObserver - -- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl -{ - self = [super init]; - if (self) { - _refreshControl = refreshControl; - } - return self; -} - -- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - - [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; - [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; - [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; - - if (task) { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wreceiver-is-weak" -#pragma clang diagnostic ignored "-Warc-repeated-use-of-weak" - if (task.state == NSURLSessionTaskStateRunning) { - [self.refreshControl beginRefreshing]; - - [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task]; - [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task]; - [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task]; - } else { - [self.refreshControl endRefreshing]; - } -#pragma clang diagnostic pop - } -} - -#pragma mark - - -- (void)af_beginRefreshing { - dispatch_async(dispatch_get_main_queue(), ^{ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wreceiver-is-weak" - [self.refreshControl beginRefreshing]; -#pragma clang diagnostic pop - }); -} - -- (void)af_endRefreshing { - dispatch_async(dispatch_get_main_queue(), ^{ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wreceiver-is-weak" - [self.refreshControl endRefreshing]; -#pragma clang diagnostic pop - }); -} - -#pragma mark - - -- (void)dealloc { - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - - [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; - [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; - [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; -} - -@end - -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h deleted file mode 100644 index b9a56af..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.h +++ /dev/null @@ -1,80 +0,0 @@ -// UIWebView+AFNetworking.h -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#import - -#if TARGET_OS_IOS - -#import - -NS_ASSUME_NONNULL_BEGIN - -@class AFHTTPSessionManager; - -/** - This category adds methods to the UIKit framework's `UIWebView` class. The methods in this category provide increased control over the request cycle, including progress monitoring and success / failure handling. - - @discussion When using these category methods, make sure to assign `delegate` for the web view, which implements `–webView:shouldStartLoadWithRequest:navigationType:` appropriately. This allows for tapped links to be loaded through AFNetworking, and can ensure that `canGoBack` & `canGoForward` update their values correctly. - */ -@interface UIWebView (AFNetworking) - -/** - The session manager used to download all requests. - */ -@property (nonatomic, strong) AFHTTPSessionManager *sessionManager; - -/** - Asynchronously loads the specified request. - - @param request A URL request identifying the location of the content to load. This must not be `nil`. - @param progress A progress object monitoring the current download progress. - @param success A block object to be executed when the request finishes loading successfully. This block returns the HTML string to be loaded by the web view, and takes two arguments: the response, and the response string. - @param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred. - */ -- (void)loadRequest:(NSURLRequest *)request - progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress - success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success - failure:(nullable void (^)(NSError *error))failure; - -/** - Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding. - - @param request A URL request identifying the location of the content to load. This must not be `nil`. - @param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified. - @param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified. -@param progress A progress object monitoring the current download progress. - @param success A block object to be executed when the request finishes loading successfully. This block returns the data to be loaded by the web view and takes two arguments: the response, and the downloaded data. - @param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred. - */ -- (void)loadRequest:(NSURLRequest *)request - MIMEType:(nullable NSString *)MIMEType - textEncodingName:(nullable NSString *)textEncodingName - progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress - success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success - failure:(nullable void (^)(NSError *error))failure; - -@end - -NS_ASSUME_NONNULL_END - -#endif diff --git a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m b/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m deleted file mode 100644 index 751c499..0000000 --- a/Demo/StudyplusSDKDemo/AFNetworking/UIKit+AFNetworking/UIWebView+AFNetworking.m +++ /dev/null @@ -1,162 +0,0 @@ -// UIWebView+AFNetworking.m -// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "UIWebView+AFNetworking.h" - -#import - -#if TARGET_OS_IOS - -#import "AFHTTPSessionManager.h" -#import "AFURLResponseSerialization.h" -#import "AFURLRequestSerialization.h" - -@interface UIWebView (_AFNetworking) -@property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask; -@end - -@implementation UIWebView (_AFNetworking) - -- (NSURLSessionDataTask *)af_URLSessionTask { - return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask)); -} - -- (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask { - objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -@end - -#pragma mark - - -@implementation UIWebView (AFNetworking) - -- (AFHTTPSessionManager *)sessionManager { - static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - _af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; - _af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer]; - _af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer]; - }); - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager; -#pragma clang diagnostic pop -} - -- (void)setSessionManager:(AFHTTPSessionManager *)sessionManager { - objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -- (AFHTTPResponseSerializer *)responseSerializer { - static AFHTTPResponseSerializer *_af_defaultResponseSerializer = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer]; - }); - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer; -#pragma clang diagnostic pop -} - -- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { - objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -#pragma mark - - -- (void)loadRequest:(NSURLRequest *)request - progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress - success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success - failure:(void (^)(NSError *error))failure -{ - [self loadRequest:request MIMEType:nil textEncodingName:nil progress:progress success:^NSData *(NSHTTPURLResponse *response, NSData *data) { - NSStringEncoding stringEncoding = NSUTF8StringEncoding; - if (response.textEncodingName) { - CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName); - if (encoding != kCFStringEncodingInvalidId) { - stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); - } - } - - NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding]; - if (success) { - string = success(response, string); - } - - return [string dataUsingEncoding:stringEncoding]; - } failure:failure]; -} - -- (void)loadRequest:(NSURLRequest *)request - MIMEType:(NSString *)MIMEType - textEncodingName:(NSString *)textEncodingName - progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress - success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success - failure:(void (^)(NSError *error))failure -{ - NSParameterAssert(request); - - if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) { - [self.af_URLSessionTask cancel]; - } - self.af_URLSessionTask = nil; - - __weak __typeof(self)weakSelf = self; - NSURLSessionDataTask *dataTask; - dataTask = [self.sessionManager - GET:request.URL.absoluteString - parameters:nil - progress:nil - success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) { - __strong __typeof(weakSelf) strongSelf = weakSelf; - if (success) { - success((NSHTTPURLResponse *)task.response, responseObject); - } - [strongSelf loadData:responseObject MIMEType:MIMEType textEncodingName:textEncodingName baseURL:[task.currentRequest URL]]; - - if ([strongSelf.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { - [strongSelf.delegate webViewDidFinishLoad:strongSelf]; - } - } - failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) { - if (failure) { - failure(error); - } - }]; - self.af_URLSessionTask = dataTask; - if (progress != nil) { - *progress = [self.sessionManager downloadProgressForTask:dataTask]; - } - [self.af_URLSessionTask resume]; - - if ([self.delegate respondsToSelector:@selector(webViewDidStartLoad:)]) { - [self.delegate webViewDidStartLoad:self]; - } -} - -@end - -#endif \ No newline at end of file diff --git a/Demo/StudyplusSDKDemo/README.md b/Demo/StudyplusSDKDemo/README.md deleted file mode 100644 index 61ba9b2..0000000 --- a/Demo/StudyplusSDKDemo/README.md +++ /dev/null @@ -1,14 +0,0 @@ -StudyplusSDK Demo -======= - -### Using - - * [AFNetworking](https://github.com/AFNetworking/AFNetworking) - * [UICKeyChainStore](https://github.com/kishikawakatsumi/UICKeyChainStore) - -### Usage - -1. Run `pod try StudyplusSDK` or open this project -2. Overwrite Consumer Key and Secret in ViewController.m -3. Set custom URL Scheme -4. Run diff --git a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStopwatch.m b/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStopwatch.m deleted file mode 100644 index b5a6c34..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStopwatch.m +++ /dev/null @@ -1,88 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "SPLStopwatch.h" - -typedef NS_ENUM(NSInteger, SPLStopwatchState) { - SPLStopwatchStateStarted, - SPLStopwatchStateStopped -}; - -@interface SPLStopwatch() -@property (nonatomic, assign) NSUInteger elapsedSeconds; -@property (nonatomic, assign) NSUInteger startedTimestamp; -@property (nonatomic, assign) SPLStopwatchState state; -@end - -@implementation SPLStopwatch - --(instancetype)init -{ - if (self = [super init]) { - self.elapsedSeconds = 0; - self.startedTimestamp = 0; - self.state = SPLStopwatchStateStopped; - } - return self; -} - --(void)start -{ - if (self.state == SPLStopwatchStateStarted) { - return; - } - self.state = SPLStopwatchStateStarted; - - self.startedTimestamp = [[NSDate date] timeIntervalSince1970]; -} - --(void)pause -{ - if (self.state == SPLStopwatchStateStopped) { - return; - } - self.state = SPLStopwatchStateStopped; - - NSUInteger now = [[NSDate date] timeIntervalSince1970]; - self.elapsedSeconds += (now - self.startedTimestamp); -} - --(void)reset -{ - if (self.state == SPLStopwatchStateStarted) { - self.startedTimestamp = [[NSDate date] timeIntervalSince1970]; - } - self.elapsedSeconds = 0; -} - --(NSUInteger)elapsedSeconds -{ - if (self.state == SPLStopwatchStateStarted) { - NSUInteger now = [[NSDate date] timeIntervalSince1970]; - NSUInteger elapsedSeconds = _elapsedSeconds + (now - self.startedTimestamp); - return elapsedSeconds; - } else { - return _elapsedSeconds; - } -} - -@end diff --git a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplus.h b/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplus.h deleted file mode 100644 index c6777ac..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplus.h +++ /dev/null @@ -1,189 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "SPLStudyplusDelegate.h" -#import "SPLStudyplusRecord.h" -#import "SPLStudyplusRecordAmount.h" -#import "SPLStopwatch.h" - -NS_ASSUME_NONNULL_BEGIN - -/** - The class for using Studyplus.
- For example, you can authenticate in Studyplus account, de-authentication, and post study record. - - Studyplusの各機能を使うためのクラスです。
- Studyplusアカウントとの連携、連携解除、勉強記録の投稿ができます。 - */ -@interface SPLStudyplus : NSObject - -/** - The version of the StudyplusAPI. Default value is 1.
- StudyplusAPI のバージョンを指定します。デフォルトは 1 です。 - - https://external-api.studyplus.jp/v{apiVersion}/endpoint_name - */ -@property (nonatomic) NSInteger apiVersion; - -/** - Debug mode switch.
- When set to YES, then call back to the delegate without posting the actual processing.
- Default value is NO. - - StudyplusAPI のバージョンを指定します。
- debug=YESの場合、勉強記録の投稿時に実際の通信は行わずdelegateのコールバックメソッドを呼び出して処理を終了します。 - */ -@property (nonatomic) BOOL debug; - -/** - StudyplusAPI用のConsumer Keyです。
- Consumer Key for Studyplus API. - */ -@property (nonatomic, copy, readonly) NSString *consumerKey; - -/** - StudyplusAPI用のConsumer Secretです。
- Consumer Secret for Studyplus API. - */ -@property (nonatomic, copy, readonly) NSString *consumerSecret; - -/** - @see SPLStudyplusDelegate protocol - */ -@property (nonatomic, weak, nullable) id delegate; - -/** - When set to YES, if Studyplus is not installed, AppStore application starts when auth/login methods are called. Default value is YES.
- YESに設定すると、auth、loginメソッドを呼び出したとき、StudyplusアプリがインストールされていなければAppStoreを起動します。デフォルトは YES です。 - */ -@property (nonatomic) BOOL openAppStoreIfNotInstalled; - -/** - Username of Studyplus account. It is set when the auth or login is successful. Default value is nil.
- Studyplusアカウントのユーザ名です。login または authが成功したとき設定されます。設定されるまではnilです。 - */ -@property (nonatomic, copy, readonly, nullable) NSString *username; - -/** - Access token of Studyplus API. It is set when the auth or login is successful. Default value is nil.
- StudyplusAPIのアクセストークンです。login または authが成功したとき設定されます。設定されるまではnilです。 - */ -@property (nonatomic, copy, readonly, nullable) NSString *accessToken; - -/** - @see SPLStopwatch class - */ -@property (nonatomic, readonly, nullable) SPLStopwatch *stopwatch; - -/** - The convenience constructor of SPLStudyplus class. - - SPLStudyplusクラスのオブジェクトを生成して返します。 - - @param consumerKey Specify a Consumer Key for StudyplusAPI.
- StudyplusAPI用のコンシューマキーを指定してください。 - - @param consumerSecret Specify a Consumer Secret for StudyplusAPI.
- StudyplusAPI用のコンシューマシークレットを指定してください。 - - @return SPLStudyplus object.
- SPLStudyplusオブジェクト。 - */ -+ (instancetype)studyplusWithConsumerKey:(NSString*)consumerKey - andConsumerSecret:(NSString*)consumerSecret; - -/** - Opens the auth screen by invoking the Studyplus application. - - Studyplusアプリを起動して連携許可画面を開きます。 - - If Studyplus app is not installed and openAppStoreIfNotInstalled is YES, then open the Studyplus page in AppStore.
- If openAppStoreIfNotInstalled is NO, do nothing.
- After the process has returned from Studyplus application, delegate method will be called back. - - Studyplusアプリがインストールされていない場合、 openAppStoreIfNotInstalled がYESであれば、AppStoreを起動してStudyplusページを開きます。
- openAppStoreIfNotInstalled がNOであれば何もしません。
- Studyplusアプリから操作が戻ってきた後、delegateオブジェクトのコールバックメソッドを呼び出します。 - - @return It returns YES when you started Studyplus application. If Studyplus application is not installed, it returns NO.
- Studyplusアプリが起動した時点でYESを返します。Studyplusアプリがインストールされていない場合、NOを返します。 - */ -- (BOOL)auth; - -/** - Opens the login screen by invoking the Studyplus application. - - Studyplusアプリを起動してStudyplusログイン画面を開きます。 - - If Studyplus app is not installed and openAppStoreIfNotInstalled is YES, then open the Studyplus page in AppStore.
- If openAppStoreIfNotInstalled is NO, do nothing.
- After the process has returned from Studyplus application, delegate method will be called back. - - Studyplusアプリがインストールされていない場合、 openAppStoreIfNotInstalled がYESであれば、AppStoreを起動してStudyplusページを開きます。
- openAppStoreIfNotInstalled がNOであれば何もしません。
- Studyplusアプリから操作が戻ってきた後、delegateオブジェクトのコールバックメソッドを呼び出します。 - - @return It returns YES when you started Studyplus application. If Studyplus application is not installed, it returns NO.
- Studyplusアプリが起動した時点でYESを返します。Studyplusアプリがインストールされていない場合、NOを返します。 - */ -- (BOOL)login; - -/** - Posts new study record to Studyplus.
- Studyplusに勉強記録を新規投稿します。 - - @param studyRecord @see SPLStudyplusRecord - */ -- (void)postStudyRecord:(SPLStudyplusRecord*)studyRecord; - -/** - Cancels the cooperation with Studyplus application.
- Studyplusアプリとの連携を解除します。 - */ -- (void)logout; - -/** - Returns to whether or not it is in conjunction with Studyplus application.
- Studyplusアプリと連携されているか否かを返します。 - */ -- (BOOL)isConnected; - -/** - It is responsible for processing custom URL scheme when it came back from the authorization / login screen of Stuudyplus app.
- After handling openURL method in AppDelegate, pass the url parameter to this method.
- If the URL is passed by Studyplus application, calls the callback method of the delegate object. - - Studyplusアプリの認可・ログイン画面から戻ってきた時のカスタムURLスキーム処理を担当します。
- AppDelegateでopenURLをハンドリングしてから、このメソッドにurlを渡して委譲してください。
- Studyplusアプリ関連のURLであれば、delegateオブジェクトのコールバックメソッドを呼び出します。 - - @param url The parameter of AppDelegate#openURL method.
- AppDelegate#openURLメソッドで受け取ったurlパラメータをそのまま渡して下さい。 - - @return If the url is supported by StudyplusSDK, returns YES. The valid URL has a "studyplus-{consumerKey}://" scheme, and right pathComponents and host.
- 渡されたurlがStudyplusSDKで対応すべきURL(スキームが"studyplus-{consumerKey}"であり、host/pathComponentsが想定内であるもの)であればYES、それ以外はNOを返します。 - */ -- (BOOL)openURL:(NSURL*)url; - -NS_ASSUME_NONNULL_END - -@end diff --git a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplus.m b/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplus.m deleted file mode 100644 index 3492ca0..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplus.m +++ /dev/null @@ -1,244 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#import "SPLStudyplus.h" -#import "SPLStudyplusAPIRequest.h" -#import "SPLStudyplusLogger.h" -#import "SPLStudyplusError.h" -#import "UICKeyChainStore.h" - -static NSString * const UsernameStoreKey = @"username"; -static NSString * const AccessTokenStoreKey = @"accessToken"; -static NSString * const AppStoreURL = @"https://itunes.apple.com/jp/app/mian-qiangga-leshiku-xuku!/id505410049?mt=8"; - -@interface SPLStudyplus() -@property (nonatomic, copy, readwrite) NSString *consumerKey; -@property (nonatomic, copy, readwrite) NSString *consumerSecret; -@property (nonatomic, copy, readwrite) NSString *username; -@property (nonatomic, copy, readwrite) NSString *accessToken; -@property (nonatomic, readwrite) SPLStopwatch *stopwatch; -@end - -@implementation SPLStudyplus - -+ (instancetype)studyplusWithConsumerKey:(NSString*)consumerKey - andConsumerSecret:(NSString*)consumerSecret -{ - return [[SPLStudyplus alloc] __initWithConsumerKey:consumerKey - andConsumerSecret:consumerSecret]; -} - -- (instancetype)__initWithConsumerKey:(NSString*)consumerKey - andConsumerSecret:(NSString*)consumerSecret -{ - if (self = [super init]) { - self.consumerKey = consumerKey; - self.consumerSecret = consumerSecret; - self.username = nil; - self.accessToken = nil; - self.openAppStoreIfNotInstalled = YES; - self.apiVersion = 1; - self.debug = NO; - self.stopwatch = [SPLStopwatch new]; - } - - return self; -} - -- (NSString*)username -{ - return [[self keyChain] stringForKey:UsernameStoreKey]; -} - -- (NSString*)accessToken -{ - return [[self keyChain] stringForKey:AccessTokenStoreKey]; -} - -- (id)authWhenError:(NSError**)error -{ - return nil; -} - -- (BOOL)auth -{ - return [self openStudyplus:@"auth"]; -} - -- (BOOL)login -{ - return [self openStudyplus:@"login"]; -} - -- (void)logout -{ - UICKeyChainStore *keyChain = [self keyChain]; - [keyChain removeItemForKey:AccessTokenStoreKey]; - [keyChain removeItemForKey:UsernameStoreKey]; - [keyChain synchronize]; -} - -- (BOOL)isConnected -{ - return self.accessToken != nil; -} - -- (void)postStudyRecord:(SPLStudyplusRecord *)studyplusRecord -{ - if (self.debug) { - if ([self.delegate respondsToSelector:@selector(studyplusDidPostStudyRecord:)]) { - [self.delegate studyplusDidPostStudyRecord:self]; - } - return; - } - - if (![self isConnected]) { - if ([self.delegate respondsToSelector:@selector(studyplusDidFailToPostStudyRecord:withError:)]) { - [self.delegate studyplusDidFailToPostStudyRecord:self withError:[SPLStudyplusError errorFromStudyplusErrorCode:SPLErrorCodeNotConnected]]; - } - - return; - } - - SPLStudyplusAPIRequest *request = [SPLStudyplusAPIRequest - newRequestWithAccessToken:self.accessToken - options:@{ - @"version": [NSNumber numberWithInteger:self.apiVersion], - }]; - - __block id __delegate = self.delegate; - - [request postRequestWithPath:@"study_records" - requestParameter:[studyplusRecord toRequestParam] - completed:^(NSDictionary *responseParameter) { - if ([__delegate respondsToSelector:@selector(studyplusDidPostStudyRecord:)]) { - [__delegate studyplusDidPostStudyRecord:self]; - } - } failed:^(NSError *error) { - if ([__delegate respondsToSelector:@selector(studyplusDidFailToPostStudyRecord:withError:)]) { - [__delegate studyplusDidFailToPostStudyRecord:self withError:error]; - } - }]; -} - -- (BOOL)openURL:(NSURL*)url -{ - if (![self isAcceptableURL:url]) { - return NO; - } - - if ([url.pathComponents[1] isEqualToString:@"success"]) { - NSString *accessToken = [url.pathComponents[2] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; - NSString *username = [url.pathComponents[3] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; - [self saveAccessToken:accessToken andUsername:username]; - [self.delegate studyplusDidConnect:self]; - } else if ([url.pathComponents[1] isEqualToString:@"fail"]) { - NSInteger studyplusErrorCode = [url.pathComponents[2] integerValue]; - [self.delegate studyplusDidFailToConnect:self - withError:[SPLStudyplusError - errorFromStudyplusErrorCode:studyplusErrorCode]]; - } else if ([url.pathComponents[1] isEqualToString:@"cancel"]) { - if ([self.delegate respondsToSelector:@selector(studyplusDidCancel:)]) { - [self.delegate studyplusDidCancel:self]; - } - } else { - StudyplusSDKLog(@"Unknown format : %@", [url absoluteString]); - return NO; - } - - return YES; -} - -#pragma mark - privates - -- (id)init -{ - @throw [NSException exceptionWithName:NSInternalInconsistencyException - reason:@"-init method is not available." - userInfo:nil]; - return nil; -} - -- (void)saveAccessToken:(NSString*)accessToken andUsername:(NSString*)username -{ - UICKeyChainStore *keyChain = [self keyChain]; - [keyChain setString:accessToken forKey:AccessTokenStoreKey]; - [keyChain setString:username forKey:UsernameStoreKey]; - [keyChain synchronize]; -} - -- (NSString*)urlScheme -{ - return [NSString stringWithFormat:@"studyplus-%@", self.consumerKey]; -} - -- (BOOL)openStudyplus:(NSString*)command -{ - NSString *urlString = [NSString stringWithFormat: - @"studyplus://external_app/%@/%@/%@", - command, - self.consumerKey, - self.consumerSecret - ]; - NSURL *url = [NSURL URLWithString:urlString]; - - BOOL isStudyplusOpened = [UIApplication.sharedApplication openURL:url]; - if (isStudyplusOpened) { - return YES; - } - - // Studyplus app is not installed. - - if (self.openAppStoreIfNotInstalled) { - NSURL *url = [NSURL URLWithString:AppStoreURL]; - [[UIApplication sharedApplication] openURL:url]; - } - - return NO; -} - -- (UICKeyChainStore*)keyChain -{ - NSString *keyChainServiceName = [NSString stringWithFormat:@"Studyplus_iOS_SDK_%@", self.consumerKey]; - return [UICKeyChainStore keyChainStoreWithService:keyChainServiceName]; -} - -- (BOOL)isAcceptableURL:(NSURL*)url -{ - if (![url.scheme isEqualToString:[self urlScheme]] - || !url.host - || !url.pathComponents) { - return NO; - } - - BOOL isAuthResult = [url.host isEqualToString:@"auth-result"]; - BOOL isLoginResult = [url.host isEqualToString:@"login-result"]; - if (!isAuthResult && !isLoginResult) { - return NO; - } - - return YES; -} - -@end diff --git a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusAPIRequest.m b/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusAPIRequest.m deleted file mode 100644 index 90ec71d..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusAPIRequest.m +++ /dev/null @@ -1,122 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFNetworking.h" -#import "SPLStudyplusAPIRequest.h" -#import "SPLStudyplusLogger.h" -#import "SPLStudyplusError.h" - -@interface SPLStudyplusAPIRequest() -@property (nonatomic, readonly) NSString *accessToken; -@property (nonatomic, readonly) NSInteger apiVersion; -@end - -static NSString * const ApiBaseURL = @"https://external-api.studyplus.jp/"; -static NSInteger const ApiDefaultVersion = 1; - -@implementation SPLStudyplusAPIRequest - -- (instancetype)init -{ - if (self = [super init]) { - _accessToken = nil; - } - return self; -} - -+ (instancetype)newRequestWithAccessToken:(NSString*)accessToken - options:(NSDictionary*)options -{ - return [[SPLStudyplusAPIRequest alloc] initWithAccessToken:accessToken - options:options]; -} - -- (instancetype)initWithAccessToken:(NSString*)accessToken - options:(NSDictionary*)options -{ - if (self = [super init]) { - _accessToken = accessToken; - _apiVersion = options[@"version"] ? [options[@"version"] integerValue] : ApiDefaultVersion; - } - return self; -} - -- (void)postRequestWithPath:(NSString *)path - requestParameter:(NSDictionary *)requestParameter - completed:(void(^)(NSDictionary *response))completed - failed:(void(^)(NSError *error))failed -{ - [self sendRequestWithPath:path - requestParams:requestParameter - completed:completed - failed:^(NSInteger httpStatusCode, NSError *error) { - if (error) { - failed(error); - } else { - failed([SPLStudyplusError errorFromStudyRecordPostStatusCode:httpStatusCode]); - } - }]; -} - -- (void)sendRequestWithPath:(NSString*)path - requestParams:(NSDictionary *)requestParams - completed:(void(^)(NSDictionary *response))completed - failed:(void(^)(NSInteger httpStatusCode, NSError *error))failed -{ - AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer]; - AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer]; - [requestSerializer setValue:[NSString stringWithFormat:@"OAuth %@", self.accessToken] - forHTTPHeaderField:@"HTTP_AUTHORIZATION"]; - - AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; - manager.requestSerializer = requestSerializer; - manager.responseSerializer = responseSerializer; - - [manager POST:[self buildUrlFromPath:path] parameters:requestParams progress:^(NSProgress * _Nonnull uploadProgress) { - } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { - NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject - options:NSJSONReadingAllowFragments - error:nil]; - StudyplusSDKLog(@"response: %@", response); - completed(response); - } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { - StudyplusSDKLog(@"Error: %@", error); - NSHTTPURLResponse *res = (NSHTTPURLResponse *)task.response; - failed(res.statusCode, error); - }]; -} - -- (NSString *)apiBaseURL -{ -#ifdef STUDYPLUS_API_URL - return STUDYPLUS_API_URL; -#else - return ApiBaseURL; -#endif -} - -- (NSString *)buildUrlFromPath:(NSString *)path -{ - return [NSString stringWithFormat:@"%@v%ld/%@", [self apiBaseURL], (long)self.apiVersion, path]; -} - -@end diff --git a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusDelegate.h b/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusDelegate.h deleted file mode 100644 index 1345488..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusDelegate.h +++ /dev/null @@ -1,85 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -@class SPLStudyplus; - -/** - The delegate to receive callbacks from SPLStudyplus. - - SPLStudyplusオブジェクトに対する各種操作後のコールバックを受けるdelegateです。 - */ -@protocol SPLStudyplusDelegate - -/** - Will be called after the SPLStudyplus#login or SPLStudyplus#auth was successful.
- SPLStudyplus#auth または SPLStudyplus#login が成功した後に呼ばれます。 - - @param studyplus SPLStudyplus object.
- SPLStudyplusオブジェクトです。 - */ -- (void)studyplusDidConnect:(SPLStudyplus*)studyplus; - -/** - Will be called after the SPLStudyplus#login or SPLStudyplus#auth was failure.
- SPLStudyplus#auth または SPLStudyplus#login が失敗した後に呼ばれます。 - - @param studyplus Studyplus object.
- Studyplusオブジェクトです。 - @param error Error object including failure reason.
- 失敗の理由を持つエラーオブジェクトです。 - @see StudyplusNSError.h - */ -- (void)studyplusDidFailToConnect:(SPLStudyplus*)studyplus withError:(NSError*)error; - -@optional - -/** - Will be called after the SPLStudyplus#login or SPLStudyplus#auth was cancelled.
- SPLStudyplus#auth または SPLStudyplus#login がキャンセルされた後に呼ばれます。 - - @param studyplus SPLStudyplus object.
- SPLStudyplusオブジェクトです。 - */ -- (void)studyplusDidCancel:(SPLStudyplus*)studyplus; - -/** - Will be called after the SPLStudyplus#postStudyRecord was successful.
- SPLStudyplus#postStudyRecord: が成功した後に呼ばれます。 - - @param studyplus SPLStudyplus object.
- SPLStudyplusオブジェクトです。 - */ -- (void)studyplusDidPostStudyRecord:(SPLStudyplus*)studyplus; - -/** - Will be called after the SPLStudyplus#postStudyRecord was failure. If this method is called, study record was not posted.
- SPLStudyplus#postStudyRecord: が失敗した後に呼ばれます。このメソッドが呼ばれた場合、勉強ログは投稿されていません。 - - @param error Error object including failure reason.
- 失敗の理由を持つエラーオブジェクトです。 - @see SPLStudyplusError - */ -- (void)studyplusDidFailToPostStudyRecord:(SPLStudyplus*)studyplus withError:(NSError*)error; - -@end diff --git a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusError.h b/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusError.h deleted file mode 100644 index 2d3ee6d..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusError.h +++ /dev/null @@ -1,43 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -typedef NS_ENUM(NSInteger, SPLErrorCode) { - SPLErrorCodeGetAppDescription = 1000, - SPLErrorCodeAuthFailed = 2000, - SPLErrorCodeLoginFailed = 3000, - SPLErrorCodeStudyplusInMaintenance = 4000, - SPLErrorCodeInvalidStudyplusSession = 5000, - SPLErrorCodeNetworkUnavailable = 6000, - SPLErrorCodeServerError = 7000, - SPLErrorCodePostRecordFailed = 8000, - SPLErrorCodeNotConnected = 9000, - SPLErrorCodeUnknown = 90000 -}; - -@interface SPLStudyplusError : NSObject - -+ (NSError*)errorFromStudyplusErrorCode:(SPLErrorCode)studyplusErrorCode; -+ (NSError*)errorFromStudyRecordPostStatusCode:(NSInteger)httpStatusCode; - -@end diff --git a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusError.m b/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusError.m deleted file mode 100644 index df0b017..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusError.m +++ /dev/null @@ -1,139 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "SPLStudyplusError.h" -#import "SPLStudyplusLogger.h" - -static NSString* const ErrorDomain = @"jp.studyplus.sdk"; - -@implementation SPLStudyplusError - -+ (NSError*)errorFromStudyplusErrorCode:(SPLErrorCode)studyplusErrorCode -{ - NSError *error; - switch (studyplusErrorCode) { - case SPLErrorCodeGetAppDescription: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Failed to get information about application. (400 bad request)"]; - break; - - case SPLErrorCodeAuthFailed: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Failed to authorize Studyplus user. (400 bad request)"]; - break; - - case SPLErrorCodeLoginFailed: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Failed to login to Studyplus. (400 bad request)"]; - break; - - case SPLErrorCodeStudyplusInMaintenance: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Maybe Studyplus is in temporary maintenance."]; - break; - - case SPLErrorCodeInvalidStudyplusSession: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Studyplus session is invalid."]; - break; - - case SPLErrorCodeNetworkUnavailable: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Network is not available."]; - break; - - case SPLErrorCodeServerError: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Some error(s) occurred in Studyplus server."]; - break; - - case SPLErrorCodePostRecordFailed: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Failed to post study record. (400 bad request)"]; - break; - - case SPLErrorCodeNotConnected: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Not Connected"]; - break; - - case SPLErrorCodeUnknown: - error = [SPLStudyplusError errorWithCode:SPLErrorCodeUnknown - localizedDescription:@"Unknown Error."]; - break; - default: - StudyplusSDKLog(@"Unexpected Studyplus status:[%ld]", (long)studyplusErrorCode); - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:[NSString - stringWithFormat:@"Unexpected Error(errorCode:[%ld]).", - (long)studyplusErrorCode]]; - break; - } - return error; -} - -+ (NSError*)errorFromStudyRecordPostStatusCode:(NSInteger)httpStatusCode -{ - if (httpStatusCode < 400 || 599 < httpStatusCode) { - // no error - return nil; - } - - NSError *error; - switch (httpStatusCode) { - case 400: - error = [SPLStudyplusError - errorFromStudyplusErrorCode:SPLErrorCodePostRecordFailed]; - break; - - case 401: - error = [SPLStudyplusError - errorFromStudyplusErrorCode:SPLErrorCodeInvalidStudyplusSession]; - break; - - case 500: - error = [SPLStudyplusError - errorFromStudyplusErrorCode:SPLErrorCodeServerError]; - - break; - case 503: - error = [SPLStudyplusError - errorFromStudyplusErrorCode:SPLErrorCodeStudyplusInMaintenance]; - break; - - default: - StudyplusSDKLog(@"Unexpected http status:[%ld]", (long)httpStatusCode); - error = [SPLStudyplusError - errorFromStudyplusErrorCode:SPLErrorCodeUnknown]; - break; - } - return error; -} - -+ (NSError*)errorWithCode:(SPLErrorCode)errorCode localizedDescription:(NSString*)localizedDescription -{ - return [NSError errorWithDomain:ErrorDomain - code:errorCode - userInfo:@{NSLocalizedDescriptionKey:localizedDescription}]; -} - -@end diff --git a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusRecord.h b/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusRecord.h deleted file mode 100644 index bfdcb21..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusRecord.h +++ /dev/null @@ -1,101 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -NS_ASSUME_NONNULL_BEGIN - -@class SPLStudyplusRecordAmount; - -/** - Study record object to post to Studyplus.
- Studyplusに投稿する一件の勉強記録を表現するクラスです。 - */ -@interface SPLStudyplusRecord : NSObject - -/** - The seconds of the learning.
- 勉強した時間(秒数)です。 - */ -@property (nonatomic, readonly) NSTimeInterval duration; - -/** - The date and time of learning.
- 勉強した日時です。 - */ -@property (nonatomic, readonly) NSDate *recordedAt; - -/** - The amount of learning.
- 勉強した量です。 - - @see StudyplusRecordAmount - */ -@property (nonatomic, readonly) SPLStudyplusRecordAmount *recordAmount; - -/** - The comment of learning.
- 勉強に関するコメントです。 - */ -@property (nonatomic, readonly, nullable) NSString *comment; - -/** - Creates and returns StudyplusRecord object that has number of seconds, no amount, and empty comment.
- 学習時間のみを指定した勉強記録オブジェクトを作成し、返します。学習量とコメントは無しです。 - - @param duration Specify the seconds of the learning.
- 勉強した時間(秒数)を指定してください。 - - @result StudyplusRecord object. - */ -+ (instancetype)recordWithDuration:(NSTimeInterval)duration; - -/** - Creates and returns StudyplusRecord object that has number of seconds and other attributes. - 学習時間とその他のオプション属性を指定した勉強記録オブジェクトを作成し、返します。 - - @param duration Specify the seconds of the learning.
- 勉強した時間(秒数)を指定してください。 - - @param options Dictionary with amount:StudyplusRecordAmount, comment:NSString, recordedAt:NSDate.
- // example.
- @{
- // @see StudyplusRecordAmount
- @"amount": [StudyplusRecordAmount amountAsRangeWithFrom:10 to:33],
- // Time the learning is ended. 学習を終えた日時。
- @"recordedAt": [NSDate date],
- // Studyplus timeline comment. Studyplusのタイムライン上で表示されるコメント。
- @"comment": @"アプリ◯◯で勉強しました!",
- }
- - @result StudyplusRecord object. - */ -+ (instancetype)recordWithDuration:(NSTimeInterval)duration options:(NSDictionary* _Nullable)options; - -/** - @result Returns the parameters of the study record for posting API - */ -- (NSDictionary*)toRequestParam; - -NS_ASSUME_NONNULL_END - -@end diff --git a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusRecord.m b/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusRecord.m deleted file mode 100644 index 9de2924..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusRecord.m +++ /dev/null @@ -1,104 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "SPLStudyplusRecord.h" -#import "SPLStudyplusRecordAmount.h" - -@interface NSDate(Formattable) -- (NSString*)toString:(NSString*)format; -@end - -@interface NSDictionary(GetOrElse) -- (id)getKey:(NSString*)key orElse:(id)elseValue; -@end - -@implementation SPLStudyplusRecord - -+ (instancetype)recordWithDuration:(NSTimeInterval)duration -{ - return [self recordWithDuration:duration options:@{}]; -} - -+ (instancetype)recordWithDuration:(NSTimeInterval)duration options:(NSDictionary*)options -{ - return [[[self class] alloc] initWithDuration:duration options:options]; -} - -- (id)getKey:(NSString *)key from:(NSDictionary *)dict orElse:(id)elseValue -{ - id value = dict[key]; - if (value == [NSNull null] || value == nil) { - value = elseValue; - } - return value; -} - -- (id)initWithDuration:(NSTimeInterval)duration options:(NSDictionary*)options -{ - if (self = [super init]) { - _duration = duration; - _recordAmount = [options getKey:@"amount" orElse:[SPLStudyplusRecordAmount amountAsNone]]; - _recordedAt = [options getKey:@"recordedAt" orElse:[NSDate date]]; - _comment = [options getKey:@"comment" orElse:nil]; - } - return self; -} - -- (NSDictionary*)toRequestParam -{ - NSMutableDictionary *param = [NSMutableDictionary new]; - param[@"duration"] = [NSNumber numberWithDouble:self.duration]; - param[@"recorded_at"] = [self.recordedAt toString:@"yyyy-MM-dd HH:mm:ss"]; - if (self.comment != nil) { - param[@"comment"] = self.comment; - } - for (NSString *key in self.recordAmount.toRequestParameter) { - param[key] = self.recordAmount.toRequestParameter[key]; - } - return (NSDictionary*)param; -} - -@end - -@implementation NSDate(Formattable) -- (NSString*)toString:(NSString*)format -{ - NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; - [formatter setLocale:[NSLocale systemLocale]]; - [formatter setTimeZone:[NSTimeZone systemTimeZone]]; - [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; - [formatter setDateFormat:format]; - [formatter setCalendar:[[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]]; - return [formatter stringFromDate:self]; -} -@end - -@implementation NSDictionary(GetOrElse) -- (id)getKey:(NSString *)key orElse:(id)elseValue -{ - id value = self[key]; - if (value == [NSNull null] || value == nil) { - value = elseValue; - } - return value; -} -@end \ No newline at end of file diff --git a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusRecordAmount.h b/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusRecordAmount.h deleted file mode 100644 index 196a944..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusRecordAmount.h +++ /dev/null @@ -1,66 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -NS_ASSUME_NONNULL_BEGIN - -/** - The class that represents the amount of learning.
- 学習量を表すクラスです。 - */ -@interface SPLStudyplusRecordAmount : NSObject - -/** - Creates and returns the Amount object with only the total amount of learning.
- 合計の学習量のみを持つAmountオブジェクトを生成して返します。 - - @param amount 学習量。 - @result SPLStudyplusRecordAmount* 生成したAmountオブジェクトです。 - */ -+ (instancetype)amount:(NSUInteger)amount; - -/** - Creates and returns the Amount object with a range of learning amount.
- 学習量を範囲で持つAmountオブジェクトを生成して返します。 - - @param from 学習量の起点。 - @param to 学習量の終点。 - @result SPLStudyplusRecordAmount* 生成したAmountオブジェクトです。 - */ -+ (instancetype)amountAsRangeWithFrom:(NSUInteger)from to:(NSUInteger)to; - -/** - Creates and returns the Amount object that has no learning amount.
- 学習量を持たないAmountオブジェクトを生成して返します。 - @result SPLStudyplusRecordAmount* 生成したAmountオブジェクトです。 - */ -+ (instancetype)amountAsNone; - -/** - @result Returns the parameters of the study record for posting API - */ -- (NSDictionary*)toRequestParameter; - -NS_ASSUME_NONNULL_END - -@end diff --git a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusRecordAmount.m b/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusRecordAmount.m deleted file mode 100644 index 207b05a..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusRecordAmount.m +++ /dev/null @@ -1,80 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "SPLStudyplusRecordAmount.h" - -@interface SPLStudyplusRecordAmount() -@property (nonatomic, readonly) NSDictionary *requestParameter; -@end - -@implementation SPLStudyplusRecordAmount - -+ (instancetype)amount:(NSUInteger)amount -{ - return [[[self class] alloc] initAsAmount:amount]; -} - -- (instancetype)initAsAmount:(NSUInteger)amount -{ - if (self = [super init]) { - _requestParameter = @{ - @"amount": [NSNumber numberWithUnsignedInteger:amount], - }; - } - return self; -} - -+ (instancetype)amountAsRangeWithFrom:(NSUInteger)from to:(NSUInteger)to -{ - return [[[self class] alloc] initAsRangeWithFrom:from to:to]; -} - -- (instancetype)initAsRangeWithFrom:(NSUInteger)from to:(NSUInteger)to -{ - if (self = [super init]) { - _requestParameter = @{ - @"start_position": [NSNumber numberWithUnsignedInteger:from], - @"end_position": [NSNumber numberWithUnsignedInteger:to], - }; - } - return self; -} - -+ (instancetype)amountAsNone -{ - return [[[self class] alloc] initAsNone]; -} - -- (instancetype)initAsNone -{ - if (self = [super init]) { - _requestParameter = @{}; - } - return self; -} - -- (NSDictionary*)toRequestParameter -{ - return _requestParameter; -} - -@end diff --git a/Demo/StudyplusSDKDemo/StudyplusSDKDemo.xcodeproj/project.pbxproj b/Demo/StudyplusSDKDemo/StudyplusSDKDemo.xcodeproj/project.pbxproj deleted file mode 100644 index 74c6e43..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDKDemo.xcodeproj/project.pbxproj +++ /dev/null @@ -1,702 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 4302C74818B49B5B005A8390 /* SPLStopwatch.m in Sources */ = {isa = PBXBuildFile; fileRef = 4302C73A18B49B5B005A8390 /* SPLStopwatch.m */; }; - 4302C74918B49B5B005A8390 /* SPLStudyplus.m in Sources */ = {isa = PBXBuildFile; fileRef = 4302C73C18B49B5B005A8390 /* SPLStudyplus.m */; }; - 4302C74A18B49B5B005A8390 /* SPLStudyplusAPIRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 4302C73E18B49B5B005A8390 /* SPLStudyplusAPIRequest.m */; }; - 4302C74B18B49B5B005A8390 /* SPLStudyplusError.m in Sources */ = {isa = PBXBuildFile; fileRef = 4302C74118B49B5B005A8390 /* SPLStudyplusError.m */; }; - 4302C74C18B49B5B005A8390 /* SPLStudyplusRecord.m in Sources */ = {isa = PBXBuildFile; fileRef = 4302C74418B49B5B005A8390 /* SPLStudyplusRecord.m */; }; - 4302C74D18B49B5B005A8390 /* SPLStudyplusRecordAmount.m in Sources */ = {isa = PBXBuildFile; fileRef = 4302C74618B49B5B005A8390 /* SPLStudyplusRecordAmount.m */; }; - 4388599E18B1E90A0063BBC8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4388599D18B1E90A0063BBC8 /* Foundation.framework */; }; - 438859A018B1E90A0063BBC8 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4388599F18B1E90A0063BBC8 /* CoreGraphics.framework */; }; - 438859A218B1E90A0063BBC8 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 438859A118B1E90A0063BBC8 /* UIKit.framework */; }; - 438859A818B1E90A0063BBC8 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 438859A618B1E90A0063BBC8 /* InfoPlist.strings */; }; - 438859AA18B1E90A0063BBC8 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 438859A918B1E90A0063BBC8 /* main.m */; }; - 438859AE18B1E90A0063BBC8 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 438859AD18B1E90A0063BBC8 /* AppDelegate.m */; }; - 438859B118B1E90A0063BBC8 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 438859AF18B1E90A0063BBC8 /* Main.storyboard */; }; - 438859B418B1E90A0063BBC8 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 438859B318B1E90A0063BBC8 /* ViewController.m */; }; - 438859B618B1E90A0063BBC8 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 438859B518B1E90A0063BBC8 /* Images.xcassets */; }; - 438859BD18B1E90A0063BBC8 /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 438859BC18B1E90A0063BBC8 /* XCTest.framework */; }; - 438859BE18B1E90A0063BBC8 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4388599D18B1E90A0063BBC8 /* Foundation.framework */; }; - 438859BF18B1E90A0063BBC8 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 438859A118B1E90A0063BBC8 /* UIKit.framework */; }; - 438859C718B1E90A0063BBC8 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 438859C518B1E90A0063BBC8 /* InfoPlist.strings */; }; - 438859C918B1E90A0063BBC8 /* StudyplusSDKDemoTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 438859C818B1E90A0063BBC8 /* StudyplusSDKDemoTests.m */; }; - 438859E618B1EA8D0063BBC8 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 438859E518B1EA8D0063BBC8 /* Security.framework */; }; - 438859E818B1EA930063BBC8 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 438859E718B1EA930063BBC8 /* SystemConfiguration.framework */; }; - 438859EC18B1EB330063BBC8 /* UICKeyChainStore.m in Sources */ = {isa = PBXBuildFile; fileRef = 438859EB18B1EB330063BBC8 /* UICKeyChainStore.m */; }; - 43885A0C18B1F1360063BBC8 /* README.md in Resources */ = {isa = PBXBuildFile; fileRef = 43885A0B18B1F1360063BBC8 /* README.md */; }; - 48989A1F1CF83BA400E96F5F /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 48989A131CF83BA400E96F5F /* AFHTTPSessionManager.m */; }; - 48989A201CF83BA400E96F5F /* AFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 48989A161CF83BA400E96F5F /* AFNetworkReachabilityManager.m */; }; - 48989A211CF83BA400E96F5F /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = 48989A181CF83BA400E96F5F /* AFSecurityPolicy.m */; }; - 48989A221CF83BA400E96F5F /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 48989A1A1CF83BA400E96F5F /* AFURLRequestSerialization.m */; }; - 48989A231CF83BA400E96F5F /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = 48989A1C1CF83BA400E96F5F /* AFURLResponseSerialization.m */; }; - 48989A241CF83BA400E96F5F /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 48989A1E1CF83BA400E96F5F /* AFURLSessionManager.m */; }; - 48989A271CF83BC800E96F5F /* LICENSE in Resources */ = {isa = PBXBuildFile; fileRef = 48989A251CF83BC800E96F5F /* LICENSE */; }; - 48989A281CF83BC800E96F5F /* README.md in Sources */ = {isa = PBXBuildFile; fileRef = 48989A261CF83BC800E96F5F /* README.md */; }; - 48989A3D1CF83C0E00E96F5F /* AFAutoPurgingImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 48989A2A1CF83C0E00E96F5F /* AFAutoPurgingImageCache.m */; }; - 48989A3E1CF83C0E00E96F5F /* AFImageDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 48989A2C1CF83C0E00E96F5F /* AFImageDownloader.m */; }; - 48989A3F1CF83C0E00E96F5F /* AFNetworkActivityIndicatorManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 48989A2E1CF83C0E00E96F5F /* AFNetworkActivityIndicatorManager.m */; }; - 48989A401CF83C0E00E96F5F /* UIActivityIndicatorView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 48989A301CF83C0E00E96F5F /* UIActivityIndicatorView+AFNetworking.m */; }; - 48989A411CF83C0E00E96F5F /* UIButton+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 48989A321CF83C0E00E96F5F /* UIButton+AFNetworking.m */; }; - 48989A421CF83C0E00E96F5F /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 48989A351CF83C0E00E96F5F /* UIImageView+AFNetworking.m */; }; - 48989A431CF83C0E00E96F5F /* UIProgressView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 48989A381CF83C0E00E96F5F /* UIProgressView+AFNetworking.m */; }; - 48989A441CF83C0E00E96F5F /* UIRefreshControl+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 48989A3A1CF83C0E00E96F5F /* UIRefreshControl+AFNetworking.m */; }; - 48989A451CF83C0E00E96F5F /* UIWebView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = 48989A3C1CF83C0E00E96F5F /* UIWebView+AFNetworking.m */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 438859C018B1E90A0063BBC8 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 4388599218B1E90A0063BBC8 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 4388599918B1E90A0063BBC8; - remoteInfo = StudyplusSDKDemo; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXFileReference section */ - 4302C73918B49B5B005A8390 /* SPLStopwatch.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPLStopwatch.h; sourceTree = ""; }; - 4302C73A18B49B5B005A8390 /* SPLStopwatch.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SPLStopwatch.m; sourceTree = ""; }; - 4302C73B18B49B5B005A8390 /* SPLStudyplus.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPLStudyplus.h; sourceTree = ""; }; - 4302C73C18B49B5B005A8390 /* SPLStudyplus.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SPLStudyplus.m; sourceTree = ""; }; - 4302C73D18B49B5B005A8390 /* SPLStudyplusAPIRequest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPLStudyplusAPIRequest.h; sourceTree = ""; }; - 4302C73E18B49B5B005A8390 /* SPLStudyplusAPIRequest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SPLStudyplusAPIRequest.m; sourceTree = ""; }; - 4302C73F18B49B5B005A8390 /* SPLStudyplusDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPLStudyplusDelegate.h; sourceTree = ""; }; - 4302C74018B49B5B005A8390 /* SPLStudyplusError.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPLStudyplusError.h; sourceTree = ""; }; - 4302C74118B49B5B005A8390 /* SPLStudyplusError.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SPLStudyplusError.m; sourceTree = ""; }; - 4302C74218B49B5B005A8390 /* SPLStudyplusLogger.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPLStudyplusLogger.h; sourceTree = ""; }; - 4302C74318B49B5B005A8390 /* SPLStudyplusRecord.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPLStudyplusRecord.h; sourceTree = ""; }; - 4302C74418B49B5B005A8390 /* SPLStudyplusRecord.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SPLStudyplusRecord.m; sourceTree = ""; }; - 4302C74518B49B5B005A8390 /* SPLStudyplusRecordAmount.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SPLStudyplusRecordAmount.h; sourceTree = ""; }; - 4302C74618B49B5B005A8390 /* SPLStudyplusRecordAmount.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SPLStudyplusRecordAmount.m; sourceTree = ""; }; - 4388599A18B1E90A0063BBC8 /* StudyplusSDKDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = StudyplusSDKDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 4388599D18B1E90A0063BBC8 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; - 4388599F18B1E90A0063BBC8 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; - 438859A118B1E90A0063BBC8 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; - 438859A518B1E90A0063BBC8 /* StudyplusSDKDemo-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "StudyplusSDKDemo-Info.plist"; sourceTree = ""; }; - 438859A718B1E90A0063BBC8 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; - 438859A918B1E90A0063BBC8 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; - 438859AB18B1E90A0063BBC8 /* StudyplusSDKDemo-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "StudyplusSDKDemo-Prefix.pch"; sourceTree = ""; }; - 438859AC18B1E90A0063BBC8 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; - 438859AD18B1E90A0063BBC8 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; - 438859B018B1E90A0063BBC8 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; - 438859B218B1E90A0063BBC8 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; - 438859B318B1E90A0063BBC8 /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; - 438859B518B1E90A0063BBC8 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = ""; }; - 438859BB18B1E90A0063BBC8 /* StudyplusSDKDemoTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = StudyplusSDKDemoTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 438859BC18B1E90A0063BBC8 /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = XCTest.framework; path = Library/Frameworks/XCTest.framework; sourceTree = DEVELOPER_DIR; }; - 438859C418B1E90A0063BBC8 /* StudyplusSDKDemoTests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "StudyplusSDKDemoTests-Info.plist"; sourceTree = ""; }; - 438859C618B1E90A0063BBC8 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; - 438859C818B1E90A0063BBC8 /* StudyplusSDKDemoTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = StudyplusSDKDemoTests.m; sourceTree = ""; }; - 438859E518B1EA8D0063BBC8 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; }; - 438859E718B1EA930063BBC8 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; }; - 438859EA18B1EB330063BBC8 /* UICKeyChainStore.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UICKeyChainStore.h; sourceTree = ""; }; - 438859EB18B1EB330063BBC8 /* UICKeyChainStore.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = UICKeyChainStore.m; sourceTree = ""; }; - 43885A0B18B1F1360063BBC8 /* README.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = README.md; sourceTree = ""; }; - 48989A121CF83BA400E96F5F /* AFHTTPSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPSessionManager.h; sourceTree = ""; }; - 48989A131CF83BA400E96F5F /* AFHTTPSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPSessionManager.m; sourceTree = ""; }; - 48989A141CF83BA400E96F5F /* AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworking.h; sourceTree = ""; }; - 48989A151CF83BA400E96F5F /* AFNetworkReachabilityManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkReachabilityManager.h; sourceTree = ""; }; - 48989A161CF83BA400E96F5F /* AFNetworkReachabilityManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkReachabilityManager.m; sourceTree = ""; }; - 48989A171CF83BA400E96F5F /* AFSecurityPolicy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFSecurityPolicy.h; sourceTree = ""; }; - 48989A181CF83BA400E96F5F /* AFSecurityPolicy.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFSecurityPolicy.m; sourceTree = ""; }; - 48989A191CF83BA400E96F5F /* AFURLRequestSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLRequestSerialization.h; sourceTree = ""; }; - 48989A1A1CF83BA400E96F5F /* AFURLRequestSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLRequestSerialization.m; sourceTree = ""; }; - 48989A1B1CF83BA400E96F5F /* AFURLResponseSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLResponseSerialization.h; sourceTree = ""; }; - 48989A1C1CF83BA400E96F5F /* AFURLResponseSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLResponseSerialization.m; sourceTree = ""; }; - 48989A1D1CF83BA400E96F5F /* AFURLSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLSessionManager.h; sourceTree = ""; }; - 48989A1E1CF83BA400E96F5F /* AFURLSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLSessionManager.m; sourceTree = ""; }; - 48989A251CF83BC800E96F5F /* LICENSE */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = LICENSE; path = AFNetworking/LICENSE; sourceTree = ""; }; - 48989A261CF83BC800E96F5F /* README.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = net.daringfireball.markdown; name = README.md; path = AFNetworking/README.md; sourceTree = ""; }; - 48989A291CF83C0E00E96F5F /* AFAutoPurgingImageCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFAutoPurgingImageCache.h; sourceTree = ""; }; - 48989A2A1CF83C0E00E96F5F /* AFAutoPurgingImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFAutoPurgingImageCache.m; sourceTree = ""; }; - 48989A2B1CF83C0E00E96F5F /* AFImageDownloader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFImageDownloader.h; sourceTree = ""; }; - 48989A2C1CF83C0E00E96F5F /* AFImageDownloader.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFImageDownloader.m; sourceTree = ""; }; - 48989A2D1CF83C0E00E96F5F /* AFNetworkActivityIndicatorManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkActivityIndicatorManager.h; sourceTree = ""; }; - 48989A2E1CF83C0E00E96F5F /* AFNetworkActivityIndicatorManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkActivityIndicatorManager.m; sourceTree = ""; }; - 48989A2F1CF83C0E00E96F5F /* UIActivityIndicatorView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIActivityIndicatorView+AFNetworking.h"; sourceTree = ""; }; - 48989A301CF83C0E00E96F5F /* UIActivityIndicatorView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIActivityIndicatorView+AFNetworking.m"; sourceTree = ""; }; - 48989A311CF83C0E00E96F5F /* UIButton+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIButton+AFNetworking.h"; sourceTree = ""; }; - 48989A321CF83C0E00E96F5F /* UIButton+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIButton+AFNetworking.m"; sourceTree = ""; }; - 48989A331CF83C0E00E96F5F /* UIImage+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImage+AFNetworking.h"; sourceTree = ""; }; - 48989A341CF83C0E00E96F5F /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImageView+AFNetworking.h"; sourceTree = ""; }; - 48989A351CF83C0E00E96F5F /* UIImageView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImageView+AFNetworking.m"; sourceTree = ""; }; - 48989A361CF83C0E00E96F5F /* UIKit+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIKit+AFNetworking.h"; sourceTree = ""; }; - 48989A371CF83C0E00E96F5F /* UIProgressView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIProgressView+AFNetworking.h"; sourceTree = ""; }; - 48989A381CF83C0E00E96F5F /* UIProgressView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIProgressView+AFNetworking.m"; sourceTree = ""; }; - 48989A391CF83C0E00E96F5F /* UIRefreshControl+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIRefreshControl+AFNetworking.h"; sourceTree = ""; }; - 48989A3A1CF83C0E00E96F5F /* UIRefreshControl+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIRefreshControl+AFNetworking.m"; sourceTree = ""; }; - 48989A3B1CF83C0E00E96F5F /* UIWebView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIWebView+AFNetworking.h"; sourceTree = ""; }; - 48989A3C1CF83C0E00E96F5F /* UIWebView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIWebView+AFNetworking.m"; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 4388599718B1E90A0063BBC8 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 438859A018B1E90A0063BBC8 /* CoreGraphics.framework in Frameworks */, - 438859E818B1EA930063BBC8 /* SystemConfiguration.framework in Frameworks */, - 438859E618B1EA8D0063BBC8 /* Security.framework in Frameworks */, - 438859A218B1E90A0063BBC8 /* UIKit.framework in Frameworks */, - 4388599E18B1E90A0063BBC8 /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 438859B818B1E90A0063BBC8 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 438859BD18B1E90A0063BBC8 /* XCTest.framework in Frameworks */, - 438859BF18B1E90A0063BBC8 /* UIKit.framework in Frameworks */, - 438859BE18B1E90A0063BBC8 /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 434B85851A4D68F100A6F59E /* AFNetworking */ = { - isa = PBXGroup; - children = ( - 434B85861A4D68F100A6F59E /* AFNetworking */, - 48989A251CF83BC800E96F5F /* LICENSE */, - 48989A261CF83BC800E96F5F /* README.md */, - 434B859C1A4D68F100A6F59E /* UIKit+AFNetworking */, - ); - path = AFNetworking; - sourceTree = ""; - }; - 434B85861A4D68F100A6F59E /* AFNetworking */ = { - isa = PBXGroup; - children = ( - 48989A121CF83BA400E96F5F /* AFHTTPSessionManager.h */, - 48989A131CF83BA400E96F5F /* AFHTTPSessionManager.m */, - 48989A141CF83BA400E96F5F /* AFNetworking.h */, - 48989A151CF83BA400E96F5F /* AFNetworkReachabilityManager.h */, - 48989A161CF83BA400E96F5F /* AFNetworkReachabilityManager.m */, - 48989A171CF83BA400E96F5F /* AFSecurityPolicy.h */, - 48989A181CF83BA400E96F5F /* AFSecurityPolicy.m */, - 48989A191CF83BA400E96F5F /* AFURLRequestSerialization.h */, - 48989A1A1CF83BA400E96F5F /* AFURLRequestSerialization.m */, - 48989A1B1CF83BA400E96F5F /* AFURLResponseSerialization.h */, - 48989A1C1CF83BA400E96F5F /* AFURLResponseSerialization.m */, - 48989A1D1CF83BA400E96F5F /* AFURLSessionManager.h */, - 48989A1E1CF83BA400E96F5F /* AFURLSessionManager.m */, - ); - path = AFNetworking; - sourceTree = ""; - }; - 434B859C1A4D68F100A6F59E /* UIKit+AFNetworking */ = { - isa = PBXGroup; - children = ( - 48989A291CF83C0E00E96F5F /* AFAutoPurgingImageCache.h */, - 48989A2A1CF83C0E00E96F5F /* AFAutoPurgingImageCache.m */, - 48989A2B1CF83C0E00E96F5F /* AFImageDownloader.h */, - 48989A2C1CF83C0E00E96F5F /* AFImageDownloader.m */, - 48989A2D1CF83C0E00E96F5F /* AFNetworkActivityIndicatorManager.h */, - 48989A2E1CF83C0E00E96F5F /* AFNetworkActivityIndicatorManager.m */, - 48989A2F1CF83C0E00E96F5F /* UIActivityIndicatorView+AFNetworking.h */, - 48989A301CF83C0E00E96F5F /* UIActivityIndicatorView+AFNetworking.m */, - 48989A311CF83C0E00E96F5F /* UIButton+AFNetworking.h */, - 48989A321CF83C0E00E96F5F /* UIButton+AFNetworking.m */, - 48989A331CF83C0E00E96F5F /* UIImage+AFNetworking.h */, - 48989A341CF83C0E00E96F5F /* UIImageView+AFNetworking.h */, - 48989A351CF83C0E00E96F5F /* UIImageView+AFNetworking.m */, - 48989A361CF83C0E00E96F5F /* UIKit+AFNetworking.h */, - 48989A371CF83C0E00E96F5F /* UIProgressView+AFNetworking.h */, - 48989A381CF83C0E00E96F5F /* UIProgressView+AFNetworking.m */, - 48989A391CF83C0E00E96F5F /* UIRefreshControl+AFNetworking.h */, - 48989A3A1CF83C0E00E96F5F /* UIRefreshControl+AFNetworking.m */, - 48989A3B1CF83C0E00E96F5F /* UIWebView+AFNetworking.h */, - 48989A3C1CF83C0E00E96F5F /* UIWebView+AFNetworking.m */, - ); - path = "UIKit+AFNetworking"; - sourceTree = ""; - }; - 4388599118B1E90A0063BBC8 = { - isa = PBXGroup; - children = ( - 43885A0B18B1F1360063BBC8 /* README.md */, - 43885A0A18B1F0D00063BBC8 /* Libraries */, - 4388599C18B1E90A0063BBC8 /* Frameworks */, - 4388599B18B1E90A0063BBC8 /* Products */, - 438859D218B1E9ED0063BBC8 /* StudyplusSDK */, - 438859A318B1E90A0063BBC8 /* StudyplusSDKDemo */, - 438859C218B1E90A0063BBC8 /* StudyplusSDKDemoTests */, - ); - sourceTree = ""; - }; - 4388599B18B1E90A0063BBC8 /* Products */ = { - isa = PBXGroup; - children = ( - 4388599A18B1E90A0063BBC8 /* StudyplusSDKDemo.app */, - 438859BB18B1E90A0063BBC8 /* StudyplusSDKDemoTests.xctest */, - ); - name = Products; - sourceTree = ""; - }; - 4388599C18B1E90A0063BBC8 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 438859E718B1EA930063BBC8 /* SystemConfiguration.framework */, - 438859E518B1EA8D0063BBC8 /* Security.framework */, - 4388599D18B1E90A0063BBC8 /* Foundation.framework */, - 4388599F18B1E90A0063BBC8 /* CoreGraphics.framework */, - 438859A118B1E90A0063BBC8 /* UIKit.framework */, - 438859BC18B1E90A0063BBC8 /* XCTest.framework */, - ); - name = Frameworks; - sourceTree = ""; - }; - 438859A318B1E90A0063BBC8 /* StudyplusSDKDemo */ = { - isa = PBXGroup; - children = ( - 438859AC18B1E90A0063BBC8 /* AppDelegate.h */, - 438859AD18B1E90A0063BBC8 /* AppDelegate.m */, - 438859AF18B1E90A0063BBC8 /* Main.storyboard */, - 438859B218B1E90A0063BBC8 /* ViewController.h */, - 438859B318B1E90A0063BBC8 /* ViewController.m */, - 438859B518B1E90A0063BBC8 /* Images.xcassets */, - 438859A418B1E90A0063BBC8 /* Supporting Files */, - ); - path = StudyplusSDKDemo; - sourceTree = ""; - }; - 438859A418B1E90A0063BBC8 /* Supporting Files */ = { - isa = PBXGroup; - children = ( - 438859A518B1E90A0063BBC8 /* StudyplusSDKDemo-Info.plist */, - 438859A618B1E90A0063BBC8 /* InfoPlist.strings */, - 438859A918B1E90A0063BBC8 /* main.m */, - 438859AB18B1E90A0063BBC8 /* StudyplusSDKDemo-Prefix.pch */, - ); - name = "Supporting Files"; - sourceTree = ""; - }; - 438859C218B1E90A0063BBC8 /* StudyplusSDKDemoTests */ = { - isa = PBXGroup; - children = ( - 438859C818B1E90A0063BBC8 /* StudyplusSDKDemoTests.m */, - 438859C318B1E90A0063BBC8 /* Supporting Files */, - ); - path = StudyplusSDKDemoTests; - sourceTree = ""; - }; - 438859C318B1E90A0063BBC8 /* Supporting Files */ = { - isa = PBXGroup; - children = ( - 438859C418B1E90A0063BBC8 /* StudyplusSDKDemoTests-Info.plist */, - 438859C518B1E90A0063BBC8 /* InfoPlist.strings */, - ); - name = "Supporting Files"; - sourceTree = ""; - }; - 438859D218B1E9ED0063BBC8 /* StudyplusSDK */ = { - isa = PBXGroup; - children = ( - 4302C73918B49B5B005A8390 /* SPLStopwatch.h */, - 4302C73A18B49B5B005A8390 /* SPLStopwatch.m */, - 4302C73B18B49B5B005A8390 /* SPLStudyplus.h */, - 4302C73C18B49B5B005A8390 /* SPLStudyplus.m */, - 4302C73D18B49B5B005A8390 /* SPLStudyplusAPIRequest.h */, - 4302C73E18B49B5B005A8390 /* SPLStudyplusAPIRequest.m */, - 4302C73F18B49B5B005A8390 /* SPLStudyplusDelegate.h */, - 4302C74018B49B5B005A8390 /* SPLStudyplusError.h */, - 4302C74118B49B5B005A8390 /* SPLStudyplusError.m */, - 4302C74218B49B5B005A8390 /* SPLStudyplusLogger.h */, - 4302C74318B49B5B005A8390 /* SPLStudyplusRecord.h */, - 4302C74418B49B5B005A8390 /* SPLStudyplusRecord.m */, - 4302C74518B49B5B005A8390 /* SPLStudyplusRecordAmount.h */, - 4302C74618B49B5B005A8390 /* SPLStudyplusRecordAmount.m */, - ); - path = StudyplusSDK; - sourceTree = ""; - }; - 438859E918B1EB1E0063BBC8 /* UICKeyChainStore */ = { - isa = PBXGroup; - children = ( - 438859EA18B1EB330063BBC8 /* UICKeyChainStore.h */, - 438859EB18B1EB330063BBC8 /* UICKeyChainStore.m */, - ); - name = UICKeyChainStore; - sourceTree = ""; - }; - 43885A0A18B1F0D00063BBC8 /* Libraries */ = { - isa = PBXGroup; - children = ( - 434B85851A4D68F100A6F59E /* AFNetworking */, - 438859E918B1EB1E0063BBC8 /* UICKeyChainStore */, - ); - name = Libraries; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 4388599918B1E90A0063BBC8 /* StudyplusSDKDemo */ = { - isa = PBXNativeTarget; - buildConfigurationList = 438859CC18B1E90B0063BBC8 /* Build configuration list for PBXNativeTarget "StudyplusSDKDemo" */; - buildPhases = ( - 4388599618B1E90A0063BBC8 /* Sources */, - 4388599718B1E90A0063BBC8 /* Frameworks */, - 4388599818B1E90A0063BBC8 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = StudyplusSDKDemo; - productName = StudyplusSDKDemo; - productReference = 4388599A18B1E90A0063BBC8 /* StudyplusSDKDemo.app */; - productType = "com.apple.product-type.application"; - }; - 438859BA18B1E90A0063BBC8 /* StudyplusSDKDemoTests */ = { - isa = PBXNativeTarget; - buildConfigurationList = 438859CF18B1E90B0063BBC8 /* Build configuration list for PBXNativeTarget "StudyplusSDKDemoTests" */; - buildPhases = ( - 438859B718B1E90A0063BBC8 /* Sources */, - 438859B818B1E90A0063BBC8 /* Frameworks */, - 438859B918B1E90A0063BBC8 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 438859C118B1E90A0063BBC8 /* PBXTargetDependency */, - ); - name = StudyplusSDKDemoTests; - productName = StudyplusSDKDemoTests; - productReference = 438859BB18B1E90A0063BBC8 /* StudyplusSDKDemoTests.xctest */; - productType = "com.apple.product-type.bundle.unit-test"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 4388599218B1E90A0063BBC8 /* Project object */ = { - isa = PBXProject; - attributes = { - LastUpgradeCheck = 0820; - ORGANIZATIONNAME = studyplus.jp; - TargetAttributes = { - 438859BA18B1E90A0063BBC8 = { - TestTargetID = 4388599918B1E90A0063BBC8; - }; - }; - }; - buildConfigurationList = 4388599518B1E90A0063BBC8 /* Build configuration list for PBXProject "StudyplusSDKDemo" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 4388599118B1E90A0063BBC8; - productRefGroup = 4388599B18B1E90A0063BBC8 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 4388599918B1E90A0063BBC8 /* StudyplusSDKDemo */, - 438859BA18B1E90A0063BBC8 /* StudyplusSDKDemoTests */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 4388599818B1E90A0063BBC8 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 438859B618B1E90A0063BBC8 /* Images.xcassets in Resources */, - 438859A818B1E90A0063BBC8 /* InfoPlist.strings in Resources */, - 43885A0C18B1F1360063BBC8 /* README.md in Resources */, - 438859B118B1E90A0063BBC8 /* Main.storyboard in Resources */, - 48989A271CF83BC800E96F5F /* LICENSE in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 438859B918B1E90A0063BBC8 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 438859C718B1E90A0063BBC8 /* InfoPlist.strings in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 4388599618B1E90A0063BBC8 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 438859B418B1E90A0063BBC8 /* ViewController.m in Sources */, - 48989A1F1CF83BA400E96F5F /* AFHTTPSessionManager.m in Sources */, - 48989A201CF83BA400E96F5F /* AFNetworkReachabilityManager.m in Sources */, - 4302C74A18B49B5B005A8390 /* SPLStudyplusAPIRequest.m in Sources */, - 48989A3F1CF83C0E00E96F5F /* AFNetworkActivityIndicatorManager.m in Sources */, - 48989A421CF83C0E00E96F5F /* UIImageView+AFNetworking.m in Sources */, - 4302C74C18B49B5B005A8390 /* SPLStudyplusRecord.m in Sources */, - 48989A401CF83C0E00E96F5F /* UIActivityIndicatorView+AFNetworking.m in Sources */, - 48989A451CF83C0E00E96F5F /* UIWebView+AFNetworking.m in Sources */, - 48989A281CF83BC800E96F5F /* README.md in Sources */, - 48989A221CF83BA400E96F5F /* AFURLRequestSerialization.m in Sources */, - 48989A211CF83BA400E96F5F /* AFSecurityPolicy.m in Sources */, - 48989A241CF83BA400E96F5F /* AFURLSessionManager.m in Sources */, - 4302C74818B49B5B005A8390 /* SPLStopwatch.m in Sources */, - 4302C74918B49B5B005A8390 /* SPLStudyplus.m in Sources */, - 4302C74B18B49B5B005A8390 /* SPLStudyplusError.m in Sources */, - 48989A3E1CF83C0E00E96F5F /* AFImageDownloader.m in Sources */, - 48989A431CF83C0E00E96F5F /* UIProgressView+AFNetworking.m in Sources */, - 438859AE18B1E90A0063BBC8 /* AppDelegate.m in Sources */, - 48989A411CF83C0E00E96F5F /* UIButton+AFNetworking.m in Sources */, - 438859AA18B1E90A0063BBC8 /* main.m in Sources */, - 4302C74D18B49B5B005A8390 /* SPLStudyplusRecordAmount.m in Sources */, - 48989A3D1CF83C0E00E96F5F /* AFAutoPurgingImageCache.m in Sources */, - 48989A441CF83C0E00E96F5F /* UIRefreshControl+AFNetworking.m in Sources */, - 438859EC18B1EB330063BBC8 /* UICKeyChainStore.m in Sources */, - 48989A231CF83BA400E96F5F /* AFURLResponseSerialization.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 438859B718B1E90A0063BBC8 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 438859C918B1E90A0063BBC8 /* StudyplusSDKDemoTests.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 438859C118B1E90A0063BBC8 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 4388599918B1E90A0063BBC8 /* StudyplusSDKDemo */; - targetProxy = 438859C018B1E90A0063BBC8 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin PBXVariantGroup section */ - 438859A618B1E90A0063BBC8 /* InfoPlist.strings */ = { - isa = PBXVariantGroup; - children = ( - 438859A718B1E90A0063BBC8 /* en */, - ); - name = InfoPlist.strings; - sourceTree = ""; - }; - 438859AF18B1E90A0063BBC8 /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 438859B018B1E90A0063BBC8 /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; - 438859C518B1E90A0063BBC8 /* InfoPlist.strings */ = { - isa = PBXVariantGroup; - children = ( - 438859C618B1E90A0063BBC8 /* en */, - ); - name = InfoPlist.strings; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 438859CA18B1E90B0063BBC8 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - }; - name = Debug; - }; - 438859CB18B1E90B0063BBC8 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = YES; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - SDKROOT = iphoneos; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 438859CD18B1E90B0063BBC8 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; - DEVELOPMENT_TEAM = ""; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "StudyplusSDKDemo/StudyplusSDKDemo-Prefix.pch"; - INFOPLIST_FILE = "StudyplusSDKDemo/StudyplusSDKDemo-Info.plist"; - PRODUCT_BUNDLE_IDENTIFIER = "jp.studyplus.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME)"; - WRAPPER_EXTENSION = app; - }; - name = Debug; - }; - 438859CE18B1E90B0063BBC8 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; - DEVELOPMENT_TEAM = ""; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "StudyplusSDKDemo/StudyplusSDKDemo-Prefix.pch"; - INFOPLIST_FILE = "StudyplusSDKDemo/StudyplusSDKDemo-Info.plist"; - PRODUCT_BUNDLE_IDENTIFIER = "jp.studyplus.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME)"; - WRAPPER_EXTENSION = app; - }; - name = Release; - }; - 438859D018B1E90B0063BBC8 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(BUILT_PRODUCTS_DIR)/StudyplusSDKDemo.app/StudyplusSDKDemo"; - DEVELOPMENT_TEAM = ""; - FRAMEWORK_SEARCH_PATHS = ( - "$(SDKROOT)/Developer/Library/Frameworks", - "$(inherited)", - "$(DEVELOPER_FRAMEWORKS_DIR)", - ); - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "StudyplusSDKDemo/StudyplusSDKDemo-Prefix.pch"; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - INFOPLIST_FILE = "StudyplusSDKDemoTests/StudyplusSDKDemoTests-Info.plist"; - PRODUCT_BUNDLE_IDENTIFIER = "jp.studyplus.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME)"; - TEST_HOST = "$(BUNDLE_LOADER)"; - WRAPPER_EXTENSION = xctest; - }; - name = Debug; - }; - 438859D118B1E90B0063BBC8 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(BUILT_PRODUCTS_DIR)/StudyplusSDKDemo.app/StudyplusSDKDemo"; - DEVELOPMENT_TEAM = ""; - FRAMEWORK_SEARCH_PATHS = ( - "$(SDKROOT)/Developer/Library/Frameworks", - "$(inherited)", - "$(DEVELOPER_FRAMEWORKS_DIR)", - ); - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "StudyplusSDKDemo/StudyplusSDKDemo-Prefix.pch"; - INFOPLIST_FILE = "StudyplusSDKDemoTests/StudyplusSDKDemoTests-Info.plist"; - PRODUCT_BUNDLE_IDENTIFIER = "jp.studyplus.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME)"; - TEST_HOST = "$(BUNDLE_LOADER)"; - WRAPPER_EXTENSION = xctest; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 4388599518B1E90A0063BBC8 /* Build configuration list for PBXProject "StudyplusSDKDemo" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 438859CA18B1E90B0063BBC8 /* Debug */, - 438859CB18B1E90B0063BBC8 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 438859CC18B1E90B0063BBC8 /* Build configuration list for PBXNativeTarget "StudyplusSDKDemo" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 438859CD18B1E90B0063BBC8 /* Debug */, - 438859CE18B1E90B0063BBC8 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 438859CF18B1E90B0063BBC8 /* Build configuration list for PBXNativeTarget "StudyplusSDKDemoTests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 438859D018B1E90B0063BBC8 /* Debug */, - 438859D118B1E90B0063BBC8 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 4388599218B1E90A0063BBC8 /* Project object */; -} diff --git a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/AppDelegate.h b/Demo/StudyplusSDKDemo/StudyplusSDKDemo/AppDelegate.h deleted file mode 100644 index 558a243..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/AppDelegate.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// AppDelegate.h -// StudyplusSDKDemo -// -// Created by akitsukada on 2014/02/17. -// Copyright (c) 2014年 studyplus.jp. All rights reserved. -// - -#import - -@interface AppDelegate : UIResponder - -@property (strong, nonatomic) UIWindow *window; - -@end diff --git a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/AppDelegate.m b/Demo/StudyplusSDKDemo/StudyplusSDKDemo/AppDelegate.m deleted file mode 100644 index 959ca77..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/AppDelegate.m +++ /dev/null @@ -1,56 +0,0 @@ -// -// AppDelegate.m -// StudyplusSDKDemo -// -// Created by akitsukada on 2014/02/17. -// Copyright (c) 2014年 studyplus.jp. All rights reserved. -// - -#import "AppDelegate.h" -#import "ViewController.h" - -@implementation AppDelegate{ -} - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions -{ - // Override point for customization after application launch. - return YES; -} - -- (void)applicationWillResignActive:(UIApplication *)application -{ - // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. -} - -- (void)applicationDidEnterBackground:(UIApplication *)application -{ - // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. -} - -- (void)applicationWillEnterForeground:(UIApplication *)application -{ - // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. -} - -- (void)applicationDidBecomeActive:(UIApplication *)application -{ - // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. -} - -- (void)applicationWillTerminate:(UIApplication *)application -{ - // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. -} - -- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation -{ - ViewController *vc; - vc = [ViewController new]; - NSLog(@"%@", vc); - return [vc openURL:url]; -} - -@end diff --git a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/Base.lproj/Main.storyboard b/Demo/StudyplusSDKDemo/StudyplusSDKDemo/Base.lproj/Main.storyboard deleted file mode 100644 index 4f0f18d..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/Base.lproj/Main.storyboard +++ /dev/null @@ -1,157 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/Images.xcassets/AppIcon.appiconset/Contents.json b/Demo/StudyplusSDKDemo/StudyplusSDKDemo/Images.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index 118c98f..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/Images.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "images" : [ - { - "idiom" : "iphone", - "size" : "29x29", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "29x29", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "40x40", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "40x40", - "scale" : "3x" - }, - { - "idiom" : "iphone", - "size" : "60x60", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "60x60", - "scale" : "3x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/Images.xcassets/LaunchImage.launchimage/Contents.json b/Demo/StudyplusSDKDemo/StudyplusSDKDemo/Images.xcassets/LaunchImage.launchimage/Contents.json deleted file mode 100644 index c79ebd3..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/Images.xcassets/LaunchImage.launchimage/Contents.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "images" : [ - { - "orientation" : "portrait", - "idiom" : "iphone", - "extent" : "full-screen", - "minimum-system-version" : "7.0", - "scale" : "2x" - }, - { - "orientation" : "portrait", - "idiom" : "iphone", - "subtype" : "retina4", - "extent" : "full-screen", - "minimum-system-version" : "7.0", - "scale" : "2x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/StudyplusSDKDemo-Prefix.pch b/Demo/StudyplusSDKDemo/StudyplusSDKDemo/StudyplusSDKDemo-Prefix.pch deleted file mode 100644 index 82a2bb4..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/StudyplusSDKDemo-Prefix.pch +++ /dev/null @@ -1,16 +0,0 @@ -// -// Prefix header -// -// The contents of this file are implicitly included at the beginning of every source file. -// - -#import - -#ifndef __IPHONE_5_0 -#warning "This project uses features only available in iOS SDK 5.0 and later." -#endif - -#ifdef __OBJC__ - #import - #import -#endif diff --git a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/ViewController.h b/Demo/StudyplusSDKDemo/StudyplusSDKDemo/ViewController.h deleted file mode 100644 index 6915e83..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/ViewController.h +++ /dev/null @@ -1,14 +0,0 @@ -// -// ViewController.h -// StudyplusSDKDemo -// -// Created by akitsukada on 2014/02/17. -// Copyright (c) 2014年 studyplus.jp. All rights reserved. -// - -#import -#import "SPLStudyplusDelegate.h" - -@interface ViewController : UIViewController --(BOOL)openURL:(NSURL*)url; -@end diff --git a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/ViewController.m b/Demo/StudyplusSDKDemo/StudyplusSDKDemo/ViewController.m deleted file mode 100644 index 0dcd74e..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/ViewController.m +++ /dev/null @@ -1,153 +0,0 @@ -// -// ViewController.m -// StudyplusSDKDemo -// -// Created by akitsukada on 2014/02/17. -// Copyright (c) 2014年 studyplus.jp. All rights reserved. -// - -#import "ViewController.h" -#import "SPLStudyplus.h" - -static NSString * const ConsumerKey = @"Your consumer key"; -static NSString * const ConsumerSecret = @"Your consumer secret"; - -@interface ViewController () -@property (weak, nonatomic) IBOutlet UILabel *elapsedSecondsLabel; -@property (weak, nonatomic) IBOutlet UILabel *isConnectedLabel; -@property (weak, nonatomic) IBOutlet UILabel *actionResultLabel; -@end - -SPLStudyplus *studyplus; - -@implementation ViewController - -- (void)viewDidLoad -{ - [super viewDidLoad]; - // Do any additional setup after loading the view, typically from a nib. - - [NSTimer - scheduledTimerWithTimeInterval:0.3f - target:self - selector:@selector(updateElapsedSeconds) - userInfo:nil - repeats:YES - ]; - - [self updateIsConnected]; -} - -- (IBAction)auth:(id)sender { - [self.studyplus auth]; -} - -- (IBAction)login:(id)sender { - [self.studyplus login]; -} - -- (IBAction)logout:(id)sender { - [self.studyplus logout]; - self.actionResultLabel.text = @"Logged out"; - [self updateIsConnected]; -} - -- (IBAction)isConnected:(id)sender { - [self updateIsConnected]; -} - -- (IBAction)post:(id)sender { - // Create new study record. - SPLStudyplusRecord *studyplusRecord = - [SPLStudyplusRecord - - // @see SPLStopwatch - recordWithDuration:[[self studyplus].stopwatch elapsedSeconds] - - /** You can add optional info. - options:@{ - // Time the learning is ended. 学習を終えた日時。 - @"recordedAt" : [NSDate date], - // Studyplus timeline comment. Studyplusのタイムライン上で表示されるコメント。 - @"comment" : @"アプリ◯◯で勉強しました!!", - // @see SPLStudyplusRecordAmount - @"amount" : [SPLStudyplusRecordAmount amount:100], - } - */ - ]; - - // post - [self.studyplus postStudyRecord:studyplusRecord]; -} - -- (IBAction)startStopwatch:(id)sender { - [[self studyplus].stopwatch start]; - self.elapsedSecondsLabel.backgroundColor = [UIColor cyanColor]; -} - -- (IBAction)pauseStopwatch:(id)sender { - [[self studyplus].stopwatch pause]; - self.elapsedSecondsLabel.backgroundColor = [UIColor groupTableViewBackgroundColor]; -} - -- (IBAction)resetStopwatch:(id)sender { - [[self studyplus].stopwatch reset]; -} - -- (void)updateElapsedSeconds { - self.elapsedSecondsLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)[[self studyplus].stopwatch elapsedSeconds]]; -} - -- (void)updateIsConnected { - self.isConnectedLabel.text = [[self studyplus] isConnected] ? @"YES" : @"NO"; - self.actionResultLabel.text = @""; -} - --(SPLStudyplus*)studyplus -{ - if (studyplus) { - return studyplus; - } - - studyplus = [SPLStudyplus studyplusWithConsumerKey:ConsumerKey - andConsumerSecret:ConsumerSecret]; - studyplus.delegate = self; - return studyplus; -} - -// Called by AppDelegate --(BOOL) openURL:(NSURL*)url -{ - return [self.studyplus openURL:url]; -} - -// callback methods --(void)studyplusDidConnect:(SPLStudyplus*)studyplus -{ - self.actionResultLabel.text = @"Auth or Login succeeded"; - [self updateIsConnected]; -} - --(void)studyplusDidFailToConnect:(SPLStudyplus*)studyplus withError:(NSError*)error -{ - self.actionResultLabel.text = @"Auth or Login failed"; - [self updateIsConnected]; -} - -- (void)studyplusDidCancel:(SPLStudyplus*)studyplus -{ - self.actionResultLabel.text = @"Auth or Login canceled"; - [self updateIsConnected]; -} - --(void)studyplusDidPostStudyRecord:(SPLStudyplus*)studyplus -{ - self.actionResultLabel.text = @"Post to Studyplus succeeded"; -} - --(void)studyplusDidFailToPostStudyRecord:(SPLStudyplus*)studyplus withError:(NSError*)error -{ - self.actionResultLabel.text = error.localizedDescription; -} - -@end diff --git a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/en.lproj/InfoPlist.strings b/Demo/StudyplusSDKDemo/StudyplusSDKDemo/en.lproj/InfoPlist.strings deleted file mode 100644 index 477b28f..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/en.lproj/InfoPlist.strings +++ /dev/null @@ -1,2 +0,0 @@ -/* Localized versions of Info.plist keys */ - diff --git a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/main.m b/Demo/StudyplusSDKDemo/StudyplusSDKDemo/main.m deleted file mode 100644 index 5d60e8c..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/main.m +++ /dev/null @@ -1,18 +0,0 @@ -// -// main.m -// StudyplusSDKDemo -// -// Created by akitsukada on 2014/02/17. -// Copyright (c) 2014年 studyplus.jp. All rights reserved. -// - -#import - -#import "AppDelegate.h" - -int main(int argc, char * argv[]) -{ - @autoreleasepool { - return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); - } -} diff --git a/Demo/StudyplusSDKDemo/StudyplusSDKDemoTests/StudyplusSDKDemoTests.m b/Demo/StudyplusSDKDemo/StudyplusSDKDemoTests/StudyplusSDKDemoTests.m deleted file mode 100644 index ad9bcf8..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDKDemoTests/StudyplusSDKDemoTests.m +++ /dev/null @@ -1,34 +0,0 @@ -// -// StudyplusSDKDemoTests.m -// StudyplusSDKDemoTests -// -// Created by akitsukada on 2014/02/17. -// Copyright (c) 2014年 studyplus.jp. All rights reserved. -// - -#import - -@interface StudyplusSDKDemoTests : XCTestCase - -@end - -@implementation StudyplusSDKDemoTests - -- (void)setUp -{ - [super setUp]; - // Put setup code here. This method is called before the invocation of each test method in the class. -} - -- (void)tearDown -{ - // Put teardown code here. This method is called after the invocation of each test method in the class. - [super tearDown]; -} - -- (void)testExample -{ - XCTFail(@"No implementation for \"%s\"", __PRETTY_FUNCTION__); -} - -@end diff --git a/Demo/StudyplusSDKDemo/StudyplusSDKDemoTests/en.lproj/InfoPlist.strings b/Demo/StudyplusSDKDemo/StudyplusSDKDemoTests/en.lproj/InfoPlist.strings deleted file mode 100644 index 477b28f..0000000 --- a/Demo/StudyplusSDKDemo/StudyplusSDKDemoTests/en.lproj/InfoPlist.strings +++ /dev/null @@ -1,2 +0,0 @@ -/* Localized versions of Info.plist keys */ - diff --git a/Demo/StudyplusSDKDemo/UICKeyChainStore.h b/Demo/StudyplusSDKDemo/UICKeyChainStore.h deleted file mode 100644 index 0731095..0000000 --- a/Demo/StudyplusSDKDemo/UICKeyChainStore.h +++ /dev/null @@ -1,59 +0,0 @@ -// -// UICKeyChainStore.h -// UICKeyChainStore -// -// Created by Kishikawa Katsumi on 11/11/20. -// Copyright (c) 2011 Kishikawa Katsumi. All rights reserved. -// - -#import - -@interface UICKeyChainStore : NSObject - -@property (nonatomic, readonly) NSString *service; -@property (nonatomic, readonly) NSString *accessGroup; - -+ (NSString *)defaultService; -+ (void)setDefaultService:(NSString *)defaultService; - -+ (UICKeyChainStore *)keyChainStore; -+ (UICKeyChainStore *)keyChainStoreWithService:(NSString *)service; -+ (UICKeyChainStore *)keyChainStoreWithService:(NSString *)service accessGroup:(NSString *)accessGroup; - -- (instancetype)init; -- (instancetype)initWithService:(NSString *)service; -- (instancetype)initWithService:(NSString *)service accessGroup:(NSString *)accessGroup; - -+ (NSString *)stringForKey:(NSString *)key; -+ (NSString *)stringForKey:(NSString *)key service:(NSString *)service; -+ (NSString *)stringForKey:(NSString *)key service:(NSString *)service accessGroup:(NSString *)accessGroup; -+ (BOOL)setString:(NSString *)value forKey:(NSString *)key; -+ (BOOL)setString:(NSString *)value forKey:(NSString *)key service:(NSString *)service; -+ (BOOL)setString:(NSString *)value forKey:(NSString *)key service:(NSString *)service accessGroup:(NSString *)accessGroup; - -+ (NSData *)dataForKey:(NSString *)key; -+ (NSData *)dataForKey:(NSString *)key service:(NSString *)service; -+ (NSData *)dataForKey:(NSString *)key service:(NSString *)service accessGroup:(NSString *)accessGroup; -+ (BOOL)setData:(NSData *)data forKey:(NSString *)key; -+ (BOOL)setData:(NSData *)data forKey:(NSString *)key service:(NSString *)service; -+ (BOOL)setData:(NSData *)data forKey:(NSString *)key service:(NSString *)service accessGroup:(NSString *)accessGroup; - -- (void)setString:(NSString *)string forKey:(NSString *)key; -- (NSString *)stringForKey:(NSString *)key; - -- (void)setData:(NSData *)data forKey:(NSString *)key; -- (NSData *)dataForKey:(NSString *)key; - -+ (BOOL)removeItemForKey:(NSString *)key; -+ (BOOL)removeItemForKey:(NSString *)key service:(NSString *)service; -+ (BOOL)removeItemForKey:(NSString *)key service:(NSString *)service accessGroup:(NSString *)accessGroup; -+ (BOOL)removeAllItems; -+ (BOOL)removeAllItemsForService:(NSString *)service; -+ (BOOL)removeAllItemsForService:(NSString *)service accessGroup:(NSString *)accessGroup; - -- (void)removeItemForKey:(NSString *)key; -- (void)removeAllItems; - -- (void)synchronize; - -@end diff --git a/Demo/StudyplusSDKDemo/UICKeyChainStore.m b/Demo/StudyplusSDKDemo/UICKeyChainStore.m deleted file mode 100644 index 7b074fb..0000000 --- a/Demo/StudyplusSDKDemo/UICKeyChainStore.m +++ /dev/null @@ -1,421 +0,0 @@ -// -// UICKeyChainStore.m -// UICKeyChainStore -// -// Created by Kishikawa Katsumi on 11/11/20. -// Copyright (c) 2011 Kishikawa Katsumi. All rights reserved. -// - -#import "UICKeyChainStore.h" - -static NSString *_defaultService; - -@interface UICKeyChainStore () { - NSMutableDictionary *itemsToUpdate; -} - -@end - -@implementation UICKeyChainStore - -+ (NSString *)defaultService -{ - if (!_defaultService) { - _defaultService = [[NSBundle mainBundle] bundleIdentifier]; - } - - return _defaultService; -} - -+ (void)setDefaultService:(NSString *)defaultService -{ - _defaultService = defaultService; -} - -#pragma mark - - -+ (UICKeyChainStore *)keyChainStore -{ - return [[self alloc] initWithService:[self defaultService]]; -} - -+ (UICKeyChainStore *)keyChainStoreWithService:(NSString *)service -{ - return [[self alloc] initWithService:service]; -} - -+ (UICKeyChainStore *)keyChainStoreWithService:(NSString *)service accessGroup:(NSString *)accessGroup { - return [[self alloc] initWithService:service accessGroup:accessGroup]; -} - -- (instancetype)init -{ - return [self initWithService:[self.class defaultService] accessGroup:nil]; -} - -- (instancetype)initWithService:(NSString *)service -{ - return [self initWithService:service accessGroup:nil]; -} - -- (instancetype)initWithService:(NSString *)service accessGroup:(NSString *)accessGroup -{ - self = [super init]; - if (self) { - if (!service) { - service = [self.class defaultService]; - } - _service = [service copy]; - _accessGroup = [accessGroup copy]; - - itemsToUpdate = [[NSMutableDictionary alloc] init]; - } - - return self; -} - -#pragma mark - - -+ (NSString *)stringForKey:(NSString *)key -{ - return [self stringForKey:key service:[self defaultService] accessGroup:nil]; -} - -+ (NSString *)stringForKey:(NSString *)key service:(NSString *)service -{ - return [self stringForKey:key service:service accessGroup:nil]; -} - -+ (NSString *)stringForKey:(NSString *)key service:(NSString *)service accessGroup:(NSString *)accessGroup -{ - NSData *data = [self dataForKey:key service:service accessGroup:accessGroup]; - if (data) { - return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - } - - return nil; -} - -+ (BOOL)setString:(NSString *)value forKey:(NSString *)key -{ - return [self setString:value forKey:key service:[self defaultService] accessGroup:nil]; -} - -+ (BOOL)setString:(NSString *)value forKey:(NSString *)key service:(NSString *)service -{ - return [self setString:value forKey:key service:service accessGroup:nil]; -} - -+ (BOOL)setString:(NSString *)value forKey:(NSString *)key service:(NSString *)service accessGroup:(NSString *)accessGroup -{ - NSData *data = [value dataUsingEncoding:NSUTF8StringEncoding]; - return [self setData:data forKey:key service:service accessGroup:accessGroup]; -} - -#pragma mark - - -+ (NSData *)dataForKey:(NSString *)key -{ - return [self dataForKey:key service:[self defaultService] accessGroup:nil]; -} - -+ (NSData *)dataForKey:(NSString *)key service:(NSString *)service -{ - return [self dataForKey:key service:service accessGroup:nil]; -} - -+ (NSData *)dataForKey:(NSString *)key service:(NSString *)service accessGroup:(NSString *)accessGroup -{ - if (!key) { - return nil; - } - if (!service) { - service = [self defaultService]; - } - - NSMutableDictionary *query = [[NSMutableDictionary alloc] init]; - [query setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass]; - [query setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData]; - [query setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit]; - [query setObject:service forKey:(__bridge id)kSecAttrService]; - [query setObject:key forKey:(__bridge id)kSecAttrGeneric]; - [query setObject:key forKey:(__bridge id)kSecAttrAccount]; -#if !TARGET_IPHONE_SIMULATOR && defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - if (accessGroup) { - [query setObject:accessGroup forKey:(__bridge id)kSecAttrAccessGroup]; - } -#endif - - CFTypeRef data = nil; - OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &data); - if (status != errSecSuccess) { - return nil; - } - - NSData *ret = [NSData dataWithData:(__bridge NSData *)data]; - if (data) { - CFRelease(data); - } - - return ret; -} - -+ (BOOL)setData:(NSData *)data forKey:(NSString *)key -{ - return [self setData:data forKey:key service:[self defaultService] accessGroup:nil]; -} - -+ (BOOL)setData:(NSData *)data forKey:(NSString *)key service:(NSString *)service -{ - return [self setData:data forKey:key service:service accessGroup:nil]; -} - -+ (BOOL)setData:(NSData *)data forKey:(NSString *)key service:(NSString *)service accessGroup:(NSString *)accessGroup -{ - if (!key) { - return NO; - } - if (!service) { - service = [self defaultService]; - } - - NSMutableDictionary *query = [[NSMutableDictionary alloc] init]; - [query setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass]; - [query setObject:service forKey:(__bridge id)kSecAttrService]; - [query setObject:key forKey:(__bridge id)kSecAttrGeneric]; - [query setObject:key forKey:(__bridge id)kSecAttrAccount]; -#if !TARGET_IPHONE_SIMULATOR && defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - if (accessGroup) { - [query setObject:accessGroup forKey:(__bridge id)kSecAttrAccessGroup]; - } -#endif - - OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, NULL); - if (status == errSecSuccess) { - if (data) { - NSMutableDictionary *attributesToUpdate = [[NSMutableDictionary alloc] init]; - [attributesToUpdate setObject:data forKey:(__bridge id)kSecValueData]; - - status = SecItemUpdate((__bridge CFDictionaryRef)query, (__bridge CFDictionaryRef)attributesToUpdate); - if (status != errSecSuccess) { - return NO; - } - } else { - [self removeItemForKey:key service:service accessGroup:accessGroup]; - } - } else if (status == errSecItemNotFound) { - NSMutableDictionary *attributes = [[NSMutableDictionary alloc] init]; - [attributes setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass]; - [attributes setObject:service forKey:(__bridge id)kSecAttrService]; - [attributes setObject:key forKey:(__bridge id)kSecAttrGeneric]; - [attributes setObject:key forKey:(__bridge id)kSecAttrAccount]; -#if TARGET_OS_IPHONE || (defined(MAC_OS_X_VERSION_10_9) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9) - [attributes setObject:(__bridge id)kSecAttrAccessibleAfterFirstUnlock forKey:(__bridge id)kSecAttrAccessible]; -#endif - [attributes setObject:data forKey:(__bridge id)kSecValueData]; -#if !TARGET_IPHONE_SIMULATOR && defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - if (accessGroup) { - [attributes setObject:accessGroup forKey:(__bridge id)kSecAttrAccessGroup]; - } -#endif - - status = SecItemAdd((__bridge CFDictionaryRef)attributes, NULL); - if (status != errSecSuccess) { - return NO; - } - } else { - return NO; - } - - return YES; -} - -#pragma mark - - -- (void)setString:(NSString *)string forKey:(NSString *)key -{ - [self setData:[string dataUsingEncoding:NSUTF8StringEncoding] forKey:key]; -} - -- (NSString *)stringForKey:(id)key -{ - NSData *data = [self dataForKey:key]; - if (data) { - return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - } - - return nil; -} - -#pragma mark - - -- (void)setData:(NSData *)data forKey:(NSString *)key -{ - if (!key) { - return; - } - if (!data) { - [self removeItemForKey:key]; - } else { - [itemsToUpdate setObject:data forKey:key]; - } -} - -- (NSData *)dataForKey:(NSString *)key -{ - NSData *data = [itemsToUpdate objectForKey:key]; - if (!data) { - data = [[self class] dataForKey:key service:self.service accessGroup:self.accessGroup]; - } - - return data; -} - -#pragma mark - - -+ (BOOL)removeItemForKey:(NSString *)key -{ - return [UICKeyChainStore removeItemForKey:key service:[self defaultService] accessGroup:nil]; -} - -+ (BOOL)removeItemForKey:(NSString *)key service:(NSString *)service -{ - return [UICKeyChainStore removeItemForKey:key service:service accessGroup:nil]; -} - -+ (BOOL)removeItemForKey:(NSString *)key service:(NSString *)service accessGroup:(NSString *)accessGroup -{ - if (!key) { - return NO; - } - if (!service) { - service = [self defaultService]; - } - - NSMutableDictionary *itemToDelete = [[NSMutableDictionary alloc] init]; - [itemToDelete setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass]; - [itemToDelete setObject:service forKey:(__bridge id)kSecAttrService]; - [itemToDelete setObject:key forKey:(__bridge id)kSecAttrGeneric]; - [itemToDelete setObject:key forKey:(__bridge id)kSecAttrAccount]; -#if !TARGET_IPHONE_SIMULATOR && defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - if (accessGroup) { - [itemToDelete setObject:accessGroup forKey:(__bridge id)kSecAttrAccessGroup]; - } -#endif - - OSStatus status = SecItemDelete((__bridge CFDictionaryRef)itemToDelete); - if (status != errSecSuccess && status != errSecItemNotFound) { - return NO; - } - - return YES; -} - -+ (NSArray *)itemsForService:(NSString *)service accessGroup:(NSString *)accessGroup -{ - if (!service) { - service = [self defaultService]; - } - - NSMutableDictionary *query = [[NSMutableDictionary alloc] init]; - [query setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass]; - [query setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnAttributes]; - [query setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData]; - [query setObject:(__bridge id)kSecMatchLimitAll forKey:(__bridge id)kSecMatchLimit]; - [query setObject:service forKey:(__bridge id)kSecAttrService]; -#if !TARGET_IPHONE_SIMULATOR && defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - if (accessGroup) { - [query setObject:accessGroup forKey:(__bridge id)kSecAttrAccessGroup]; - } -#endif - - CFArrayRef result = nil; - OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef *)&result); - if (status == errSecSuccess || status == errSecItemNotFound) { - return CFBridgingRelease(result); - } else { - return nil; - } -} - -+ (BOOL)removeAllItems -{ - return [self removeAllItemsForService:[self defaultService] accessGroup:nil]; -} - -+ (BOOL)removeAllItemsForService:(NSString *)service -{ - return [self removeAllItemsForService:service accessGroup:nil]; -} - -+ (BOOL)removeAllItemsForService:(NSString *)service accessGroup:(NSString *)accessGroup -{ - NSArray *items = [UICKeyChainStore itemsForService:service accessGroup:accessGroup]; - for (NSDictionary *item in items) { - NSMutableDictionary *itemToDelete = [[NSMutableDictionary alloc] initWithDictionary:item]; - [itemToDelete setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass]; - - OSStatus status = SecItemDelete((__bridge CFDictionaryRef)itemToDelete); - if (status != errSecSuccess) { - return NO; - } - } - - return YES; -} - -#pragma mark - - -- (void)removeItemForKey:(NSString *)key -{ - if ([itemsToUpdate objectForKey:key]) { - [itemsToUpdate removeObjectForKey:key]; - } else { - [[self class] removeItemForKey:key service:self.service accessGroup:self.accessGroup]; - } -} - -- (void)removeAllItems -{ - [itemsToUpdate removeAllObjects]; - [[self class] removeAllItemsForService:self.service accessGroup:self.accessGroup]; -} - -#pragma mark - - -- (void)synchronize -{ - for (NSString *key in itemsToUpdate) { - [[self class] setData:[itemsToUpdate objectForKey:key] forKey:key service:self.service accessGroup:self.accessGroup]; - } - - [itemsToUpdate removeAllObjects]; -} - -#pragma mark - - -- (NSString *)description -{ - NSArray *items = [UICKeyChainStore itemsForService:self.service accessGroup:self.accessGroup]; - NSMutableArray *list = [[NSMutableArray alloc] initWithCapacity:items.count]; - for (NSDictionary *attributes in items) { - NSMutableDictionary *attrs = [[NSMutableDictionary alloc] init]; - [attrs setObject:[attributes objectForKey:(__bridge id)kSecAttrService] forKey:@"Service"]; - [attrs setObject:[attributes objectForKey:(__bridge id)kSecAttrAccount] forKey:@"Account"]; -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - [attrs setObject:[attributes objectForKey:(__bridge id)kSecAttrAccessGroup] forKey:@"AccessGroup"]; -#endif - NSData *data = [attributes objectForKey:(__bridge id)kSecValueData]; - NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - if (string) { - [attrs setObject:string forKey:@"Value"]; - } else { - [attrs setObject:data forKey:@"Value"]; - } - [list addObject:attrs]; - } - - return [list description]; -} - -@end diff --git a/Examples/Demo.xcodeproj/project.pbxproj b/Examples/Demo.xcodeproj/project.pbxproj new file mode 100644 index 0000000..bd23e04 --- /dev/null +++ b/Examples/Demo.xcodeproj/project.pbxproj @@ -0,0 +1,541 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 183FDA881E7510F10085589F /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 183FDA871E7510F10085589F /* AppDelegate.swift */; }; + 183FDA8A1E7510F10085589F /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 183FDA891E7510F10085589F /* ViewController.swift */; }; + 183FDA8D1E7510F10085589F /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 183FDA8B1E7510F10085589F /* Main.storyboard */; }; + 183FDA8F1E7510F10085589F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 183FDA8E1E7510F10085589F /* Assets.xcassets */; }; + 183FDA921E7510F10085589F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 183FDA901E7510F10085589F /* LaunchScreen.storyboard */; }; + 183FDA9D1E7510F10085589F /* DemoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 183FDA9C1E7510F10085589F /* DemoTests.swift */; }; + 6538472825F35D6300A6D7D9 /* StudyplusSDK.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 658C822725F21569002291FE /* StudyplusSDK.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 183FDA991E7510F10085589F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 183FDA5E1E7510920085589F /* Project object */; + proxyType = 1; + remoteGlobalIDString = 183FDA841E7510F00085589F; + remoteInfo = Demo; + }; + 658C822625F21569002291FE /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 658C822125F21569002291FE /* StudyplusSDK.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 183FDA671E7510920085589F; + remoteInfo = StudyplusSDK; + }; + 658C822825F21569002291FE /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 658C822125F21569002291FE /* StudyplusSDK.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 183FDA701E7510920085589F; + remoteInfo = StudyplusSDKTests; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 6538472925F35D6300A6D7D9 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + 6538472825F35D6300A6D7D9 /* StudyplusSDK.framework in Embed Frameworks */, + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 183FDA851E7510F00085589F /* Demo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Demo.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 183FDA871E7510F10085589F /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 183FDA891E7510F10085589F /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; + 183FDA8C1E7510F10085589F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 183FDA8E1E7510F10085589F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 183FDA911E7510F10085589F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 183FDA931E7510F10085589F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 183FDA981E7510F10085589F /* DemoTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = DemoTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 183FDA9C1E7510F10085589F /* DemoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoTests.swift; sourceTree = ""; }; + 183FDA9E1E7510F10085589F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 658C822125F21569002291FE /* StudyplusSDK.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = StudyplusSDK.xcodeproj; path = ../Lib/StudyplusSDK.xcodeproj; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 183FDA821E7510F00085589F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 183FDA951E7510F10085589F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 183FDA5D1E7510920085589F = { + isa = PBXGroup; + children = ( + 183FDA861E7510F10085589F /* Demo */, + 183FDA9B1E7510F10085589F /* DemoTests */, + 183FDA681E7510920085589F /* Products */, + 65AEE18725F2126A00821E1E /* Frameworks */, + ); + sourceTree = ""; + }; + 183FDA681E7510920085589F /* Products */ = { + isa = PBXGroup; + children = ( + 183FDA851E7510F00085589F /* Demo.app */, + 183FDA981E7510F10085589F /* DemoTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 183FDA861E7510F10085589F /* Demo */ = { + isa = PBXGroup; + children = ( + 183FDA871E7510F10085589F /* AppDelegate.swift */, + 183FDA891E7510F10085589F /* ViewController.swift */, + 183FDA8B1E7510F10085589F /* Main.storyboard */, + 183FDA8E1E7510F10085589F /* Assets.xcassets */, + 183FDA901E7510F10085589F /* LaunchScreen.storyboard */, + 183FDA931E7510F10085589F /* Info.plist */, + ); + path = Demo; + sourceTree = ""; + }; + 183FDA9B1E7510F10085589F /* DemoTests */ = { + isa = PBXGroup; + children = ( + 183FDA9C1E7510F10085589F /* DemoTests.swift */, + 183FDA9E1E7510F10085589F /* Info.plist */, + ); + path = DemoTests; + sourceTree = ""; + }; + 658C822225F21569002291FE /* Products */ = { + isa = PBXGroup; + children = ( + 658C822725F21569002291FE /* StudyplusSDK.framework */, + 658C822925F21569002291FE /* StudyplusSDKTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 65AEE18725F2126A00821E1E /* Frameworks */ = { + isa = PBXGroup; + children = ( + 658C822125F21569002291FE /* StudyplusSDK.xcodeproj */, + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 183FDA841E7510F00085589F /* Demo */ = { + isa = PBXNativeTarget; + buildConfigurationList = 183FDA9F1E7510F10085589F /* Build configuration list for PBXNativeTarget "Demo" */; + buildPhases = ( + 183FDA811E7510F00085589F /* Sources */, + 183FDA821E7510F00085589F /* Frameworks */, + 183FDA831E7510F00085589F /* Resources */, + 6538472925F35D6300A6D7D9 /* Embed Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Demo; + packageProductDependencies = ( + ); + productName = Demo; + productReference = 183FDA851E7510F00085589F /* Demo.app */; + productType = "com.apple.product-type.application"; + }; + 183FDA971E7510F10085589F /* DemoTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 183FDAA21E7510F10085589F /* Build configuration list for PBXNativeTarget "DemoTests" */; + buildPhases = ( + 183FDA941E7510F10085589F /* Sources */, + 183FDA951E7510F10085589F /* Frameworks */, + 183FDA961E7510F10085589F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 183FDA9A1E7510F10085589F /* PBXTargetDependency */, + ); + name = DemoTests; + productName = DemoTests; + productReference = 183FDA981E7510F10085589F /* DemoTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 183FDA5E1E7510920085589F /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0820; + LastUpgradeCheck = 1240; + ORGANIZATIONNAME = studyplus; + TargetAttributes = { + 183FDA841E7510F00085589F = { + CreatedOnToolsVersion = 8.2.1; + LastSwiftMigration = 1020; + ProvisioningStyle = Automatic; + }; + 183FDA971E7510F10085589F = { + CreatedOnToolsVersion = 8.2.1; + LastSwiftMigration = 1020; + ProvisioningStyle = Automatic; + TestTargetID = 183FDA841E7510F00085589F; + }; + }; + }; + buildConfigurationList = 183FDA611E7510920085589F /* Build configuration list for PBXProject "Demo" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 183FDA5D1E7510920085589F; + packageReferences = ( + ); + productRefGroup = 183FDA681E7510920085589F /* Products */; + projectDirPath = ""; + projectReferences = ( + { + ProductGroup = 658C822225F21569002291FE /* Products */; + ProjectRef = 658C822125F21569002291FE /* StudyplusSDK.xcodeproj */; + }, + ); + projectRoot = ""; + targets = ( + 183FDA841E7510F00085589F /* Demo */, + 183FDA971E7510F10085589F /* DemoTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXReferenceProxy section */ + 658C822725F21569002291FE /* StudyplusSDK.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = StudyplusSDK.framework; + remoteRef = 658C822625F21569002291FE /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 658C822925F21569002291FE /* StudyplusSDKTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = StudyplusSDKTests.xctest; + remoteRef = 658C822825F21569002291FE /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; +/* End PBXReferenceProxy section */ + +/* Begin PBXResourcesBuildPhase section */ + 183FDA831E7510F00085589F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 183FDA921E7510F10085589F /* LaunchScreen.storyboard in Resources */, + 183FDA8F1E7510F10085589F /* Assets.xcassets in Resources */, + 183FDA8D1E7510F10085589F /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 183FDA961E7510F10085589F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 183FDA811E7510F00085589F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 183FDA8A1E7510F10085589F /* ViewController.swift in Sources */, + 183FDA881E7510F10085589F /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 183FDA941E7510F10085589F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 183FDA9D1E7510F10085589F /* DemoTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 183FDA9A1E7510F10085589F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 183FDA841E7510F00085589F /* Demo */; + targetProxy = 183FDA991E7510F10085589F /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 183FDA8B1E7510F10085589F /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 183FDA8C1E7510F10085589F /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 183FDA901E7510F10085589F /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 183FDA911E7510F10085589F /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 183FDA791E7510920085589F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = "$(inherited)"; + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + OTHER_SWIFT_FLAGS = "-D DEBUG"; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_SWIFT3_OBJC_INFERENCE = Default; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 183FDA7A1E7510920085589F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = "$(inherited)"; + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_SWIFT_FLAGS = "-D RELEASE"; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_SWIFT3_OBJC_INFERENCE = Default; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 183FDAA01E7510F10085589F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + DEVELOPMENT_TEAM = ""; + INFOPLIST_FILE = Demo/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + MARKETING_VERSION = 3.0.0; + OTHER_SWIFT_FLAGS = "$(inherited)"; + PRODUCT_BUNDLE_IDENTIFIER = com.studyplus.Demo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 183FDAA11E7510F10085589F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + DEVELOPMENT_TEAM = ""; + INFOPLIST_FILE = Demo/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + MARKETING_VERSION = 3.0.0; + OTHER_SWIFT_FLAGS = "$(inherited)"; + PRODUCT_BUNDLE_IDENTIFIER = com.studyplus.Demo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 183FDAA31E7510F10085589F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = "$(inherited)"; + BUNDLE_LOADER = "$(TEST_HOST)"; + INFOPLIST_FILE = DemoTests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.studyplus.DemoTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Demo.app/Demo"; + }; + name = Debug; + }; + 183FDAA41E7510F10085589F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = "$(inherited)"; + BUNDLE_LOADER = "$(TEST_HOST)"; + INFOPLIST_FILE = DemoTests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.studyplus.DemoTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Demo.app/Demo"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 183FDA611E7510920085589F /* Build configuration list for PBXProject "Demo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 183FDA791E7510920085589F /* Debug */, + 183FDA7A1E7510920085589F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 183FDA9F1E7510F10085589F /* Build configuration list for PBXNativeTarget "Demo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 183FDAA01E7510F10085589F /* Debug */, + 183FDAA11E7510F10085589F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 183FDAA21E7510F10085589F /* Build configuration list for PBXNativeTarget "DemoTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 183FDAA31E7510F10085589F /* Debug */, + 183FDAA41E7510F10085589F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 183FDA5E1E7510920085589F /* Project object */; +} diff --git a/StudyplusSDK.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Examples/Demo.xcodeproj/project.xcworkspace/contents.xcworkspacedata similarity index 69% rename from StudyplusSDK.xcodeproj/project.xcworkspace/contents.xcworkspacedata rename to Examples/Demo.xcodeproj/project.xcworkspace/contents.xcworkspacedata index 3495778..919434a 100644 --- a/StudyplusSDK.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ b/Examples/Demo.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -2,6 +2,6 @@ + location = "self:"> diff --git a/Examples/Demo.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Examples/Demo.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/Examples/Demo.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Examples/Demo.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/Examples/Demo.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..0c67376 --- /dev/null +++ b/Examples/Demo.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,5 @@ + + + + + diff --git a/Examples/Demo.xcodeproj/xcshareddata/xcschemes/Demo.xcscheme b/Examples/Demo.xcodeproj/xcshareddata/xcschemes/Demo.xcscheme new file mode 100644 index 0000000..c044231 --- /dev/null +++ b/Examples/Demo.xcodeproj/xcshareddata/xcschemes/Demo.xcscheme @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStopwatch.h b/Examples/Demo/AppDelegate.swift similarity index 51% rename from Demo/StudyplusSDKDemo/StudyplusSDK/SPLStopwatch.h rename to Examples/Demo/AppDelegate.swift index c1e82ca..9e07e8c 100644 --- a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStopwatch.h +++ b/Examples/Demo/AppDelegate.swift @@ -1,6 +1,10 @@ +// +// AppDelegate.swift +// Demo +// // The MIT License (MIT) // -// Copyright (c) 2014 Studyplus inc. +// Copyright (c) 2017 Studyplus inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -20,36 +24,38 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#import - -/** - Simple stopwatch with [start/stop/reset] functions. Useful for measuring the learning duration.
- シンプルなストップウォッチです。学習時間(duration)を計測するのに便利です。 - */ -@interface SPLStopwatch : NSObject - -/** - Begin or resume measuring.
- 測定を開始または再開します。 - */ --(void)start; - -/** - Pause measuring. Elapsed seconds will not be reset.
- 測定を一時停止します。経過秒数はリセットされません。 - */ --(void)pause; - -/** - Reset elapsed seconds. Elapsed seconds will be 0, and measuring will not stop.
- 経過秒数を0にリセットします。測定中の場合、測定は止まりません。 - */ --(void)reset; - -/** - Returns total elapsed seconds.
- 現時点の累計経過秒数を返します。 - */ --(NSUInteger)elapsedSeconds; - -@end +import UIKit +import StudyplusSDK + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + func application(_ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + return true + } + + func applicationWillResignActive(_ application: UIApplication) { + } + + func applicationDidEnterBackground(_ application: UIApplication) { + } + + func applicationWillEnterForeground(_ application: UIApplication) { + } + + func applicationDidBecomeActive(_ application: UIApplication) { + } + + func applicationWillTerminate(_ application: UIApplication) { + } + + func application(_ app: UIApplication, + open url: URL, + options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { + print("-- called application(_:open:options:) --") + return Studyplus.shared.handle(url) + } +} diff --git a/Examples/Demo/Assets.xcassets/AppIcon.appiconset/Contents.json b/Examples/Demo/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d8db8d6 --- /dev/null +++ b/Examples/Demo/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,98 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "3x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "83.5x83.5", + "scale" : "2x" + }, + { + "idiom" : "ios-marketing", + "size" : "1024x1024", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Examples/Demo/Base.lproj/LaunchScreen.storyboard b/Examples/Demo/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..fdf3f97 --- /dev/null +++ b/Examples/Demo/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Examples/Demo/Base.lproj/Main.storyboard b/Examples/Demo/Base.lproj/Main.storyboard new file mode 100644 index 0000000..12181a7 --- /dev/null +++ b/Examples/Demo/Base.lproj/Main.storyboard @@ -0,0 +1,161 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/StudyplusSDKDemo-Info.plist b/Examples/Demo/Info.plist similarity index 62% rename from Demo/StudyplusSDKDemo/StudyplusSDKDemo/StudyplusSDKDemo-Info.plist rename to Examples/Demo/Info.plist index b93d979..1f367c7 100644 --- a/Demo/StudyplusSDKDemo/StudyplusSDKDemo/StudyplusSDKDemo-Info.plist +++ b/Examples/Demo/Info.plist @@ -4,22 +4,18 @@ CFBundleDevelopmentRegion en - CFBundleDisplayName - ${PRODUCT_NAME} CFBundleExecutable - ${EXECUTABLE_NAME} + $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName - ${PRODUCT_NAME} + $(PRODUCT_NAME) CFBundlePackageType APPL CFBundleShortVersionString - 1.0 - CFBundleSignature - ???? + $(MARKETING_VERSION) CFBundleURLTypes @@ -34,9 +30,22 @@ CFBundleVersion - 1.0 + 1 + LSApplicationQueriesSchemes + + studyplus + LSRequiresIPhoneOS + StudyplusSDK + + consumerKey + set_your_consumerKey + consumerSecret + set_your_consumerSecret + + UILaunchStoryboardName + LaunchScreen UIMainStoryboardFile Main UIRequiredDeviceCapabilities @@ -49,5 +58,12 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + diff --git a/Examples/Demo/ViewController.swift b/Examples/Demo/ViewController.swift new file mode 100644 index 0000000..a81b8bf --- /dev/null +++ b/Examples/Demo/ViewController.swift @@ -0,0 +1,97 @@ +// +// ViewController.swift +// Demo +// +// The MIT License (MIT) +// +// Copyright (c) 2021 Studyplus inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import UIKit +import StudyplusSDK + +class ViewController: UIViewController { + + @IBOutlet weak var isConnectedLabel: UILabel! + @IBOutlet weak var resultLabel: UILabel! + + var duration: TimeInterval = TimeInterval(60) + + override func viewDidLoad() { + super.viewDidLoad() + Studyplus.shared.delegate = self + } + + @IBAction func loginButton(_ sender: UIButton) { + Studyplus.shared.login() + } + + @IBAction func logoutButton(_ sender: UIButton) { + Studyplus.shared.logout() + updateIsConnected() + resultLabel.text = "Logout" + } + + @IBAction func connectedButton(_ sender: UIButton) { + updateIsConnected() + resultLabel.text = "" + } + + @IBAction func postStudyRecordButton(_ sender: UIButton) { + + self.resultLabel.text = "" + + let record = StudyplusRecord(duration: Int(duration), + amount: 10, + comment: "Today, I studied like anything.", + recordDatetime: Date()) + + Studyplus.shared.post(record, completion: { result in + switch result { + case .failure(let error): + self.resultLabel.text = "Error Code: \(error)" + case .success: + self.resultLabel.text = "Success to post your studyRecord to Studyplus App" + } + }) + } + + @IBAction func studyRecordDurationPicker(_ sender: UIDatePicker) { + duration = sender.countDownDuration + } + + private func updateIsConnected() { + isConnectedLabel.text = Studyplus.shared.isConnected() ? "True" : "False" + } +} + +extension ViewController: StudyplusLoginDelegate { + func studyplusLoginSuccess() { + print("-- Called studyplusDidSuccessToLogin --") + resultLabel.text = "Login succeeded" + updateIsConnected() + } + + func studyplusLoginFail(error: StudyplusLoginError) { + print("-- Called studyplusDidFailToLogin --") + resultLabel.text = "Error Code: \(error)" + updateIsConnected() + } +} diff --git a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusAPIRequest.h b/Examples/DemoTests/DemoTests.swift similarity index 56% rename from Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusAPIRequest.h rename to Examples/DemoTests/DemoTests.swift index 5b8990d..012db27 100644 --- a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusAPIRequest.h +++ b/Examples/DemoTests/DemoTests.swift @@ -1,6 +1,10 @@ +// +// DemoTests.swift +// DemoTests +// // The MIT License (MIT) // -// Copyright (c) 2014 Studyplus inc. +// Copyright (c) 2017 Studyplus inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -20,20 +24,31 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#import +import XCTest +@testable import Demo -NS_ASSUME_NONNULL_BEGIN +class DemoTests: XCTestCase { -@interface SPLStudyplusAPIRequest : NSObject + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } -+ (instancetype)newRequestWithAccessToken:(NSString*)accessToken - options:(NSDictionary*)options; + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } -- (void)postRequestWithPath:(NSString *)path - requestParameter:(NSDictionary *)requestParameter - completed:(void(^)(NSDictionary * _Nullable response))completed - failed:(void(^)(NSError *error))failed; + func testExample() { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. + } -NS_ASSUME_NONNULL_END + func testPerformanceExample() { + // This is an example of a performance test case. + self.measure { + // Put the code you want to measure the time of here. + } + } -@end +} diff --git a/Demo/StudyplusSDKDemo/StudyplusSDKDemoTests/StudyplusSDKDemoTests-Info.plist b/Examples/DemoTests/Info.plist similarity index 85% rename from Demo/StudyplusSDKDemo/StudyplusSDKDemoTests/StudyplusSDKDemoTests-Info.plist rename to Examples/DemoTests/Info.plist index 169b6f7..6c6c23c 100644 --- a/Demo/StudyplusSDKDemo/StudyplusSDKDemoTests/StudyplusSDKDemoTests-Info.plist +++ b/Examples/DemoTests/Info.plist @@ -5,17 +5,17 @@ CFBundleDevelopmentRegion en CFBundleExecutable - ${EXECUTABLE_NAME} + $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 + CFBundleName + $(PRODUCT_NAME) CFBundlePackageType BNDL CFBundleShortVersionString 1.0 - CFBundleSignature - ???? CFBundleVersion 1 diff --git a/build/Debug/deliverables/StudyplusSDK/LICENSE.txt b/LICENSE similarity index 96% rename from build/Debug/deliverables/StudyplusSDK/LICENSE.txt rename to LICENSE index 33afa03..7afdfeb 100644 --- a/build/Debug/deliverables/StudyplusSDK/LICENSE.txt +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2014 Studyplus inc. +Copyright (c) 2021 Studyplus inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -19,3 +19,4 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/LICENSE.txt b/LICENSE.txt deleted file mode 100644 index 33afa03..0000000 --- a/LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Studyplus inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/Lib/StudyplusSDK.xcodeproj/project.pbxproj b/Lib/StudyplusSDK.xcodeproj/project.pbxproj new file mode 100644 index 0000000..3dfaa30 --- /dev/null +++ b/Lib/StudyplusSDK.xcodeproj/project.pbxproj @@ -0,0 +1,492 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 183FDA711E7510920085589F /* StudyplusSDK.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 183FDA671E7510920085589F /* StudyplusSDK.framework */; }; + 183FDA761E7510920085589F /* StudyplusSDKTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 183FDA751E7510920085589F /* StudyplusSDKTests.swift */; }; + 183FDA781E7510920085589F /* StudyplusSDK.h in Headers */ = {isa = PBXBuildFile; fileRef = 183FDA6A1E7510920085589F /* StudyplusSDK.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 183FDAAB1E75148D0085589F /* Studyplus.swift in Sources */ = {isa = PBXBuildFile; fileRef = 183FDAAA1E75148D0085589F /* Studyplus.swift */; }; + 183FDAAD1E753E430085589F /* StudyplusLoginDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 183FDAAC1E753E430085589F /* StudyplusLoginDelegate.swift */; }; + 183FDAAF1E7544240085589F /* StudyplusError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 183FDAAE1E7544240085589F /* StudyplusError.swift */; }; + 183FDAB11E754DCB0085589F /* StudyplusAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 183FDAB01E754DCB0085589F /* StudyplusAPI.swift */; }; + 183FDAB31E7561B90085589F /* StudyplusRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 183FDAB21E7561B90085589F /* StudyplusRecord.swift */; }; + 65E3912925F8A74E00490547 /* StudyplusKeychain.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65E3912825F8A74E00490547 /* StudyplusKeychain.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 183FDA721E7510920085589F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 183FDA5E1E7510920085589F /* Project object */; + proxyType = 1; + remoteGlobalIDString = 183FDA661E7510920085589F; + remoteInfo = StudyplusSDK; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 183FDA671E7510920085589F /* StudyplusSDK.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = StudyplusSDK.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 183FDA6A1E7510920085589F /* StudyplusSDK.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = StudyplusSDK.h; sourceTree = ""; }; + 183FDA6B1E7510920085589F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 183FDA701E7510920085589F /* StudyplusSDKTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = StudyplusSDKTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 183FDA751E7510920085589F /* StudyplusSDKTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StudyplusSDKTests.swift; sourceTree = ""; }; + 183FDA771E7510920085589F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 183FDAAA1E75148D0085589F /* Studyplus.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Studyplus.swift; sourceTree = ""; }; + 183FDAAC1E753E430085589F /* StudyplusLoginDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StudyplusLoginDelegate.swift; sourceTree = ""; }; + 183FDAAE1E7544240085589F /* StudyplusError.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StudyplusError.swift; sourceTree = ""; }; + 183FDAB01E754DCB0085589F /* StudyplusAPI.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StudyplusAPI.swift; sourceTree = ""; }; + 183FDAB21E7561B90085589F /* StudyplusRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StudyplusRecord.swift; sourceTree = ""; }; + 65E3912825F8A74E00490547 /* StudyplusKeychain.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StudyplusKeychain.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 183FDA631E7510920085589F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 183FDA6D1E7510920085589F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 183FDA711E7510920085589F /* StudyplusSDK.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 183FDA5D1E7510920085589F = { + isa = PBXGroup; + children = ( + 183FDA691E7510920085589F /* StudyplusSDK */, + 183FDA741E7510920085589F /* StudyplusSDKTests */, + 183FDA681E7510920085589F /* Products */, + ); + sourceTree = ""; + }; + 183FDA681E7510920085589F /* Products */ = { + isa = PBXGroup; + children = ( + 183FDA671E7510920085589F /* StudyplusSDK.framework */, + 183FDA701E7510920085589F /* StudyplusSDKTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 183FDA691E7510920085589F /* StudyplusSDK */ = { + isa = PBXGroup; + children = ( + 183FDA6B1E7510920085589F /* Info.plist */, + 65E3911625F889A700490547 /* internal */, + 183FDAAA1E75148D0085589F /* Studyplus.swift */, + 183FDAAE1E7544240085589F /* StudyplusError.swift */, + 183FDAAC1E753E430085589F /* StudyplusLoginDelegate.swift */, + 183FDAB21E7561B90085589F /* StudyplusRecord.swift */, + 183FDA6A1E7510920085589F /* StudyplusSDK.h */, + ); + path = StudyplusSDK; + sourceTree = ""; + }; + 183FDA741E7510920085589F /* StudyplusSDKTests */ = { + isa = PBXGroup; + children = ( + 183FDA751E7510920085589F /* StudyplusSDKTests.swift */, + 183FDA771E7510920085589F /* Info.plist */, + ); + path = StudyplusSDKTests; + sourceTree = ""; + }; + 65E3911625F889A700490547 /* internal */ = { + isa = PBXGroup; + children = ( + 183FDAB01E754DCB0085589F /* StudyplusAPI.swift */, + 65E3912825F8A74E00490547 /* StudyplusKeychain.swift */, + ); + path = internal; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 183FDA641E7510920085589F /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 183FDA781E7510920085589F /* StudyplusSDK.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 183FDA661E7510920085589F /* StudyplusSDK */ = { + isa = PBXNativeTarget; + buildConfigurationList = 183FDA7B1E7510920085589F /* Build configuration list for PBXNativeTarget "StudyplusSDK" */; + buildPhases = ( + 183FDA621E7510920085589F /* Sources */, + 183FDA631E7510920085589F /* Frameworks */, + 183FDA641E7510920085589F /* Headers */, + 183FDA651E7510920085589F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = StudyplusSDK; + packageProductDependencies = ( + ); + productName = StudyplusSDK; + productReference = 183FDA671E7510920085589F /* StudyplusSDK.framework */; + productType = "com.apple.product-type.framework"; + }; + 183FDA6F1E7510920085589F /* StudyplusSDKTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 183FDA7E1E7510920085589F /* Build configuration list for PBXNativeTarget "StudyplusSDKTests" */; + buildPhases = ( + 183FDA6C1E7510920085589F /* Sources */, + 183FDA6D1E7510920085589F /* Frameworks */, + 183FDA6E1E7510920085589F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 183FDA731E7510920085589F /* PBXTargetDependency */, + ); + name = StudyplusSDKTests; + productName = StudyplusSDKTests; + productReference = 183FDA701E7510920085589F /* StudyplusSDKTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 183FDA5E1E7510920085589F /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0820; + LastUpgradeCheck = 1240; + ORGANIZATIONNAME = studyplus; + TargetAttributes = { + 183FDA661E7510920085589F = { + CreatedOnToolsVersion = 8.2.1; + LastSwiftMigration = 1020; + ProvisioningStyle = Automatic; + }; + 183FDA6F1E7510920085589F = { + CreatedOnToolsVersion = 8.2.1; + LastSwiftMigration = 1020; + ProvisioningStyle = Automatic; + }; + }; + }; + buildConfigurationList = 183FDA611E7510920085589F /* Build configuration list for PBXProject "StudyplusSDK" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 183FDA5D1E7510920085589F; + packageReferences = ( + ); + productRefGroup = 183FDA681E7510920085589F /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 183FDA661E7510920085589F /* StudyplusSDK */, + 183FDA6F1E7510920085589F /* StudyplusSDKTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 183FDA651E7510920085589F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 183FDA6E1E7510920085589F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 183FDA621E7510920085589F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 183FDAB11E754DCB0085589F /* StudyplusAPI.swift in Sources */, + 183FDAB31E7561B90085589F /* StudyplusRecord.swift in Sources */, + 183FDAAD1E753E430085589F /* StudyplusLoginDelegate.swift in Sources */, + 65E3912925F8A74E00490547 /* StudyplusKeychain.swift in Sources */, + 183FDAAF1E7544240085589F /* StudyplusError.swift in Sources */, + 183FDAAB1E75148D0085589F /* Studyplus.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 183FDA6C1E7510920085589F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 183FDA761E7510920085589F /* StudyplusSDKTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 183FDA731E7510920085589F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 183FDA661E7510920085589F /* StudyplusSDK */; + targetProxy = 183FDA721E7510920085589F /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 183FDA791E7510920085589F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = "$(inherited)"; + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + OTHER_SWIFT_FLAGS = "-D DEBUG"; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_SWIFT3_OBJC_INFERENCE = Default; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 183FDA7A1E7510920085589F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = "$(inherited)"; + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_SWIFT_FLAGS = "-D RELEASE"; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_SWIFT3_OBJC_INFERENCE = Default; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 183FDA7C1E7510920085589F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = "$(inherited)"; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + FRAMEWORK_SEARCH_PATHS = "$(inherited)"; + INFOPLIST_FILE = StudyplusSDK/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MARKETING_VERSION = 3.0.0; + OTHER_SWIFT_FLAGS = "$(inherited)"; + PRODUCT_BUNDLE_IDENTIFIER = com.studyplus.StudyplusSDK; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 183FDA7D1E7510920085589F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = "$(inherited)"; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_IDENTITY = ""; + DEFINES_MODULE = YES; + DEVELOPMENT_TEAM = ""; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + FRAMEWORK_SEARCH_PATHS = "$(inherited)"; + INFOPLIST_FILE = StudyplusSDK/Info.plist; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MARKETING_VERSION = 3.0.0; + OTHER_SWIFT_FLAGS = "$(inherited)"; + PRODUCT_BUNDLE_IDENTIFIER = com.studyplus.StudyplusSDK; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 183FDA7F1E7510920085589F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + INFOPLIST_FILE = StudyplusSDKTests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.studyplus.StudyplusSDKTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 183FDA801E7510920085589F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + INFOPLIST_FILE = StudyplusSDKTests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.studyplus.StudyplusSDKTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 183FDA611E7510920085589F /* Build configuration list for PBXProject "StudyplusSDK" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 183FDA791E7510920085589F /* Debug */, + 183FDA7A1E7510920085589F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 183FDA7B1E7510920085589F /* Build configuration list for PBXNativeTarget "StudyplusSDK" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 183FDA7C1E7510920085589F /* Debug */, + 183FDA7D1E7510920085589F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 183FDA7E1E7510920085589F /* Build configuration list for PBXNativeTarget "StudyplusSDKTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 183FDA7F1E7510920085589F /* Debug */, + 183FDA801E7510920085589F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 183FDA5E1E7510920085589F /* Project object */; +} diff --git a/Demo/StudyplusSDKDemo/StudyplusSDKDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Lib/StudyplusSDK.xcodeproj/project.xcworkspace/contents.xcworkspacedata similarity index 67% rename from Demo/StudyplusSDKDemo/StudyplusSDKDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata rename to Lib/StudyplusSDK.xcodeproj/project.xcworkspace/contents.xcworkspacedata index 0adcc6e..919434a 100644 --- a/Demo/StudyplusSDKDemo/StudyplusSDKDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ b/Lib/StudyplusSDK.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -2,6 +2,6 @@ + location = "self:"> diff --git a/Lib/StudyplusSDK.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Lib/StudyplusSDK.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/Lib/StudyplusSDK.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Lib/StudyplusSDK.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/Lib/StudyplusSDK.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..0c67376 --- /dev/null +++ b/Lib/StudyplusSDK.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,5 @@ + + + + + diff --git a/Lib/StudyplusSDK.xcodeproj/xcshareddata/xcschemes/StudyplusSDK.xcscheme b/Lib/StudyplusSDK.xcodeproj/xcshareddata/xcschemes/StudyplusSDK.xcscheme new file mode 100644 index 0000000..f0efcef --- /dev/null +++ b/Lib/StudyplusSDK.xcodeproj/xcshareddata/xcschemes/StudyplusSDK.xcscheme @@ -0,0 +1,95 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Lib/StudyplusSDK/Info.plist b/Lib/StudyplusSDK/Info.plist new file mode 100644 index 0000000..ec0cc7b --- /dev/null +++ b/Lib/StudyplusSDK/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + FMWK + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSPrincipalClass + + + diff --git a/Lib/StudyplusSDK/Studyplus.swift b/Lib/StudyplusSDK/Studyplus.swift new file mode 100644 index 0000000..4092c29 --- /dev/null +++ b/Lib/StudyplusSDK/Studyplus.swift @@ -0,0 +1,197 @@ +// +// Studyplus.swift +// StudyplusSDK +// +// The MIT License (MIT) +// +// Copyright (c) 2021 Studyplus inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import UIKit + +final public class Studyplus { + + private init() { + guard let data = Bundle.main.infoDictionary?["StudyplusSDK"] as? [String: String], + let consumerKey = data["consumerKey"], + let consumerSecret = data["consumerSecret"] else { + assert(false, "StudyplusSDK: *** Please set consumerKey and consumerSecret in your Info.plist. ***") + + self.consumerKey = "" + self.consumerSecret = "" + return + } + + if consumerKey == "set_your_consumerKey" || consumerSecret == "set_your_consumerSecret" { + assert(false, "StudyplusSDK: *** Please set consumerKey and consumerSecret in Info.plist. ***") + + self.consumerKey = "" + self.consumerSecret = "" + return + } + + self.consumerKey = consumerKey + self.consumerSecret = consumerSecret + } + + public static let shared: Studyplus = Studyplus() + + public private(set) var consumerKey: String + public private(set) var consumerSecret: String + public weak var delegate: StudyplusLoginDelegate? + + private var serviceName: String { + return "Studyplus_iOS_SDK_\(consumerKey)" + } + + /// Studyplusアプリを経由して、Studyplusアカウントにログインします。 + /// Studyplusアプリがインストールされていない場合、AppStoreへ遷移します。 + /// ログイン処理の完了後にStudyplusLoginDelegateを呼び出します。 + public func login() { + let customScheme = URL(string: "studyplus://")! + guard UIApplication.shared.canOpenURL(customScheme) else { + if let store = URL(string: "https://apps.apple.com/jp/app/id505410049?mt=8") { + UIApplication.shared.open(store) + } + + return + } + + if let url = URL(string: "\(customScheme)external_app/auth/\(consumerKey)/\(consumerSecret)") { + UIApplication.shared.open(url) + } + } + + /// Studyplusアプリとの連携を解除します。 + public func logout() { + StudyplusKeychain.deleteAll(serviceName: serviceName) + } + + /// Studyplusアプリと連携されているか否かを返します。 + public func isConnected() -> Bool { + return StudyplusKeychain.accessToken(serviceName: serviceName) != nil + } + + /// Studyplusに学習記録を投稿 + /// + /// - Parameters: + /// - record: 学習記録 + /// - completion: 投稿完了後のコールバック + public func post(_ record: StudyplusRecord, completion: @escaping (Result) -> Void) { + guard let accessToken = StudyplusKeychain.accessToken(serviceName: serviceName) else { + completion(.failure(.loginRequired)) + return + } + + guard record.isValidDuration else { + completion(.failure(.invalidDuration)) + return + } + + StudyplusAPI(accessToken: accessToken).post(record, completion: { result in + switch result { + case .failure(let error): + switch error { + case .loginRequired: + // clear invalid access token + StudyplusKeychain.deleteAll(serviceName: self.serviceName) + default: + break + } + case .success: break + } + + completion(result) + }) + } + + /// Studyplusアプリの認可・ログイン画面から戻ってきた時のカスタムURLスキーム処理を担当します。 + /// AppDelegateでopenURLをハンドリングしてから、このメソッドにurlを渡して委譲してください。 + /// Studyplusアプリ関連のURLであれば、delegateオブジェクトのコールバックメソッドを呼び出します。 + /// + /// - Parameter url: + /// AppDelegate#openURLメソッドで受け取ったurlパラメータをそのまま渡して下さい。 + /// - Returns: + /// 渡されたurlがStudyplusSDKで対応すべきURLであれば true、それ以外は false を返します。 + /// __[studyplus-{consumerKey}]__と正しいpathComponentsを持つことを確認してください。 + public func handle(_ url: URL) -> Bool { + guard isAcceptableURL(url: url) else { + delegate?.studyplusLoginFail(error: .unknownUrl(url)) + return false + } + + switch url.pathComponents[1] { + case "success": + guard url.pathComponents.count >= 3 else { + delegate?.studyplusLoginFail(error: .unknownUrl(url)) + return false + } + + let accessToken: Data = url + .pathComponents[2] + .trimmingCharacters(in: .whitespacesAndNewlines) + .data(using: .utf8, allowLossyConversion: false)! + + StudyplusKeychain.set(serviceName: serviceName, accessToken: accessToken) { result in + switch result { + case .failure(let error): + self.delegate?.studyplusLoginFail(error: error) + case .success: + self.delegate?.studyplusLoginSuccess() + } + } + case "fail": + delegate?.studyplusLoginFail(error: .applicationError) + case "cancel": + delegate?.studyplusLoginFail(error: .cancel) + default: + return false + } + + return true + } + + /// StudyplusAPI用のConsumer Key と Secret を変更します。 + /// このメソッドを呼ぶとStudyplusにログイン、ログアウト、勉強記録を投稿するときなどに、別の Consumer Key と Secret に切り替えることができます。 + /// 複数のアプリケーションがStudyplusと連携している場合は、このメソッドを呼ぶ必要があります。 + /// 連携されたアプリケーションが1つしかない場合は、このメソッドを呼ぶ必要はありません。 + /// 複数のアプリケーションがStudyplusと連携している場合は、カスタムURLスキーマの設定を忘れないように注意してください。 + /// + /// - Parameter + /// - consumerKey: consumer key + /// - consumerSecret: consumer secret + public func change(consumerKey: String, consumerSecret: String) { + self.consumerKey = consumerKey + self.consumerSecret = consumerSecret + } + + private func isAcceptableURL(url: URL) -> Bool { + guard let host = url.host else { return false } + guard host == "auth-result" || host == "login-result" else { return false } + + guard let scheme = url.scheme else { return false } + guard scheme == "studyplus-\(consumerKey)" else { return false } + + // handle(_:) reads pathComponents[1], so at least 2 components are required + guard url.pathComponents.count >= 2 else { return false } + + return true + } +} diff --git a/StudyplusSDK/SPLStudyplusError.h b/Lib/StudyplusSDK/StudyplusError.swift similarity index 59% rename from StudyplusSDK/SPLStudyplusError.h rename to Lib/StudyplusSDK/StudyplusError.swift index 2d3ee6d..002a727 100644 --- a/StudyplusSDK/SPLStudyplusError.h +++ b/Lib/StudyplusSDK/StudyplusError.swift @@ -1,6 +1,10 @@ +// +// StudyplusError.swift +// StudyplusSDK +// // The MIT License (MIT) // -// Copyright (c) 2014 Studyplus inc. +// Copyright (c) 2021 Studyplus inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -20,24 +24,33 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#import - -typedef NS_ENUM(NSInteger, SPLErrorCode) { - SPLErrorCodeGetAppDescription = 1000, - SPLErrorCodeAuthFailed = 2000, - SPLErrorCodeLoginFailed = 3000, - SPLErrorCodeStudyplusInMaintenance = 4000, - SPLErrorCodeInvalidStudyplusSession = 5000, - SPLErrorCodeNetworkUnavailable = 6000, - SPLErrorCodeServerError = 7000, - SPLErrorCodePostRecordFailed = 8000, - SPLErrorCodeNotConnected = 9000, - SPLErrorCodeUnknown = 90000 -}; +import Foundation -@interface SPLStudyplusError : NSObject +public enum StudyplusPostError: Error { + case invalidDuration + case offline + case badRequest + case loginRequired + case serverError + case unknown(_ message: String) -+ (NSError*)errorFromStudyplusErrorCode:(SPLErrorCode)studyplusErrorCode; -+ (NSError*)errorFromStudyRecordPostStatusCode:(NSInteger)httpStatusCode; + static func responseError(_ code: Int) -> StudyplusPostError { + switch code { + case 400: + return .badRequest + case 401: + return .loginRequired + case 500...599: + return .serverError + default: + return .unknown("Unexpected http status: \(code)") + } + } +} -@end +public enum StudyplusLoginError: Error { + case unknownUrl(_ url: URL) + case keychainError + case applicationError + case cancel +} diff --git a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusLogger.h b/Lib/StudyplusSDK/StudyplusLoginDelegate.swift similarity index 81% rename from Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusLogger.h rename to Lib/StudyplusSDK/StudyplusLoginDelegate.swift index ec6a93e..e1ec18a 100644 --- a/Demo/StudyplusSDKDemo/StudyplusSDK/SPLStudyplusLogger.h +++ b/Lib/StudyplusSDK/StudyplusLoginDelegate.swift @@ -1,6 +1,10 @@ +// +// StudyplusLoginDelegate.swift +// StudyplusSDK +// // The MIT License (MIT) // -// Copyright (c) 2014 Studyplus inc. +// Copyright (c) 2021 Studyplus inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -20,6 +24,9 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -// This file's name must be synchronized with code in StudyplusSDK.podspec and StudyplusSDK-Prefix.pch +import Foundation -#define StudyplusSDKLog(format, ...) NSLog((@"%s[L%d]" format), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) +public protocol StudyplusLoginDelegate: AnyObject { + func studyplusLoginSuccess() + func studyplusLoginFail(error: StudyplusLoginError) +} diff --git a/Lib/StudyplusSDK/StudyplusRecord.swift b/Lib/StudyplusSDK/StudyplusRecord.swift new file mode 100644 index 0000000..4ba84ec --- /dev/null +++ b/Lib/StudyplusSDK/StudyplusRecord.swift @@ -0,0 +1,122 @@ +// +// StudyplusRecord.swift +// StudyplusSDK +// +// The MIT License (MIT) +// +// Copyright (c) 2021 Studyplus inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +public struct StudyplusRecord { + private var duration: Int + private var amount: Int? + private var startPosition: Int? + private var endPosition: Int? + private var comment: String? + private var recordDatetime: Date + + /// 勉強記録 + /// + /// - Parameters: + /// - duration: 学習時間(s), MAX 86400 (24h) + /// - comment: 学習に関するコメント + /// - recordDatetime: 学習を終えた日時 + public init(duration: Int, + comment: String?, + recordDatetime: Date = Date()) { + self.init(duration: duration, + amount: nil, + startPosition: nil, + endPosition: nil, + comment: comment, + recordDatetime: recordDatetime) + } + + /// 勉強記録 + /// + /// - Parameters: + /// - duration: 学習時間(s), MAX 86400 (24h) + /// - amount: 学習量(単位はAPI申請時に指定したもの) + /// - comment: 学習に関するコメント + /// - recordDatetime: 学習を終えた日時 + public init(duration: Int, + amount: Int, + comment: String?, + recordDatetime: Date = Date()) { + self.init(duration: duration, + amount: amount, + startPosition: nil, + endPosition: nil, + comment: comment, + recordDatetime: recordDatetime) + } + + /// 勉強記録 + /// + /// - Parameters: + /// - duration: 学習時間(s), MAX 86400 (24h) + /// - from: 学習範囲の始点 + /// - to: 学習範囲の終点 + /// - comment: 学習に関するコメント + /// - recordDatetime: 学習を終えた日時 + public init(duration: Int, + startPosition: Int, + endPosition: Int, + comment: String?, + recordDatetime: Date = Date()) { + guard startPosition <= endPosition else { + assert(true, "endPosition must be greater than startPosition") + self.init(duration: duration, + comment: comment, + recordDatetime: recordDatetime) + return + } + + self.init(duration: duration, + amount: nil, + startPosition: startPosition, + endPosition: endPosition, + comment: comment, + recordDatetime: recordDatetime) + } + + private init(duration: Int, amount: Int?, + startPosition: Int?, + endPosition: Int?, + comment: String?, + recordDatetime: Date) { + self.duration = duration + self.amount = amount + self.startPosition = startPosition + self.endPosition = endPosition + self.comment = comment + self.recordDatetime = recordDatetime + } +} + +extension StudyplusRecord { + var isValidDuration: Bool { + return 0...(24 * 60 * 60) ~= Int(duration) + } +} + +extension StudyplusRecord: Encodable {} diff --git a/StudyplusSDK/SPLStudyplusLogger.h b/Lib/StudyplusSDK/StudyplusSDK.h similarity index 71% rename from StudyplusSDK/SPLStudyplusLogger.h rename to Lib/StudyplusSDK/StudyplusSDK.h index ec6a93e..63d8fdf 100644 --- a/StudyplusSDK/SPLStudyplusLogger.h +++ b/Lib/StudyplusSDK/StudyplusSDK.h @@ -1,6 +1,10 @@ +// +// StudyplusSDK.h +// StudyplusSDK +// // The MIT License (MIT) // -// Copyright (c) 2014 Studyplus inc. +// Copyright (c) 2017 Studyplus inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -20,6 +24,14 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -// This file's name must be synchronized with code in StudyplusSDK.podspec and StudyplusSDK-Prefix.pch +#import + +//! Project version number for StudyplusSDK. +FOUNDATION_EXPORT double StudyplusSDKVersionNumber; + +//! Project version string for StudyplusSDK. +FOUNDATION_EXPORT const unsigned char StudyplusSDKVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + -#define StudyplusSDKLog(format, ...) NSLog((@"%s[L%d]" format), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) diff --git a/Lib/StudyplusSDK/internal/StudyplusAPI.swift b/Lib/StudyplusSDK/internal/StudyplusAPI.swift new file mode 100644 index 0000000..1162d30 --- /dev/null +++ b/Lib/StudyplusSDK/internal/StudyplusAPI.swift @@ -0,0 +1,103 @@ +// +// StudyplusAPI.swift +// StudyplusSDK +// +// The MIT License (MIT) +// +// Copyright (c) 2017 Studyplus inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +private struct StudyplusURL { + private static let scheme: String = "https" + private static let host: String = "external-api.studyplus.jp" + private static let version: String = "v1" + + static var records: URL { + var components = URLComponents() + components.scheme = scheme + components.host = host + components.path = "/\(version)/study_records" + + return components.url! + } +} + +internal struct StudyplusAPI { + + private let accessToken: String + private var encoder: JSONEncoder { + let encoder = JSONEncoder() + encoder.keyEncodingStrategy = .convertToSnakeCase + encoder.dateEncodingStrategy = .iso8601 + + return encoder + } + + internal init(accessToken: String) { + self.accessToken = accessToken + } + + internal func post(_ record: StudyplusRecord, completion: @escaping (Result) -> Void) { + exec(record, completion: { result in + DispatchQueue.main.async { + completion(result) + } + }) + } + + private func exec(_ record: StudyplusRecord, completion: @escaping (Result) -> Void) { + var request = URLRequest(url: StudyplusURL.records) + request.httpMethod = "POST" + request.addValue("application/json; charaset=utf-8", forHTTPHeaderField: "Content-Type") + request.addValue("OAuth \(accessToken)", forHTTPHeaderField: "Authorization") + request.httpBody = try? encoder.encode(record) + + let task = URLSession.shared.dataTask(with: request) { data, response, error in + if let error = error { + if let error = error as NSError?, + error.domain == NSURLErrorDomain, + error.code == NSURLErrorNotConnectedToInternet { + completion(.failure(.offline)) + return + } + + completion(.failure(.badRequest)) + return + } + + guard data != nil, let response = response as? HTTPURLResponse else { + completion(.failure(.badRequest)) + return + } + + guard (200...204).contains(response.statusCode) else { + let studyplusError = StudyplusPostError.responseError(response.statusCode) + completion(.failure(studyplusError)) + return + } + + completion(.success(Void())) + } + + task.resume() + } +} diff --git a/Lib/StudyplusSDK/internal/StudyplusKeychain.swift b/Lib/StudyplusSDK/internal/StudyplusKeychain.swift new file mode 100644 index 0000000..f194bf4 --- /dev/null +++ b/Lib/StudyplusSDK/internal/StudyplusKeychain.swift @@ -0,0 +1,81 @@ +// +// StudyplusKeychain.swift +// StudyplusSDK +// +// The MIT License (MIT) +// +// Copyright (c) 2021 Studyplus inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +internal struct StudyplusKeychain { + private static let accessTokenStoreKey: String = "accessToken" + + static internal func accessToken(serviceName: String) -> String? { + let query = [ + kSecClass: kSecClassGenericPassword, + kSecAttrService: serviceName, + kSecAttrSynchronizable: kSecAttrSynchronizableAny, + kSecMatchLimit: kSecMatchLimitOne, + kSecReturnData: true, + kSecAttrAccount: accessTokenStoreKey + ] as CFDictionary + + var item: CFTypeRef? + let status = SecItemCopyMatching(query, &item) + guard status == errSecSuccess, let data = item as? Data else { + return nil + } + + return String(data: data, encoding: .utf8) + } + + static internal func set(serviceName: String, + accessToken: Data, + completion: (Result) -> Void) { + // delete previous keys + deleteAll(serviceName: serviceName) + + // add new token and username + let statusAccessToken = SecItemAdd([ + kSecClass: kSecClassGenericPassword, + kSecAttrService: serviceName, + kSecAttrSynchronizable: kSecAttrSynchronizableAny, + kSecAttrAccount: accessTokenStoreKey, + kSecValueData: accessToken + ] as CFDictionary, nil) + + if statusAccessToken != noErr { + completion(.failure(.keychainError)) + return + } + + completion(.success(Void())) + } + + static func deleteAll(serviceName: String) { + SecItemDelete([ + kSecClass: kSecClassGenericPassword, + kSecAttrService: serviceName, + kSecAttrSynchronizable: kSecAttrSynchronizableAny + ] as CFDictionary) + } +} diff --git a/StudyplusSDKTests/StudyplusSDKTests-Info.plist b/Lib/StudyplusSDKTests/Info.plist similarity index 85% rename from StudyplusSDKTests/StudyplusSDKTests-Info.plist rename to Lib/StudyplusSDKTests/Info.plist index 169b6f7..6c6c23c 100644 --- a/StudyplusSDKTests/StudyplusSDKTests-Info.plist +++ b/Lib/StudyplusSDKTests/Info.plist @@ -5,17 +5,17 @@ CFBundleDevelopmentRegion en CFBundleExecutable - ${EXECUTABLE_NAME} + $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 + CFBundleName + $(PRODUCT_NAME) CFBundlePackageType BNDL CFBundleShortVersionString 1.0 - CFBundleSignature - ???? CFBundleVersion 1 diff --git a/StudyplusSDK/SPLStudyplusAPIRequest.h b/Lib/StudyplusSDKTests/StudyplusSDKTests.swift similarity index 55% rename from StudyplusSDK/SPLStudyplusAPIRequest.h rename to Lib/StudyplusSDKTests/StudyplusSDKTests.swift index 5b8990d..047f93d 100644 --- a/StudyplusSDK/SPLStudyplusAPIRequest.h +++ b/Lib/StudyplusSDKTests/StudyplusSDKTests.swift @@ -1,6 +1,10 @@ +// +// StudyplusSDKTests.swift +// StudyplusSDK +// // The MIT License (MIT) // -// Copyright (c) 2014 Studyplus inc. +// Copyright (c) 2017 Studyplus inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -20,20 +24,31 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#import +import XCTest +@testable import StudyplusSDK -NS_ASSUME_NONNULL_BEGIN +class StudyplusSDKTests: XCTestCase { -@interface SPLStudyplusAPIRequest : NSObject + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } -+ (instancetype)newRequestWithAccessToken:(NSString*)accessToken - options:(NSDictionary*)options; + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } -- (void)postRequestWithPath:(NSString *)path - requestParameter:(NSDictionary *)requestParameter - completed:(void(^)(NSDictionary * _Nullable response))completed - failed:(void(^)(NSError *error))failed; + func testExample() { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. + } -NS_ASSUME_NONNULL_END + func testPerformanceExample() { + // This is an example of a performance test case. + self.measure { + // Put the code you want to measure the time of here. + } + } -@end +} diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..dfea8ec --- /dev/null +++ b/Package.swift @@ -0,0 +1,22 @@ +// swift-tools-version:5.1 + +import PackageDescription + +let package = Package( + name: "StudyplusSDK", + platforms: [ + .iOS(.v11) + ], + products: [ + .library( + name: "StudyplusSDK", + targets: ["StudyplusSDK"] + ) + ], + targets: [ + .target( + name: "StudyplusSDK", + path: "Lib/StudyplusSDK" + ) + ] +) diff --git a/Podfile b/Podfile deleted file mode 100644 index f63868f..0000000 --- a/Podfile +++ /dev/null @@ -1,18 +0,0 @@ -platform :ios, '8.0' - -target :StudyplusSDK do - pod 'UICKeyChainStore', '1.0.4' - pod 'AFNetworking', '3.1.0' -end - -target :StudyplusSDKTests do - pod 'Kiwi/XCTest', '2.2.3' -end - -post_install do |installer_representation| - installer_representation.pods_project.targets.each do |target| - target.build_configurations.each do |config| - config.build_settings['ONLY_ACTIVE_ARCH'] = 'NO' - end - end -end diff --git a/README.md b/README.md index b23f394..4e48813 100644 --- a/README.md +++ b/README.md @@ -1,206 +1,152 @@ -StudyplusSDK -======= - -Studyplus iOS SDK for Objective-C. -[New Studyplus iOS SDK for Swift.](https://github.com/studyplus/Studyplus-iOS-SDK-V2) +# StudyplusSDK ## Requirements - * iOS 8.0 or above - * Xcode command line tools - * ARC - * [Studyplus iOS App 3.10.0 or adove](https://itunes.apple.com/jp/app/mian-qiangga-leshiku-xuku!/id505410049?mt=8) - * CocoaPods (Optional, but recommended) - -## Dependency - * [AFNetworking](https://github.com/AFNetworking/AFNetworking) - * [UICKeyChainStore](https://github.com/kishikawakatsumi/UICKeyChainStore) + * iOS 11.0以上 + * Swift 5.1以上 ## Install -### CocoaPods (Recommended) - -```ruby -# Edit your podfile -platform :ios, '8.0' -pod 'StudyplusSDK' -``` -and run -```pod install ``` +### [Swift Package Manager](https://github.com/apple/swift-package-manager/) -### Manual install +を追加してください。 -#### By library and headers +### [CocoaPods](https://cocoapods.org/) -1. Get StudyplusSDK. - * ```git clone https://github.com/studyplus/Studyplus-iOS-SDK``` or download zip from [this page](https://github.com/studyplus/Studyplus-iOS-SDK/releases). -2. Copy ```build/Release/deliverables/StudyplusSDK``` to your project. -3. Install [AFNetworking](https://github.com/AFNetworking/AFNetworking) and [UICKeyChainStore](https://github.com/kishikawakatsumi/UICKeyChainStore) too. -4. Add required frameworks(i.e. ```Security.framework, SystemConfiguration.framework, MobileCoreServices, CoreGraphics``` etc). See [AFNetworking](https://github.com/AFNetworking/AFNetworking) and [UICKeyChainStore](https://github.com/kishikawakatsumi/UICKeyChainStore). +Podfileに `StudyplusSDK` を追加してください。 -#### By source copy (iOS 8 required) - -1. Get StudyplusSDK - * ```git clone https://github.com/studyplus/Studyplus-iOS-SDK``` or download zip from [this page](https://github.com/studyplus/Studyplus-iOS-SDK/releases). -2. Copy Studyplus-iOS-SDK/StudyplusSDK directory to your project. -3. Install [AFNetworking](https://github.com/AFNetworking/AFNetworking) and [UICKeyChainStore](https://github.com/kishikawakatsumi/UICKeyChainStore) too. +```ruby +use_frameworks! +pod 'StudyplusSDK' +``` ## Usage -### Set up custom URL scheme +よりStudypluAPIの申請を最初に行ってください。 +審査後、`consumer key`と`consumer secret`の2つをメールにて送付いたします。 -- set "studyplus-*{your consumer key}*" to URL Types. -(ex. studyplus-MIoh79q7pfMbTUVA3BNsSeTaZRcOK3yg ) -- If you don't have consumerKey and consumerSecret, please contact https://info.studyplus.co.jp/contact/studyplus-api +### custom URL schemeの設定 +__studyplus-*{consumer key}*__ を URL Typesに追加してください。 -![xcode](https://raw.github.com/studyplus/Studyplus-iOS-SDK/master/docs/set_url_scheme.png) +![xcode](https://github.com/studyplus/Studyplus-iOS-SDK/blob/main/docs/set_url_scheme.png) -### Initialize +### `consumer key`と`consumer secret`の追加 -```Objective-C -#import "SPLStudyplusDelegate.h" +Info.plistに`consumer key`と`consumer secret`を追加してください。 -@interface YourClass --(BOOL)openURL:(NSURL*)url; -@end +```txt +StudyplusSDK + + consumerKey + set_your_consumerKey + consumerSecret + set_your_consumerSecret + ``` -```Objective-C -#import "SPLStudyplus.h" +### LSApplicationQueriesSchemes -static NSString * const ConsumerKey = @"Your Studyplus consumer key"; -static NSString * const ConsumerSecret = @"Your Studyplus consumer secret"; +Studyplusアプリがインストールされているかチェックできるようにするため、Info.plistの`LSApplicationQueriesSchemes`に`studyplus`を追加してください。 -static SPLStudyplus *studyplus; +```txt +LSApplicationQueriesSchemes + + studyplus + +``` -@implementation YourClass +### Initialize --(id) init { +```swift +import StudyplusSDK - if (self = [super init]) { - studyplus = [SPLStudyplus studyplusWithConsumerKey:ConsumerKey - andConsumerSecret:ConsumerSecret]; - studyplus.delegate = self; +class ViewController: UIViewController, StudyplusLoginDelegate { + override func viewDidLoad() { + super.viewDidLoad() + Studyplus.shared.delegate = self } - return self; } ``` -### Auth or Login -```Objective-C -@implementation AppDelegate +### Login -- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation -{ - return [yourClassObject openURL:url]; -} -``` +```swift +import StudyplusSDK -```Objective-C -@interface YourClass --(BOOL)openURL:(NSURL*)url; -@end +class AppDelegate: UIResponder, UIApplicationDelegate { + func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { + return Studyplus.shared.handle(url) + } +} ``` -```Objective-C -@implementation YourClass +```swift +import StudyplusSDK --(void) doAuth { - [studyplus auth]; -} +class ViewController: UIViewController, StudyplusLoginDelegate { + func login() { + Studyplus.shared.login() + } --(void) doLogin -{ - [studyplus login]; -} + func studyplusLoginSuccess() { + // on success + } -// Called by AppDelegate --(BOOL) openURL:(NSURL*)url -{ - return [studyplus openURL:url]; + func studyplusLoginFail(error: StudyplusLoginError) { + // on failed + } } +``` -// callback methods --(void)studyplusDidConnect:(SPLStudyplus*)studyplus -{ - NSLog(@"Auth or Login succeeded"); -} +### 学習記録の投稿 --(void)studyplusDidFailToConnect:(SPLStudyplus*)studyplus withError:(NSError*)error -{ - NSLog(@"Auth or Login failed"); -} +```swift +let record = StudyplusRecord(duration: Int(duration), + amount: 10, + comment: "Today, I studied like anything.", + recordDatetime: Date()) -- (void)studyplusDidCancel:(SPLStudyplus*)studyplus -{ - NSLog(@"Auth or Login canceled"); -} +Studyplus.shared.post(record, completion: { result in + switch result { + case .failure(let error): + // handle error + case .success: + // finish post + } +}) ``` -### Post study record to Studyplus - -```Objective-C --(void)post -{ - - // Create new study record. - SPLStudyplusRecord *studyplusRecord = - [SPLStudyplusRecord - - /** - @see SPLStopwatch - */ - recordWithDuration:[studyplus.stopwatch elapsedSeconds] - - /** You can add optional info. - options:@{ - // Time the learning is ended. 学習を終えた日時。 - @"recordedAt" : [NSDate date], - // Studyplus timeline comment. Studyplusのタイムライン上で表示されるコメント。 - @"comment" : @"アプリ◯◯で勉強しました!!", - // @see SPLStudyplusRecordAmount - @"amount" : [SPLStudyplusRecordAmount amount:100], - } - */ - - ]; - - // post - [studyplus postStudyRecord:studyplusRecord]; - -} - -// callback methods --(void)studyplusDidPostStudyRecord:(SPLStudyplus*)studyplus -{ - NSLog(@"Post to Studyplus succeeded"); -} +## Demo app --(void)studyplusDidFailToPostStudyRecord:(SPLStudyplus*)studyplus withError:(NSError*)error -{ - // see @SPLStudyplusError with error.code. - NSLog(@"Post to Studyplus failed"); -} -``` +![demo](https://github.com/studyplus/Studyplus-iOS-SDK/blob/main/docs/demoapp.jpg) -### More info about SDK interface +- Set __studyplus-*{your consumer key}*__ to URL Types in Demo. +- Set __consumerKey__ and __consumerSecret__ in Info.plist of Demo. +- Select Demo Scheme and Run. - * StudyplusSDK/SPLStudyplus.h - * StudyplusSDK/SPLStudyplusDelegate.h - * StudyplusSDK/SPLStudyplusRecord.h - * StudyplusSDK/SPLStudyplusRecordAmount.h +## License -## Demo app +```txt +The MIT License (MIT) -![demo](https://raw.github.com/studyplus/Studyplus-iOS-SDK/master/docs/demoapp.png) +Copyright (c) 2021 Studyplus inc. -1. Run `pod try StudyplusSDK` or See Demo directory and open StudyplusSDKDemo/StudyplusSDKDemo.xcodeproj -2. Edit consumer key and consumer secret in Viewcontroller.m -3. Set URL Type with your consumer key -4. Run -5. Do "Auth" and "Post record", and see public timeline at http://studyplus.jp +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: -## License +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. -[MIT License.](http://opensource.org/licenses/mit-license.php) +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +``` diff --git a/Sources/Studyplus.swift b/Sources/Studyplus.swift new file mode 100644 index 0000000..11dacbc --- /dev/null +++ b/Sources/Studyplus.swift @@ -0,0 +1 @@ +../Lib/StudyplusSDK/Studyplus.swift diff --git a/StudyplusSDK.podspec b/StudyplusSDK.podspec index e9f7a27..fae74d9 100644 --- a/StudyplusSDK.podspec +++ b/StudyplusSDK.podspec @@ -1,19 +1,14 @@ Pod::Spec.new do |s| - s.name = "StudyplusSDK" - s.version = "3.0.1" - s.summary = "Studyplus iOS SDK" - s.description = <<-DESC - Let's post learning records to Studyplus(https://studyplus.jp) - DESC - s.homepage = "http://info.studyplus.jp" - s.license = { :type => 'MIT', :file => 'LICENSE.txt' } - s.author = { "studyplus" => "sutou@studyplus.jp" } - s.platform = :ios, '8.0' - s.source = { :git => "https://github.com/studyplus/Studyplus-iOS-SDK.git", :tag => s.version.to_s } - s.source_files = 'StudyplusSDK/**/*.{h,m}' - s.public_header_files = 'StudyplusSDK/**/*.h' - s.requires_arc = true - - s.dependency 'UICKeyChainStore', '1.0.4' - s.dependency 'AFNetworking', '3.1.0' + s.name = "StudyplusSDK" + s.version = "4.0.0" + s.summary = "StudyplusSDK is Studyplus iOS SDK for Swift" + s.homepage = "https://info.studyplus.jp" + s.license = "MIT" + s.source = { :git => "https://github.com/studyplus/Studyplus-iOS-SDK.git", :tag => s.version } + s.source_files = "StudyplusSDK", "Lib/StudyplusSDK/**/*.{swift}" + s.platform = :ios, '11.0' + s.ios.deployment_target = '11.0' + s.ios.frameworks = ['UIKit', 'Foundation'] + s.author = { 'Studyplus inc' => 'developer-all@studyplus.jp' } + s.swift_versions = ['5.1', '5.2', '5.3'] end diff --git a/StudyplusSDK.xcodeproj/project.pbxproj b/StudyplusSDK.xcodeproj/project.pbxproj deleted file mode 100644 index c427cf4..0000000 --- a/StudyplusSDK.xcodeproj/project.pbxproj +++ /dev/null @@ -1,606 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 15AB6B46CA8D69A07A657108 /* libPods-StudyplusSDK.a in Frameworks */ = {isa = PBXBuildFile; fileRef = AB6543514EFDD1680EB02D7D /* libPods-StudyplusSDK.a */; }; - 33472D69D42A4309A1008C74 /* libPods-StudyplusSDKTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = FBD5C2B6437D459690D83F00 /* libPods-StudyplusSDKTests.a */; }; - 4302C73818B49A5F005A8390 /* SPLStopwatch.m in Sources */ = {isa = PBXBuildFile; fileRef = 4302C73718B49A5F005A8390 /* SPLStopwatch.m */; }; - 4369272E188F7D3B00D06212 /* SPLStudyplus.m in Sources */ = {isa = PBXBuildFile; fileRef = 43692722188F7D3B00D06212 /* SPLStudyplus.m */; }; - 4369272F188F7D3B00D06212 /* SPLStudyplusAPIRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 43692723188F7D3B00D06212 /* SPLStudyplusAPIRequest.m */; }; - 43692730188F7D3B00D06212 /* SPLStudyplusError.m in Sources */ = {isa = PBXBuildFile; fileRef = 43692725188F7D3B00D06212 /* SPLStudyplusError.m */; }; - 43692731188F7D3B00D06212 /* SPLStudyplusRecordAmount.m in Sources */ = {isa = PBXBuildFile; fileRef = 43692728188F7D3B00D06212 /* SPLStudyplusRecordAmount.m */; }; - 43692732188F7D3B00D06212 /* SPLStudyplusRecord.m in Sources */ = {isa = PBXBuildFile; fileRef = 4369272A188F7D3B00D06212 /* SPLStudyplusRecord.m */; }; - 43692BC7188FA25700D06212 /* libStudyplusSDK.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 43E8E6761856CB770066D476 /* libStudyplusSDK.a */; }; - 436C40CC1866076000B35D72 /* StudyplusRecordTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 436C40CB1866076000B35D72 /* StudyplusRecordTests.m */; }; - 43E8E6881856CB770066D476 /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 43E8E6871856CB770066D476 /* XCTest.framework */; }; - 43E8E6941856CB780066D476 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 43E8E6921856CB780066D476 /* InfoPlist.strings */; }; - 43E8E6A2185701C20066D476 /* StudyplusTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 43E8E6A1185701C20066D476 /* StudyplusTests.m */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 43E8E68C1856CB770066D476 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 43E8E66E1856CB770066D476 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 43E8E6751856CB770066D476; - remoteInfo = StudyplusSDK; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 43E8E6741856CB770066D476 /* CopyFiles */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = "include/$(PRODUCT_NAME)"; - dstSubfolderSpec = 16; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 4302C73618B49A5F005A8390 /* SPLStopwatch.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SPLStopwatch.h; path = StudyplusSDK/SPLStopwatch.h; sourceTree = SOURCE_ROOT; }; - 4302C73718B49A5F005A8390 /* SPLStopwatch.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SPLStopwatch.m; path = StudyplusSDK/SPLStopwatch.m; sourceTree = SOURCE_ROOT; }; - 43692722188F7D3B00D06212 /* SPLStudyplus.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SPLStudyplus.m; path = StudyplusSDK/SPLStudyplus.m; sourceTree = SOURCE_ROOT; }; - 43692723188F7D3B00D06212 /* SPLStudyplusAPIRequest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SPLStudyplusAPIRequest.m; path = StudyplusSDK/SPLStudyplusAPIRequest.m; sourceTree = SOURCE_ROOT; }; - 43692724188F7D3B00D06212 /* SPLStudyplusError.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SPLStudyplusError.h; path = StudyplusSDK/SPLStudyplusError.h; sourceTree = SOURCE_ROOT; }; - 43692725188F7D3B00D06212 /* SPLStudyplusError.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SPLStudyplusError.m; path = StudyplusSDK/SPLStudyplusError.m; sourceTree = SOURCE_ROOT; }; - 43692726188F7D3B00D06212 /* SPLStudyplusDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SPLStudyplusDelegate.h; path = StudyplusSDK/SPLStudyplusDelegate.h; sourceTree = SOURCE_ROOT; }; - 43692727188F7D3B00D06212 /* SPLStudyplusLogger.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SPLStudyplusLogger.h; path = StudyplusSDK/SPLStudyplusLogger.h; sourceTree = SOURCE_ROOT; }; - 43692728188F7D3B00D06212 /* SPLStudyplusRecordAmount.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SPLStudyplusRecordAmount.m; path = StudyplusSDK/SPLStudyplusRecordAmount.m; sourceTree = SOURCE_ROOT; }; - 43692729188F7D3B00D06212 /* SPLStudyplusRecordAmount.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SPLStudyplusRecordAmount.h; path = StudyplusSDK/SPLStudyplusRecordAmount.h; sourceTree = SOURCE_ROOT; }; - 4369272A188F7D3B00D06212 /* SPLStudyplusRecord.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SPLStudyplusRecord.m; path = StudyplusSDK/SPLStudyplusRecord.m; sourceTree = SOURCE_ROOT; }; - 4369272B188F7D3B00D06212 /* SPLStudyplusRecord.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SPLStudyplusRecord.h; path = StudyplusSDK/SPLStudyplusRecord.h; sourceTree = SOURCE_ROOT; }; - 4369272C188F7D3B00D06212 /* SPLStudyplusAPIRequest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SPLStudyplusAPIRequest.h; path = StudyplusSDK/SPLStudyplusAPIRequest.h; sourceTree = SOURCE_ROOT; }; - 4369272D188F7D3B00D06212 /* SPLStudyplus.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SPLStudyplus.h; path = StudyplusSDK/SPLStudyplus.h; sourceTree = SOURCE_ROOT; }; - 436C40CB1866076000B35D72 /* StudyplusRecordTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = StudyplusRecordTests.m; sourceTree = ""; }; - 43E8E6761856CB770066D476 /* libStudyplusSDK.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libStudyplusSDK.a; sourceTree = BUILT_PRODUCTS_DIR; }; - 43E8E67D1856CB770066D476 /* StudyplusSDK-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "StudyplusSDK-Prefix.pch"; sourceTree = ""; }; - 43E8E6861856CB770066D476 /* StudyplusSDKTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = StudyplusSDKTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 43E8E6871856CB770066D476 /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = XCTest.framework; path = Library/Frameworks/XCTest.framework; sourceTree = DEVELOPER_DIR; }; - 43E8E6911856CB780066D476 /* StudyplusSDKTests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "StudyplusSDKTests-Info.plist"; sourceTree = ""; }; - 43E8E6931856CB780066D476 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; - 43E8E6A1185701C20066D476 /* StudyplusTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = StudyplusTests.m; sourceTree = ""; }; - 6CDC075119D444CB061961CD /* Pods-StudyplusSDKTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-StudyplusSDKTests.debug.xcconfig"; path = "Pods/Target Support Files/Pods-StudyplusSDKTests/Pods-StudyplusSDKTests.debug.xcconfig"; sourceTree = ""; }; - 6D8BEFFED25640C683A993B8 /* libPods.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPods.a; sourceTree = BUILT_PRODUCTS_DIR; }; - 75AE92730C3FEEC9998DAB03 /* Pods-StudyplusSDK.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-StudyplusSDK.debug.xcconfig"; path = "Pods/Target Support Files/Pods-StudyplusSDK/Pods-StudyplusSDK.debug.xcconfig"; sourceTree = ""; }; - AB6543514EFDD1680EB02D7D /* libPods-StudyplusSDK.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-StudyplusSDK.a"; sourceTree = BUILT_PRODUCTS_DIR; }; - D5BEF810E851793E19193D92 /* Pods-StudyplusSDK.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-StudyplusSDK.release.xcconfig"; path = "Pods/Target Support Files/Pods-StudyplusSDK/Pods-StudyplusSDK.release.xcconfig"; sourceTree = ""; }; - F05AC748C4A7545C45B0C21D /* Pods-StudyplusSDKTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-StudyplusSDKTests.release.xcconfig"; path = "Pods/Target Support Files/Pods-StudyplusSDKTests/Pods-StudyplusSDKTests.release.xcconfig"; sourceTree = ""; }; - FBD5C2B6437D459690D83F00 /* libPods-StudyplusSDKTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-StudyplusSDKTests.a"; sourceTree = BUILT_PRODUCTS_DIR; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 43E8E6731856CB770066D476 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 15AB6B46CA8D69A07A657108 /* libPods-StudyplusSDK.a in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 43E8E6831856CB770066D476 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 43692BC7188FA25700D06212 /* libStudyplusSDK.a in Frameworks */, - 43E8E6881856CB770066D476 /* XCTest.framework in Frameworks */, - 33472D69D42A4309A1008C74 /* libPods-StudyplusSDKTests.a in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 43802C8E185FFA4A00D941FE /* Studyplus */ = { - isa = PBXGroup; - children = ( - 4369272D188F7D3B00D06212 /* SPLStudyplus.h */, - 43692722188F7D3B00D06212 /* SPLStudyplus.m */, - 4369272C188F7D3B00D06212 /* SPLStudyplusAPIRequest.h */, - 43692723188F7D3B00D06212 /* SPLStudyplusAPIRequest.m */, - 43692726188F7D3B00D06212 /* SPLStudyplusDelegate.h */, - 43692724188F7D3B00D06212 /* SPLStudyplusError.h */, - 43692725188F7D3B00D06212 /* SPLStudyplusError.m */, - 43692727188F7D3B00D06212 /* SPLStudyplusLogger.h */, - 4369272B188F7D3B00D06212 /* SPLStudyplusRecord.h */, - 4369272A188F7D3B00D06212 /* SPLStudyplusRecord.m */, - 43692729188F7D3B00D06212 /* SPLStudyplusRecordAmount.h */, - 43692728188F7D3B00D06212 /* SPLStudyplusRecordAmount.m */, - 4302C73618B49A5F005A8390 /* SPLStopwatch.h */, - 4302C73718B49A5F005A8390 /* SPLStopwatch.m */, - ); - name = Studyplus; - path = Classes; - sourceTree = ""; - }; - 43E8E66D1856CB770066D476 = { - isa = PBXGroup; - children = ( - 43E8E67B1856CB770066D476 /* Studyplus */, - 43E8E68F1856CB780066D476 /* StudyplusTests */, - 43E8E6781856CB770066D476 /* Frameworks */, - 43E8E6771856CB770066D476 /* Products */, - 49CC654E20CA237380F2A27B /* Pods */, - ); - sourceTree = ""; - }; - 43E8E6771856CB770066D476 /* Products */ = { - isa = PBXGroup; - children = ( - 43E8E6761856CB770066D476 /* libStudyplusSDK.a */, - 43E8E6861856CB770066D476 /* StudyplusSDKTests.xctest */, - ); - name = Products; - sourceTree = ""; - }; - 43E8E6781856CB770066D476 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 43E8E6871856CB770066D476 /* XCTest.framework */, - 6D8BEFFED25640C683A993B8 /* libPods.a */, - FBD5C2B6437D459690D83F00 /* libPods-StudyplusSDKTests.a */, - AB6543514EFDD1680EB02D7D /* libPods-StudyplusSDK.a */, - ); - name = Frameworks; - sourceTree = ""; - }; - 43E8E67B1856CB770066D476 /* Studyplus */ = { - isa = PBXGroup; - children = ( - 43802C8E185FFA4A00D941FE /* Studyplus */, - 43E8E67C1856CB770066D476 /* Supporting Files */, - ); - name = Studyplus; - path = StudyplusSDK; - sourceTree = ""; - }; - 43E8E67C1856CB770066D476 /* Supporting Files */ = { - isa = PBXGroup; - children = ( - 43E8E67D1856CB770066D476 /* StudyplusSDK-Prefix.pch */, - ); - name = "Supporting Files"; - sourceTree = ""; - }; - 43E8E68F1856CB780066D476 /* StudyplusTests */ = { - isa = PBXGroup; - children = ( - 43E8E6A1185701C20066D476 /* StudyplusTests.m */, - 436C40CB1866076000B35D72 /* StudyplusRecordTests.m */, - 43E8E6901856CB780066D476 /* Supporting Files */, - ); - name = StudyplusTests; - path = StudyplusSDKTests; - sourceTree = ""; - }; - 43E8E6901856CB780066D476 /* Supporting Files */ = { - isa = PBXGroup; - children = ( - 43E8E6911856CB780066D476 /* StudyplusSDKTests-Info.plist */, - 43E8E6921856CB780066D476 /* InfoPlist.strings */, - ); - name = "Supporting Files"; - sourceTree = ""; - }; - 49CC654E20CA237380F2A27B /* Pods */ = { - isa = PBXGroup; - children = ( - 75AE92730C3FEEC9998DAB03 /* Pods-StudyplusSDK.debug.xcconfig */, - D5BEF810E851793E19193D92 /* Pods-StudyplusSDK.release.xcconfig */, - 6CDC075119D444CB061961CD /* Pods-StudyplusSDKTests.debug.xcconfig */, - F05AC748C4A7545C45B0C21D /* Pods-StudyplusSDKTests.release.xcconfig */, - ); - name = Pods; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 43E8E6751856CB770066D476 /* StudyplusSDK */ = { - isa = PBXNativeTarget; - buildConfigurationList = 43E8E6991856CB780066D476 /* Build configuration list for PBXNativeTarget "StudyplusSDK" */; - buildPhases = ( - 813A4A7A17024E4CA022C118 /* [CP] Check Pods Manifest.lock */, - 43E8E6721856CB770066D476 /* Sources */, - 43E8E6731856CB770066D476 /* Frameworks */, - 43E8E6741856CB770066D476 /* CopyFiles */, - 62CDD57D8E864132B070C939 /* [CP] Copy Pods Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = StudyplusSDK; - productName = StudyplusSDK; - productReference = 43E8E6761856CB770066D476 /* libStudyplusSDK.a */; - productType = "com.apple.product-type.library.static"; - }; - 43E8E6851856CB770066D476 /* StudyplusSDKTests */ = { - isa = PBXNativeTarget; - buildConfigurationList = 43E8E69C1856CB780066D476 /* Build configuration list for PBXNativeTarget "StudyplusSDKTests" */; - buildPhases = ( - 5C9B292132524996BCADD319 /* [CP] Check Pods Manifest.lock */, - 43E8E6821856CB770066D476 /* Sources */, - 43E8E6831856CB770066D476 /* Frameworks */, - 43E8E6841856CB770066D476 /* Resources */, - 6C6645884994437082EAF22F /* [CP] Copy Pods Resources */, - A904EA54BC5E03808ECBD415 /* [CP] Embed Pods Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - 43E8E68D1856CB770066D476 /* PBXTargetDependency */, - ); - name = StudyplusSDKTests; - productName = StudyplusSDKTests; - productReference = 43E8E6861856CB770066D476 /* StudyplusSDKTests.xctest */; - productType = "com.apple.product-type.bundle.unit-test"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 43E8E66E1856CB770066D476 /* Project object */ = { - isa = PBXProject; - attributes = { - CLASSPREFIX = SPL; - LastUpgradeCheck = 0820; - ORGANIZATIONNAME = studyplus.jp; - }; - buildConfigurationList = 43E8E6711856CB770066D476 /* Build configuration list for PBXProject "StudyplusSDK" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 0; - knownRegions = ( - en, - ); - mainGroup = 43E8E66D1856CB770066D476; - productRefGroup = 43E8E6771856CB770066D476 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 43E8E6751856CB770066D476 /* StudyplusSDK */, - 43E8E6851856CB770066D476 /* StudyplusSDKTests */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 43E8E6841856CB770066D476 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 43E8E6941856CB780066D476 /* InfoPlist.strings in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXShellScriptBuildPhase section */ - 5C9B292132524996BCADD319 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n"; - showEnvVarsInLog = 0; - }; - 62CDD57D8E864132B070C939 /* [CP] Copy Pods Resources */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "[CP] Copy Pods Resources"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-StudyplusSDK/Pods-StudyplusSDK-resources.sh\"\n"; - showEnvVarsInLog = 0; - }; - 6C6645884994437082EAF22F /* [CP] Copy Pods Resources */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "[CP] Copy Pods Resources"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-StudyplusSDKTests/Pods-StudyplusSDKTests-resources.sh\"\n"; - showEnvVarsInLog = 0; - }; - 813A4A7A17024E4CA022C118 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "[CP] Check Pods Manifest.lock"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n"; - showEnvVarsInLog = 0; - }; - A904EA54BC5E03808ECBD415 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - name = "[CP] Embed Pods Frameworks"; - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-StudyplusSDKTests/Pods-StudyplusSDKTests-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 43E8E6721856CB770066D476 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4369272F188F7D3B00D06212 /* SPLStudyplusAPIRequest.m in Sources */, - 4302C73818B49A5F005A8390 /* SPLStopwatch.m in Sources */, - 43692732188F7D3B00D06212 /* SPLStudyplusRecord.m in Sources */, - 43692730188F7D3B00D06212 /* SPLStudyplusError.m in Sources */, - 43692731188F7D3B00D06212 /* SPLStudyplusRecordAmount.m in Sources */, - 4369272E188F7D3B00D06212 /* SPLStudyplus.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 43E8E6821856CB770066D476 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 436C40CC1866076000B35D72 /* StudyplusRecordTests.m in Sources */, - 43E8E6A2185701C20066D476 /* StudyplusTests.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 43E8E68D1856CB770066D476 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 43E8E6751856CB770066D476 /* StudyplusSDK */; - targetProxy = 43E8E68C1856CB770066D476 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin PBXVariantGroup section */ - 43E8E6921856CB780066D476 /* InfoPlist.strings */ = { - isa = PBXVariantGroup; - children = ( - 43E8E6931856CB780066D476 /* en */, - ); - name = InfoPlist.strings; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 43E8E6971856CB780066D476 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_TREAT_WARNINGS_AS_ERRORS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_INHIBIT_ALL_WARNINGS = NO; - GCC_WARN_PEDANTIC = NO; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - VALID_ARCHS = "arm64 armv7 armv7s"; - }; - name = Debug; - }; - 43E8E6981856CB780066D476 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = YES; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_TREAT_WARNINGS_AS_ERRORS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_INHIBIT_ALL_WARNINGS = NO; - GCC_WARN_PEDANTIC = NO; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - SDKROOT = iphoneos; - VALIDATE_PRODUCT = YES; - VALID_ARCHS = "arm64 armv7 armv7s"; - }; - name = Release; - }; - 43E8E69A1856CB780066D476 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 75AE92730C3FEEC9998DAB03 /* Pods-StudyplusSDK.debug.xcconfig */; - buildSettings = { - DSTROOT = /tmp/StudyplusSDK.dst; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "StudyplusSDK/StudyplusSDK-Prefix.pch"; - ONLY_ACTIVE_ARCH = NO; - OTHER_LDFLAGS = ( - "$(inherited)", - "-ObjC", - ); - PRODUCT_NAME = "$(TARGET_NAME)"; - SKIP_INSTALL = YES; - VALID_ARCHS = "arm64 armv7 armv7s"; - }; - name = Debug; - }; - 43E8E69B1856CB780066D476 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = D5BEF810E851793E19193D92 /* Pods-StudyplusSDK.release.xcconfig */; - buildSettings = { - DSTROOT = /tmp/StudyplusSDK.dst; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "StudyplusSDK/StudyplusSDK-Prefix.pch"; - ONLY_ACTIVE_ARCH = NO; - OTHER_LDFLAGS = ( - "$(inherited)", - "-ObjC", - ); - PRODUCT_NAME = "$(TARGET_NAME)"; - SKIP_INSTALL = YES; - VALID_ARCHS = "arm64 armv7 armv7s"; - }; - name = Release; - }; - 43E8E69D1856CB780066D476 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 6CDC075119D444CB061961CD /* Pods-StudyplusSDKTests.debug.xcconfig */; - buildSettings = { - FRAMEWORK_SEARCH_PATHS = ( - "$(SDKROOT)/Developer/Library/Frameworks", - "$(inherited)", - "$(DEVELOPER_FRAMEWORKS_DIR)", - ); - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "StudyplusSDK/StudyplusSDK-Prefix.pch"; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - INFOPLIST_FILE = "StudyplusSDKTests/StudyplusSDKTests-Info.plist"; - ONLY_ACTIVE_ARCH = NO; - PRODUCT_BUNDLE_IDENTIFIER = "jp.studyplus.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME)"; - WRAPPER_EXTENSION = xctest; - }; - name = Debug; - }; - 43E8E69E1856CB780066D476 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = F05AC748C4A7545C45B0C21D /* Pods-StudyplusSDKTests.release.xcconfig */; - buildSettings = { - FRAMEWORK_SEARCH_PATHS = ( - "$(SDKROOT)/Developer/Library/Frameworks", - "$(inherited)", - "$(DEVELOPER_FRAMEWORKS_DIR)", - ); - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "StudyplusSDK/StudyplusSDK-Prefix.pch"; - INFOPLIST_FILE = "StudyplusSDKTests/StudyplusSDKTests-Info.plist"; - ONLY_ACTIVE_ARCH = NO; - PRODUCT_BUNDLE_IDENTIFIER = "jp.studyplus.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME)"; - WRAPPER_EXTENSION = xctest; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 43E8E6711856CB770066D476 /* Build configuration list for PBXProject "StudyplusSDK" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 43E8E6971856CB780066D476 /* Debug */, - 43E8E6981856CB780066D476 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 43E8E6991856CB780066D476 /* Build configuration list for PBXNativeTarget "StudyplusSDK" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 43E8E69A1856CB780066D476 /* Debug */, - 43E8E69B1856CB780066D476 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 43E8E69C1856CB780066D476 /* Build configuration list for PBXNativeTarget "StudyplusSDKTests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 43E8E69D1856CB780066D476 /* Debug */, - 43E8E69E1856CB780066D476 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 43E8E66E1856CB770066D476 /* Project object */; -} diff --git a/StudyplusSDK.xcworkspace/contents.xcworkspacedata b/StudyplusSDK.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 8c0b865..0000000 --- a/StudyplusSDK.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/StudyplusSDK/SPLStopwatch.h b/StudyplusSDK/SPLStopwatch.h deleted file mode 100644 index c1e82ca..0000000 --- a/StudyplusSDK/SPLStopwatch.h +++ /dev/null @@ -1,55 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -/** - Simple stopwatch with [start/stop/reset] functions. Useful for measuring the learning duration.
- シンプルなストップウォッチです。学習時間(duration)を計測するのに便利です。 - */ -@interface SPLStopwatch : NSObject - -/** - Begin or resume measuring.
- 測定を開始または再開します。 - */ --(void)start; - -/** - Pause measuring. Elapsed seconds will not be reset.
- 測定を一時停止します。経過秒数はリセットされません。 - */ --(void)pause; - -/** - Reset elapsed seconds. Elapsed seconds will be 0, and measuring will not stop.
- 経過秒数を0にリセットします。測定中の場合、測定は止まりません。 - */ --(void)reset; - -/** - Returns total elapsed seconds.
- 現時点の累計経過秒数を返します。 - */ --(NSUInteger)elapsedSeconds; - -@end diff --git a/StudyplusSDK/SPLStopwatch.m b/StudyplusSDK/SPLStopwatch.m deleted file mode 100644 index b5a6c34..0000000 --- a/StudyplusSDK/SPLStopwatch.m +++ /dev/null @@ -1,88 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "SPLStopwatch.h" - -typedef NS_ENUM(NSInteger, SPLStopwatchState) { - SPLStopwatchStateStarted, - SPLStopwatchStateStopped -}; - -@interface SPLStopwatch() -@property (nonatomic, assign) NSUInteger elapsedSeconds; -@property (nonatomic, assign) NSUInteger startedTimestamp; -@property (nonatomic, assign) SPLStopwatchState state; -@end - -@implementation SPLStopwatch - --(instancetype)init -{ - if (self = [super init]) { - self.elapsedSeconds = 0; - self.startedTimestamp = 0; - self.state = SPLStopwatchStateStopped; - } - return self; -} - --(void)start -{ - if (self.state == SPLStopwatchStateStarted) { - return; - } - self.state = SPLStopwatchStateStarted; - - self.startedTimestamp = [[NSDate date] timeIntervalSince1970]; -} - --(void)pause -{ - if (self.state == SPLStopwatchStateStopped) { - return; - } - self.state = SPLStopwatchStateStopped; - - NSUInteger now = [[NSDate date] timeIntervalSince1970]; - self.elapsedSeconds += (now - self.startedTimestamp); -} - --(void)reset -{ - if (self.state == SPLStopwatchStateStarted) { - self.startedTimestamp = [[NSDate date] timeIntervalSince1970]; - } - self.elapsedSeconds = 0; -} - --(NSUInteger)elapsedSeconds -{ - if (self.state == SPLStopwatchStateStarted) { - NSUInteger now = [[NSDate date] timeIntervalSince1970]; - NSUInteger elapsedSeconds = _elapsedSeconds + (now - self.startedTimestamp); - return elapsedSeconds; - } else { - return _elapsedSeconds; - } -} - -@end diff --git a/StudyplusSDK/SPLStudyplus.h b/StudyplusSDK/SPLStudyplus.h deleted file mode 100644 index c6777ac..0000000 --- a/StudyplusSDK/SPLStudyplus.h +++ /dev/null @@ -1,189 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "SPLStudyplusDelegate.h" -#import "SPLStudyplusRecord.h" -#import "SPLStudyplusRecordAmount.h" -#import "SPLStopwatch.h" - -NS_ASSUME_NONNULL_BEGIN - -/** - The class for using Studyplus.
- For example, you can authenticate in Studyplus account, de-authentication, and post study record. - - Studyplusの各機能を使うためのクラスです。
- Studyplusアカウントとの連携、連携解除、勉強記録の投稿ができます。 - */ -@interface SPLStudyplus : NSObject - -/** - The version of the StudyplusAPI. Default value is 1.
- StudyplusAPI のバージョンを指定します。デフォルトは 1 です。 - - https://external-api.studyplus.jp/v{apiVersion}/endpoint_name - */ -@property (nonatomic) NSInteger apiVersion; - -/** - Debug mode switch.
- When set to YES, then call back to the delegate without posting the actual processing.
- Default value is NO. - - StudyplusAPI のバージョンを指定します。
- debug=YESの場合、勉強記録の投稿時に実際の通信は行わずdelegateのコールバックメソッドを呼び出して処理を終了します。 - */ -@property (nonatomic) BOOL debug; - -/** - StudyplusAPI用のConsumer Keyです。
- Consumer Key for Studyplus API. - */ -@property (nonatomic, copy, readonly) NSString *consumerKey; - -/** - StudyplusAPI用のConsumer Secretです。
- Consumer Secret for Studyplus API. - */ -@property (nonatomic, copy, readonly) NSString *consumerSecret; - -/** - @see SPLStudyplusDelegate protocol - */ -@property (nonatomic, weak, nullable) id delegate; - -/** - When set to YES, if Studyplus is not installed, AppStore application starts when auth/login methods are called. Default value is YES.
- YESに設定すると、auth、loginメソッドを呼び出したとき、StudyplusアプリがインストールされていなければAppStoreを起動します。デフォルトは YES です。 - */ -@property (nonatomic) BOOL openAppStoreIfNotInstalled; - -/** - Username of Studyplus account. It is set when the auth or login is successful. Default value is nil.
- Studyplusアカウントのユーザ名です。login または authが成功したとき設定されます。設定されるまではnilです。 - */ -@property (nonatomic, copy, readonly, nullable) NSString *username; - -/** - Access token of Studyplus API. It is set when the auth or login is successful. Default value is nil.
- StudyplusAPIのアクセストークンです。login または authが成功したとき設定されます。設定されるまではnilです。 - */ -@property (nonatomic, copy, readonly, nullable) NSString *accessToken; - -/** - @see SPLStopwatch class - */ -@property (nonatomic, readonly, nullable) SPLStopwatch *stopwatch; - -/** - The convenience constructor of SPLStudyplus class. - - SPLStudyplusクラスのオブジェクトを生成して返します。 - - @param consumerKey Specify a Consumer Key for StudyplusAPI.
- StudyplusAPI用のコンシューマキーを指定してください。 - - @param consumerSecret Specify a Consumer Secret for StudyplusAPI.
- StudyplusAPI用のコンシューマシークレットを指定してください。 - - @return SPLStudyplus object.
- SPLStudyplusオブジェクト。 - */ -+ (instancetype)studyplusWithConsumerKey:(NSString*)consumerKey - andConsumerSecret:(NSString*)consumerSecret; - -/** - Opens the auth screen by invoking the Studyplus application. - - Studyplusアプリを起動して連携許可画面を開きます。 - - If Studyplus app is not installed and openAppStoreIfNotInstalled is YES, then open the Studyplus page in AppStore.
- If openAppStoreIfNotInstalled is NO, do nothing.
- After the process has returned from Studyplus application, delegate method will be called back. - - Studyplusアプリがインストールされていない場合、 openAppStoreIfNotInstalled がYESであれば、AppStoreを起動してStudyplusページを開きます。
- openAppStoreIfNotInstalled がNOであれば何もしません。
- Studyplusアプリから操作が戻ってきた後、delegateオブジェクトのコールバックメソッドを呼び出します。 - - @return It returns YES when you started Studyplus application. If Studyplus application is not installed, it returns NO.
- Studyplusアプリが起動した時点でYESを返します。Studyplusアプリがインストールされていない場合、NOを返します。 - */ -- (BOOL)auth; - -/** - Opens the login screen by invoking the Studyplus application. - - Studyplusアプリを起動してStudyplusログイン画面を開きます。 - - If Studyplus app is not installed and openAppStoreIfNotInstalled is YES, then open the Studyplus page in AppStore.
- If openAppStoreIfNotInstalled is NO, do nothing.
- After the process has returned from Studyplus application, delegate method will be called back. - - Studyplusアプリがインストールされていない場合、 openAppStoreIfNotInstalled がYESであれば、AppStoreを起動してStudyplusページを開きます。
- openAppStoreIfNotInstalled がNOであれば何もしません。
- Studyplusアプリから操作が戻ってきた後、delegateオブジェクトのコールバックメソッドを呼び出します。 - - @return It returns YES when you started Studyplus application. If Studyplus application is not installed, it returns NO.
- Studyplusアプリが起動した時点でYESを返します。Studyplusアプリがインストールされていない場合、NOを返します。 - */ -- (BOOL)login; - -/** - Posts new study record to Studyplus.
- Studyplusに勉強記録を新規投稿します。 - - @param studyRecord @see SPLStudyplusRecord - */ -- (void)postStudyRecord:(SPLStudyplusRecord*)studyRecord; - -/** - Cancels the cooperation with Studyplus application.
- Studyplusアプリとの連携を解除します。 - */ -- (void)logout; - -/** - Returns to whether or not it is in conjunction with Studyplus application.
- Studyplusアプリと連携されているか否かを返します。 - */ -- (BOOL)isConnected; - -/** - It is responsible for processing custom URL scheme when it came back from the authorization / login screen of Stuudyplus app.
- After handling openURL method in AppDelegate, pass the url parameter to this method.
- If the URL is passed by Studyplus application, calls the callback method of the delegate object. - - Studyplusアプリの認可・ログイン画面から戻ってきた時のカスタムURLスキーム処理を担当します。
- AppDelegateでopenURLをハンドリングしてから、このメソッドにurlを渡して委譲してください。
- Studyplusアプリ関連のURLであれば、delegateオブジェクトのコールバックメソッドを呼び出します。 - - @param url The parameter of AppDelegate#openURL method.
- AppDelegate#openURLメソッドで受け取ったurlパラメータをそのまま渡して下さい。 - - @return If the url is supported by StudyplusSDK, returns YES. The valid URL has a "studyplus-{consumerKey}://" scheme, and right pathComponents and host.
- 渡されたurlがStudyplusSDKで対応すべきURL(スキームが"studyplus-{consumerKey}"であり、host/pathComponentsが想定内であるもの)であればYES、それ以外はNOを返します。 - */ -- (BOOL)openURL:(NSURL*)url; - -NS_ASSUME_NONNULL_END - -@end diff --git a/StudyplusSDK/SPLStudyplus.m b/StudyplusSDK/SPLStudyplus.m deleted file mode 100644 index 74947b5..0000000 --- a/StudyplusSDK/SPLStudyplus.m +++ /dev/null @@ -1,245 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#import "SPLStudyplus.h" -#import "SPLStudyplusAPIRequest.h" -#import "SPLStudyplusLogger.h" -#import "SPLStudyplusError.h" -#import "UICKeyChainStore.h" - -static NSString * const UsernameStoreKey = @"username"; -static NSString * const AccessTokenStoreKey = @"accessToken"; -static NSString * const AppStoreURL = @"https://itunes.apple.com/jp/app/mian-qiangga-leshiku-xuku!/id505410049?mt=8"; - -@interface SPLStudyplus() -@property (nonatomic, copy, readwrite) NSString *consumerKey; -@property (nonatomic, copy, readwrite) NSString *consumerSecret; -@property (nonatomic, copy, readwrite) NSString *username; -@property (nonatomic, copy, readwrite) NSString *accessToken; -@property (nonatomic, readwrite) SPLStopwatch *stopwatch; -@end - -@implementation SPLStudyplus - -+ (instancetype)studyplusWithConsumerKey:(NSString*)consumerKey - andConsumerSecret:(NSString*)consumerSecret -{ - return [[SPLStudyplus alloc] __initWithConsumerKey:consumerKey - andConsumerSecret:consumerSecret]; -} - -- (instancetype)__initWithConsumerKey:(NSString*)consumerKey - andConsumerSecret:(NSString*)consumerSecret -{ - - if (self = [super init]) { - self.consumerKey = consumerKey; - self.consumerSecret = consumerSecret; - self.username = nil; - self.accessToken = nil; - self.openAppStoreIfNotInstalled = YES; - self.apiVersion = 1; - self.debug = NO; - self.stopwatch = [SPLStopwatch new]; - } - - return self; -} - -- (NSString*)username -{ - return [[self keyChain] stringForKey:UsernameStoreKey]; -} - -- (NSString*)accessToken -{ - return [[self keyChain] stringForKey:AccessTokenStoreKey]; -} - -- (id)authWhenError:(NSError**)error -{ - return nil; -} - -- (BOOL)auth -{ - return [self openStudyplus:@"auth"]; -} - -- (BOOL)login -{ - return [self openStudyplus:@"login"]; -} - -- (void)logout -{ - UICKeyChainStore *keyChain = [self keyChain]; - [keyChain removeItemForKey:AccessTokenStoreKey]; - [keyChain removeItemForKey:UsernameStoreKey]; - [keyChain synchronize]; -} - -- (BOOL)isConnected -{ - return self.accessToken != nil; -} - -- (void)postStudyRecord:(SPLStudyplusRecord *)studyplusRecord -{ - if (self.debug) { - if ([self.delegate respondsToSelector:@selector(studyplusDidPostStudyRecord:)]) { - [self.delegate studyplusDidPostStudyRecord:self]; - } - return; - } - - if (![self isConnected]) { - if ([self.delegate respondsToSelector:@selector(studyplusDidFailToPostStudyRecord:withError:)]) { - [self.delegate studyplusDidFailToPostStudyRecord:self withError:[SPLStudyplusError errorFromStudyplusErrorCode:SPLErrorCodeNotConnected]]; - } - - return; - } - - SPLStudyplusAPIRequest *request = [SPLStudyplusAPIRequest - newRequestWithAccessToken:self.accessToken - options:@{ - @"version": [NSNumber numberWithInteger:self.apiVersion], - }]; - - __block id __delegate = self.delegate; - - [request postRequestWithPath:@"study_records" - requestParameter:[studyplusRecord toRequestParam] - completed:^(NSDictionary *responseParameter) { - if ([__delegate respondsToSelector:@selector(studyplusDidPostStudyRecord:)]) { - [__delegate studyplusDidPostStudyRecord:self]; - } - } failed:^(NSError *error) { - if ([__delegate respondsToSelector:@selector(studyplusDidFailToPostStudyRecord:withError:)]) { - [__delegate studyplusDidFailToPostStudyRecord:self withError:error]; - } - }]; -} - -- (BOOL)openURL:(NSURL*)url -{ - if (![self isAcceptableURL:url]) { - return NO; - } - - if ([url.pathComponents[1] isEqualToString:@"success"]) { - NSString *accessToken = [url.pathComponents[2] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; - NSString *username = [url.pathComponents[3] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; - [self saveAccessToken:accessToken andUsername:username]; - [self.delegate studyplusDidConnect:self]; - } else if ([url.pathComponents[1] isEqualToString:@"fail"]) { - NSInteger studyplusErrorCode = [url.pathComponents[2] integerValue]; - [self.delegate studyplusDidFailToConnect:self - withError:[SPLStudyplusError - errorFromStudyplusErrorCode:studyplusErrorCode]]; - } else if ([url.pathComponents[1] isEqualToString:@"cancel"]) { - if ([self.delegate respondsToSelector:@selector(studyplusDidCancel:)]) { - [self.delegate studyplusDidCancel:self]; - } - } else { - StudyplusSDKLog(@"Unknown format : %@", [url absoluteString]); - return NO; - } - - return YES; -} - -#pragma mark - privates - -- (id)init -{ - @throw [NSException exceptionWithName:NSInternalInconsistencyException - reason:@"-init method is not available." - userInfo:nil]; - return nil; -} - -- (void)saveAccessToken:(NSString*)accessToken andUsername:(NSString*)username -{ - UICKeyChainStore *keyChain = [self keyChain]; - [keyChain setString:accessToken forKey:AccessTokenStoreKey]; - [keyChain setString:username forKey:UsernameStoreKey]; - [keyChain synchronize]; -} - -- (NSString*)urlScheme -{ - return [NSString stringWithFormat:@"studyplus-%@", self.consumerKey]; -} - -- (BOOL)openStudyplus:(NSString*)command -{ - NSString *urlString = [NSString stringWithFormat: - @"studyplus://external_app/%@/%@/%@", - command, - self.consumerKey, - self.consumerSecret - ]; - NSURL *url = [NSURL URLWithString:urlString]; - - BOOL isStudyplusOpened = [UIApplication.sharedApplication openURL:url]; - if (isStudyplusOpened) { - return YES; - } - - // Studyplus app is not installed. - - if (self.openAppStoreIfNotInstalled) { - NSURL *url = [NSURL URLWithString:AppStoreURL]; - [[UIApplication sharedApplication] openURL:url]; - } - - return NO; -} - -- (UICKeyChainStore*)keyChain -{ - NSString *keyChainServiceName = [NSString stringWithFormat:@"Studyplus_iOS_SDK_%@", self.consumerKey]; - return [UICKeyChainStore keyChainStoreWithService:keyChainServiceName]; -} - -- (BOOL)isAcceptableURL:(NSURL*)url -{ - if (![url.scheme isEqualToString:[self urlScheme]] - || !url.host - || !url.pathComponents) { - return NO; - } - - BOOL isAuthResult = [url.host isEqualToString:@"auth-result"]; - BOOL isLoginResult = [url.host isEqualToString:@"login-result"]; - if (!isAuthResult && !isLoginResult) { - return NO; - } - - return YES; -} - -@end diff --git a/StudyplusSDK/SPLStudyplusAPIRequest.m b/StudyplusSDK/SPLStudyplusAPIRequest.m deleted file mode 100644 index 90ec71d..0000000 --- a/StudyplusSDK/SPLStudyplusAPIRequest.m +++ /dev/null @@ -1,122 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFNetworking.h" -#import "SPLStudyplusAPIRequest.h" -#import "SPLStudyplusLogger.h" -#import "SPLStudyplusError.h" - -@interface SPLStudyplusAPIRequest() -@property (nonatomic, readonly) NSString *accessToken; -@property (nonatomic, readonly) NSInteger apiVersion; -@end - -static NSString * const ApiBaseURL = @"https://external-api.studyplus.jp/"; -static NSInteger const ApiDefaultVersion = 1; - -@implementation SPLStudyplusAPIRequest - -- (instancetype)init -{ - if (self = [super init]) { - _accessToken = nil; - } - return self; -} - -+ (instancetype)newRequestWithAccessToken:(NSString*)accessToken - options:(NSDictionary*)options -{ - return [[SPLStudyplusAPIRequest alloc] initWithAccessToken:accessToken - options:options]; -} - -- (instancetype)initWithAccessToken:(NSString*)accessToken - options:(NSDictionary*)options -{ - if (self = [super init]) { - _accessToken = accessToken; - _apiVersion = options[@"version"] ? [options[@"version"] integerValue] : ApiDefaultVersion; - } - return self; -} - -- (void)postRequestWithPath:(NSString *)path - requestParameter:(NSDictionary *)requestParameter - completed:(void(^)(NSDictionary *response))completed - failed:(void(^)(NSError *error))failed -{ - [self sendRequestWithPath:path - requestParams:requestParameter - completed:completed - failed:^(NSInteger httpStatusCode, NSError *error) { - if (error) { - failed(error); - } else { - failed([SPLStudyplusError errorFromStudyRecordPostStatusCode:httpStatusCode]); - } - }]; -} - -- (void)sendRequestWithPath:(NSString*)path - requestParams:(NSDictionary *)requestParams - completed:(void(^)(NSDictionary *response))completed - failed:(void(^)(NSInteger httpStatusCode, NSError *error))failed -{ - AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer]; - AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer]; - [requestSerializer setValue:[NSString stringWithFormat:@"OAuth %@", self.accessToken] - forHTTPHeaderField:@"HTTP_AUTHORIZATION"]; - - AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; - manager.requestSerializer = requestSerializer; - manager.responseSerializer = responseSerializer; - - [manager POST:[self buildUrlFromPath:path] parameters:requestParams progress:^(NSProgress * _Nonnull uploadProgress) { - } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { - NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject - options:NSJSONReadingAllowFragments - error:nil]; - StudyplusSDKLog(@"response: %@", response); - completed(response); - } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { - StudyplusSDKLog(@"Error: %@", error); - NSHTTPURLResponse *res = (NSHTTPURLResponse *)task.response; - failed(res.statusCode, error); - }]; -} - -- (NSString *)apiBaseURL -{ -#ifdef STUDYPLUS_API_URL - return STUDYPLUS_API_URL; -#else - return ApiBaseURL; -#endif -} - -- (NSString *)buildUrlFromPath:(NSString *)path -{ - return [NSString stringWithFormat:@"%@v%ld/%@", [self apiBaseURL], (long)self.apiVersion, path]; -} - -@end diff --git a/StudyplusSDK/SPLStudyplusDelegate.h b/StudyplusSDK/SPLStudyplusDelegate.h deleted file mode 100644 index 5ab0f88..0000000 --- a/StudyplusSDK/SPLStudyplusDelegate.h +++ /dev/null @@ -1,85 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -@class SPLStudyplus; - -/** - The delegate to receive callbacks from SPLStudyplus. - - SPLStudyplusオブジェクトに対する各種操作後のコールバックを受けるdelegateです。 - */ -@protocol SPLStudyplusDelegate - -/** - Will be called after the SPLStudyplus#login or SPLStudyplus#auth was successful.
- SPLStudyplus#auth または SPLStudyplus#login が成功した後に呼ばれます。 - - @param studyplus SPLStudyplus object.
- SPLStudyplusオブジェクトです。 - */ -- (void)studyplusDidConnect:(SPLStudyplus*)studyplus; - -/** - Will be called after the SPLStudyplus#login or SPLStudyplus#auth was failure.
- SPLStudyplus#auth または SPLStudyplus#login が失敗した後に呼ばれます。 - - @param studyplus Studyplus object.
- Studyplusオブジェクトです。 - @param error Error object including failure reason.
- 失敗の理由を持つエラーオブジェクトです。 - @see StudyplusError.h - */ -- (void)studyplusDidFailToConnect:(SPLStudyplus*)studyplus withError:(NSError*)error; - -@optional - -/** - Will be called after the SPLStudyplus#login or SPLStudyplus#auth was cancelled.
- SPLStudyplus#auth または SPLStudyplus#login がキャンセルされた後に呼ばれます。 - - @param studyplus SPLStudyplus object.
- SPLStudyplusオブジェクトです。 - */ -- (void)studyplusDidCancel:(SPLStudyplus*)studyplus; - -/** - Will be called after the SPLStudyplus#postStudyRecord was successful.
- SPLStudyplus#postStudyRecord: が成功した後に呼ばれます。 - - @param studyplus SPLStudyplus object.
- SPLStudyplusオブジェクトです。 - */ -- (void)studyplusDidPostStudyRecord:(SPLStudyplus*)studyplus; - -/** - Will be called after the SPLStudyplus#postStudyRecord was failure. If this method is called, study record was not posted.
- SPLStudyplus#postStudyRecord: が失敗した後に呼ばれます。このメソッドが呼ばれた場合、勉強ログは投稿されていません。 - - @param error Error object including failure reason.
- 失敗の理由を持つエラーオブジェクトです。 - @see SPLStudyplusError - */ -- (void)studyplusDidFailToPostStudyRecord:(SPLStudyplus*)studyplus withError:(NSError*)error; - -@end diff --git a/StudyplusSDK/SPLStudyplusError.m b/StudyplusSDK/SPLStudyplusError.m deleted file mode 100644 index 52132ed..0000000 --- a/StudyplusSDK/SPLStudyplusError.m +++ /dev/null @@ -1,139 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "SPLStudyplusError.h" -#import "SPLStudyplusLogger.h" - -static NSString* const ErrorDomain = @"jp.studyplus.sdk"; - -@implementation SPLStudyplusError - -+ (NSError*)errorFromStudyplusErrorCode:(SPLErrorCode)studyplusErrorCode -{ - NSError *error; - switch (studyplusErrorCode) { - case SPLErrorCodeGetAppDescription: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Failed to get information about application. (400 bad request)"]; - break; - - case SPLErrorCodeAuthFailed: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Failed to authorize Studyplus user. (400 bad request)"]; - break; - - case SPLErrorCodeLoginFailed: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Failed to login to Studyplus. (400 bad request)"]; - break; - - case SPLErrorCodeStudyplusInMaintenance: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Maybe Studyplus is in temporary maintenance."]; - break; - - case SPLErrorCodeInvalidStudyplusSession: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Studyplus session is invalid."]; - break; - - case SPLErrorCodeNetworkUnavailable: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Network is not available."]; - break; - - case SPLErrorCodeServerError: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Some error(s) occurred in Studyplus server."]; - break; - - case SPLErrorCodePostRecordFailed: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Failed to post study record. (400 bad request)"]; - break; - - case SPLErrorCodeNotConnected: - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:@"Not Connected"]; - break; - - case SPLErrorCodeUnknown: - error = [SPLStudyplusError errorWithCode:SPLErrorCodeUnknown - localizedDescription:@"Unknown Error."]; - break; - default: - StudyplusSDKLog(@"Unexpected Studyplus status:[%ld]", (long)studyplusErrorCode); - error = [SPLStudyplusError errorWithCode:studyplusErrorCode - localizedDescription:[NSString - stringWithFormat:@"Unexpected Error(errorCode:[%ld]).", - (long)studyplusErrorCode]]; - break; - } - return error; -} - -+ (NSError*)errorFromStudyRecordPostStatusCode:(NSInteger)httpStatusCode -{ - if (httpStatusCode < 400 || 599 < httpStatusCode) { - // no error - return nil; - } - - NSError *error; - switch (httpStatusCode) { - case 400: - error = [SPLStudyplusError - errorFromStudyplusErrorCode:SPLErrorCodePostRecordFailed]; - break; - - case 401: - error = [SPLStudyplusError - errorFromStudyplusErrorCode:SPLErrorCodeInvalidStudyplusSession]; - break; - - case 500: - error = [SPLStudyplusError - errorFromStudyplusErrorCode:SPLErrorCodeServerError]; - - break; - case 503: - error = [SPLStudyplusError - errorFromStudyplusErrorCode:SPLErrorCodeStudyplusInMaintenance]; - break; - - default: - StudyplusSDKLog(@"Unexpected http status:[%ld]", (long)httpStatusCode); - error = [SPLStudyplusError - errorFromStudyplusErrorCode:SPLErrorCodeUnknown]; - break; - } - return error; -} - -+ (NSError*)errorWithCode:(SPLErrorCode)errorCode localizedDescription:(NSString*)localizedDescription -{ - return [NSError errorWithDomain:ErrorDomain - code:errorCode - userInfo:@{NSLocalizedDescriptionKey:localizedDescription}]; -} - -@end diff --git a/StudyplusSDK/SPLStudyplusRecord.h b/StudyplusSDK/SPLStudyplusRecord.h deleted file mode 100644 index bfdcb21..0000000 --- a/StudyplusSDK/SPLStudyplusRecord.h +++ /dev/null @@ -1,101 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -NS_ASSUME_NONNULL_BEGIN - -@class SPLStudyplusRecordAmount; - -/** - Study record object to post to Studyplus.
- Studyplusに投稿する一件の勉強記録を表現するクラスです。 - */ -@interface SPLStudyplusRecord : NSObject - -/** - The seconds of the learning.
- 勉強した時間(秒数)です。 - */ -@property (nonatomic, readonly) NSTimeInterval duration; - -/** - The date and time of learning.
- 勉強した日時です。 - */ -@property (nonatomic, readonly) NSDate *recordedAt; - -/** - The amount of learning.
- 勉強した量です。 - - @see StudyplusRecordAmount - */ -@property (nonatomic, readonly) SPLStudyplusRecordAmount *recordAmount; - -/** - The comment of learning.
- 勉強に関するコメントです。 - */ -@property (nonatomic, readonly, nullable) NSString *comment; - -/** - Creates and returns StudyplusRecord object that has number of seconds, no amount, and empty comment.
- 学習時間のみを指定した勉強記録オブジェクトを作成し、返します。学習量とコメントは無しです。 - - @param duration Specify the seconds of the learning.
- 勉強した時間(秒数)を指定してください。 - - @result StudyplusRecord object. - */ -+ (instancetype)recordWithDuration:(NSTimeInterval)duration; - -/** - Creates and returns StudyplusRecord object that has number of seconds and other attributes. - 学習時間とその他のオプション属性を指定した勉強記録オブジェクトを作成し、返します。 - - @param duration Specify the seconds of the learning.
- 勉強した時間(秒数)を指定してください。 - - @param options Dictionary with amount:StudyplusRecordAmount, comment:NSString, recordedAt:NSDate.
- // example.
- @{
- // @see StudyplusRecordAmount
- @"amount": [StudyplusRecordAmount amountAsRangeWithFrom:10 to:33],
- // Time the learning is ended. 学習を終えた日時。
- @"recordedAt": [NSDate date],
- // Studyplus timeline comment. Studyplusのタイムライン上で表示されるコメント。
- @"comment": @"アプリ◯◯で勉強しました!",
- }
- - @result StudyplusRecord object. - */ -+ (instancetype)recordWithDuration:(NSTimeInterval)duration options:(NSDictionary* _Nullable)options; - -/** - @result Returns the parameters of the study record for posting API - */ -- (NSDictionary*)toRequestParam; - -NS_ASSUME_NONNULL_END - -@end diff --git a/StudyplusSDK/SPLStudyplusRecord.m b/StudyplusSDK/SPLStudyplusRecord.m deleted file mode 100644 index a4c062d..0000000 --- a/StudyplusSDK/SPLStudyplusRecord.m +++ /dev/null @@ -1,104 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "SPLStudyplusRecord.h" -#import "SPLStudyplusRecordAmount.h" - -@interface NSDate(Formattable) -- (NSString*)toString:(NSString*)format; -@end - -@interface NSDictionary(GetOrElse) -- (id)getKey:(NSString*)key orElse:(id)elseValue; -@end - -@implementation SPLStudyplusRecord - -+ (instancetype)recordWithDuration:(NSTimeInterval)duration -{ - return [self recordWithDuration:duration options:@{}]; -} - -+ (instancetype)recordWithDuration: (NSTimeInterval)duration options:(NSDictionary*)options -{ - return [[[self class] alloc] initWithDuration:duration options:options]; -} - -- (id)getKey:(NSString *)key from:(NSDictionary *)dict orElse:(id)elseValue -{ - id value = dict[key]; - if (value == [NSNull null] || value == nil) { - value = elseValue; - } - return value; -} - -- (instancetype)initWithDuration:(NSTimeInterval)duration options:(NSDictionary*)options -{ - if (self = [super init]) { - _duration = duration; - _recordAmount = [options getKey:@"amount" orElse:[SPLStudyplusRecordAmount amountAsNone]]; - _recordedAt = [options getKey:@"recordedAt" orElse:[NSDate date]]; - _comment = [options getKey:@"comment" orElse:nil]; - } - return self; -} - -- (NSDictionary*)toRequestParam -{ - NSMutableDictionary *param = [NSMutableDictionary new]; - param[@"duration"] = [NSNumber numberWithDouble:self.duration]; - param[@"recorded_at"] = [self.recordedAt toString:@"yyyy-MM-dd HH:mm:ss"]; - if (self.comment != nil) { - param[@"comment"] = self.comment; - } - for (NSString *key in self.recordAmount.toRequestParameter) { - param[key] = self.recordAmount.toRequestParameter[key]; - } - return (NSDictionary*)param; -} - -@end - -@implementation NSDate(Formattable) -- (NSString*)toString:(NSString*)format -{ - NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; - [formatter setLocale:[NSLocale systemLocale]]; - [formatter setTimeZone:[NSTimeZone systemTimeZone]]; - [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; - [formatter setDateFormat:format]; - [formatter setCalendar:[[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]]; - return [formatter stringFromDate:self]; -} -@end - -@implementation NSDictionary(GetOrElse) -- (id)getKey:(NSString *)key orElse:(id)elseValue -{ - id value = self[key]; - if (value == [NSNull null] || value == nil) { - value = elseValue; - } - return value; -} -@end \ No newline at end of file diff --git a/StudyplusSDK/SPLStudyplusRecordAmount.h b/StudyplusSDK/SPLStudyplusRecordAmount.h deleted file mode 100644 index 196a944..0000000 --- a/StudyplusSDK/SPLStudyplusRecordAmount.h +++ /dev/null @@ -1,66 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -NS_ASSUME_NONNULL_BEGIN - -/** - The class that represents the amount of learning.
- 学習量を表すクラスです。 - */ -@interface SPLStudyplusRecordAmount : NSObject - -/** - Creates and returns the Amount object with only the total amount of learning.
- 合計の学習量のみを持つAmountオブジェクトを生成して返します。 - - @param amount 学習量。 - @result SPLStudyplusRecordAmount* 生成したAmountオブジェクトです。 - */ -+ (instancetype)amount:(NSUInteger)amount; - -/** - Creates and returns the Amount object with a range of learning amount.
- 学習量を範囲で持つAmountオブジェクトを生成して返します。 - - @param from 学習量の起点。 - @param to 学習量の終点。 - @result SPLStudyplusRecordAmount* 生成したAmountオブジェクトです。 - */ -+ (instancetype)amountAsRangeWithFrom:(NSUInteger)from to:(NSUInteger)to; - -/** - Creates and returns the Amount object that has no learning amount.
- 学習量を持たないAmountオブジェクトを生成して返します。 - @result SPLStudyplusRecordAmount* 生成したAmountオブジェクトです。 - */ -+ (instancetype)amountAsNone; - -/** - @result Returns the parameters of the study record for posting API - */ -- (NSDictionary*)toRequestParameter; - -NS_ASSUME_NONNULL_END - -@end diff --git a/StudyplusSDK/SPLStudyplusRecordAmount.m b/StudyplusSDK/SPLStudyplusRecordAmount.m deleted file mode 100644 index 207b05a..0000000 --- a/StudyplusSDK/SPLStudyplusRecordAmount.m +++ /dev/null @@ -1,80 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "SPLStudyplusRecordAmount.h" - -@interface SPLStudyplusRecordAmount() -@property (nonatomic, readonly) NSDictionary *requestParameter; -@end - -@implementation SPLStudyplusRecordAmount - -+ (instancetype)amount:(NSUInteger)amount -{ - return [[[self class] alloc] initAsAmount:amount]; -} - -- (instancetype)initAsAmount:(NSUInteger)amount -{ - if (self = [super init]) { - _requestParameter = @{ - @"amount": [NSNumber numberWithUnsignedInteger:amount], - }; - } - return self; -} - -+ (instancetype)amountAsRangeWithFrom:(NSUInteger)from to:(NSUInteger)to -{ - return [[[self class] alloc] initAsRangeWithFrom:from to:to]; -} - -- (instancetype)initAsRangeWithFrom:(NSUInteger)from to:(NSUInteger)to -{ - if (self = [super init]) { - _requestParameter = @{ - @"start_position": [NSNumber numberWithUnsignedInteger:from], - @"end_position": [NSNumber numberWithUnsignedInteger:to], - }; - } - return self; -} - -+ (instancetype)amountAsNone -{ - return [[[self class] alloc] initAsNone]; -} - -- (instancetype)initAsNone -{ - if (self = [super init]) { - _requestParameter = @{}; - } - return self; -} - -- (NSDictionary*)toRequestParameter -{ - return _requestParameter; -} - -@end diff --git a/StudyplusSDK/StudyplusSDK-Prefix.pch b/StudyplusSDK/StudyplusSDK-Prefix.pch deleted file mode 100644 index eb2007e..0000000 --- a/StudyplusSDK/StudyplusSDK-Prefix.pch +++ /dev/null @@ -1,9 +0,0 @@ -// -// Prefix header -// -// The contents of this file are implicitly included at the beginning of every source file. -// - -#ifdef __OBJC__ - #import -#endif diff --git a/StudyplusSDKTests/StudyplusRecordTests.m b/StudyplusSDKTests/StudyplusRecordTests.m deleted file mode 100644 index 343e159..0000000 --- a/StudyplusSDKTests/StudyplusRecordTests.m +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) 2013年 studyplus.jp. All rights reserved. - -#import "Kiwi.h" -#import "SPLStudyplusRecord.h" -#import "SPLStudyplusRecordAmount.h" - -SPEC_BEGIN(StudyplusRecordTest) - -describe(@"StudyplusRecord", ^{ - describe(@"toRequestParam", ^{ - - it(@"returns NSDictionary", ^{ - SPLStudyplusRecord *record = [SPLStudyplusRecord recordWithDuration:100]; - [[record.toRequestParam should] beKindOfClass:[NSDictionary class]]; - }); - - context(@"record has duration only", ^{ - SPLStudyplusRecord *record = [SPLStudyplusRecord recordWithDuration:100]; - NSDictionary *requestParams = record.toRequestParam; - - it(@"returns specified duration with default recordedAt", ^{ - [[[requestParams should] have:2] items]; - [[requestParams[@"duration"] should] equal:@100]; - [[requestParams[@"recorded_at"] should] matchPattern:@"\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"]; - - }); - }); - - context(@"record has duration and comment", ^{ - SPLStudyplusRecord *record = [SPLStudyplusRecord recordWithDuration:100 - options:@{ - @"comment": - @" (_`Д´), ○=(゚皿´メ), (○`⊿´)" - }]; - NSDictionary *requestParams = record.toRequestParam; - - it(@"returns specified duration with specified comment", ^{ - [[[requestParams should] have:3] items]; - [[requestParams[@"duration"] should] equal:@100]; - [[requestParams[@"recorded_at"] should] matchPattern:@"\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"]; - [[requestParams[@"comment"] should] equal:@" (_`Д´), ○=(゚皿´メ), (○`⊿´)"]; - }); - }); - - context(@"record has duration and amount", ^{ - SPLStudyplusRecord *record = [SPLStudyplusRecord recordWithDuration:100 - options:@{ - @"amount":[SPLStudyplusRecordAmount amount:999], - }]; - NSDictionary *requestParams = record.toRequestParam; - - it(@"returns specified duration with specified amount", ^{ - [[[requestParams should] have:3] items]; - [[requestParams[@"duration"] should] equal:@100]; - [[requestParams[@"recorded_at"] should] matchPattern:@"\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"]; - [[requestParams[@"amount"] should] equal:@999]; - }); - }); - - context(@"record has duration and amount as range", ^{ - SPLStudyplusRecord *record = [SPLStudyplusRecord recordWithDuration:100 - options:@{ - @"amount":[SPLStudyplusRecordAmount - amountAsRangeWithFrom:90 to:91], - }]; - NSDictionary *requestParams = record.toRequestParam; - - it(@"returns specified duration with specified amount", ^{ - [[[requestParams should] have:4] items]; - [[requestParams[@"duration"] should] equal:@100]; - [[requestParams[@"recorded_at"] should] matchPattern:@"\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"]; - [[requestParams[@"start_position"] should] equal:@90]; - [[requestParams[@"end_position"] should] equal:@91]; - }); - }); - - }); -}); - -SPEC_END diff --git a/StudyplusSDKTests/StudyplusTests.m b/StudyplusSDKTests/StudyplusTests.m deleted file mode 100644 index 4e8a175..0000000 --- a/StudyplusSDKTests/StudyplusTests.m +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) 2013年 studyplus.jp. All rights reserved. - -#import "Kiwi.h" -#import "SPLStudyplus.h" - -SPEC_BEGIN(SPLStudyplusTest) - -describe(NSStringFromClass([SPLStudyplus class]), ^{ - - describe(@"studyplusWithConsumerKey:consumerSecret:", ^{ - - context(@"consumerKey and consumerSecret are specified", ^{ - SPLStudyplus *sp = [SPLStudyplus studyplusWithConsumerKey:@"cKey" andConsumerSecret:@"cSecret"]; - - it(@"returns Studyplus object with specified values", ^{ - [[sp should] beKindOfClass:[SPLStudyplus class]]; - [[sp.consumerKey should] equal:@"cKey"]; - [[sp.consumerSecret should] equal:@"cSecret"]; - }); - }); - - context(@"consumerKey is not specified", ^{ - SPLStudyplus *sp = [SPLStudyplus studyplusWithConsumerKey:nil andConsumerSecret:@"cSecret"]; - - it(@"returns Studyplus object with nil consumerKey", ^{ - [[sp should] beKindOfClass:[SPLStudyplus class]]; - [[sp.consumerKey should] beNil]; - [[sp.consumerSecret should] equal:@"cSecret"]; - }); - }); - - context(@"consumerSecret is not specified", ^{ - SPLStudyplus *sp = [SPLStudyplus studyplusWithConsumerKey:@"cKey" andConsumerSecret:nil]; - - it(@"returns Studyplus object with nil consumerSecret", ^{ - [[sp should] beKindOfClass:[SPLStudyplus class]]; - [[sp.consumerKey should] equal:@"cKey"]; - [[sp.consumerSecret should] beNil]; - }); - }); - - }); -}); - -SPEC_END diff --git a/StudyplusSDKTests/en.lproj/InfoPlist.strings b/StudyplusSDKTests/en.lproj/InfoPlist.strings deleted file mode 100644 index 477b28f..0000000 --- a/StudyplusSDKTests/en.lproj/InfoPlist.strings +++ /dev/null @@ -1,2 +0,0 @@ -/* Localized versions of Info.plist keys */ - diff --git a/build/Debug/deliverables/StudyplusSDK.zip b/build/Debug/deliverables/StudyplusSDK.zip deleted file mode 100644 index e260452..0000000 Binary files a/build/Debug/deliverables/StudyplusSDK.zip and /dev/null differ diff --git a/build/Debug/deliverables/StudyplusSDK/README.md b/build/Debug/deliverables/StudyplusSDK/README.md deleted file mode 100644 index edf4fe1..0000000 --- a/build/Debug/deliverables/StudyplusSDK/README.md +++ /dev/null @@ -1,192 +0,0 @@ -StudyplusSDK -======= - -Studyplus iOS SDK - -## Requirements - - * iOS 6.0 or above - * Xcode command line tools - * ARC - * [Studyplus iOS App 3.10.0 or adove](https://itunes.apple.com/jp/app/mian-qiangga-leshiku-xuku!/id505410049?mt=8) - * CocoaPods (Optional, but recommended) - -## Dependency - * [AFNetworking](https://github.com/AFNetworking/AFNetworking) - * [UICKeyChainStore](https://github.com/kishikawakatsumi/UICKeyChainStore) - -## Install - -### CocoaPods (Recommended) - -```ruby -# Edit your podfile -platform :ios, '6.0' -pod 'StudyplusSDK' -``` -and run -```pod install ``` - -### Manual install - -#### By library and headers - -1. Get StudyplusSDK. - * ```git clone https://github.com/studyplus/Studyplus-iOS-SDK``` or download zip from [this page](https://github.com/studyplus/Studyplus-iOS-SDK/releases). -2. Copy ```build/Release/deliverables/StudyplusSDK``` to your project. -3. Install [AFNetworking](https://github.com/AFNetworking/AFNetworking) and [UICKeyChainStore](https://github.com/kishikawakatsumi/UICKeyChainStore) too. -4. Add required frameworks(i.e. ```Security.framework, SystemConfiguration.framework, MobileCoreServices, CoreGraphics``` etc). See [AFNetworking](https://github.com/AFNetworking/AFNetworking) and [UICKeyChainStore](https://github.com/kishikawakatsumi/UICKeyChainStore). - -#### By source copy (iOS 7 required) - -1. Get StudyplusSDK - * ```git clone https://github.com/studyplus/Studyplus-iOS-SDK``` or download zip from [this page](https://github.com/studyplus/Studyplus-iOS-SDK/releases). -2. Copy Studyplus-iOS-SDK/StudyplusSDK directory to your project. -3. Install [AFNetworking](https://github.com/AFNetworking/AFNetworking) and [UICKeyChainStore](https://github.com/kishikawakatsumi/UICKeyChainStore) too. - -## Usage - -### Set up custom URL scheme - -set "studyplus-*{your consumer key}*" to URL Types. - -![xcode](https://raw.github.com/studyplus/Studyplus-iOS-SDK/master/docs/set_url_scheme.png) - -### Initialize - -```Objective-C -#import "SPLStudyplusDelegate.h" - -@interface YourClass --(BOOL)openURL:(NSURL*)url; -@end -``` - -```Objective-C -#import "SPLStudyplus.h" - -static NSString * const ConsumerKey = @"Your Studyplus consumer key"; -static NSString * const ConsumerSecret = @"Your Studyplus consumer secret"; - -@implementation YourClass -{ - SPLStudyplus *studyplus; -} - --(id) init { - - if (self = [super init]) { - studyplus = [SPLStudyplus studyplusWithConsumerKey:ConsumerKey - andConsumerSecret:ConsumerSecret]; - studyplus.delegate = self; - } - return self; -} -``` - -### Auth or Login -```Objective-C -@implementation AppDelegate - -- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation -{ - return [yourClassObject openURL:url]; -} -``` - -```Objective-C -@interface YourClass --(BOOL)openURL:(NSURL*)url; -@end -``` - -```Objective-C -@implementation YourClass - --(void) doAuth { - [studyplus auth]; -} - --(void) doLogin -{ - [studyplus login]; -} - -// Called by AppDelegate --(BOOL) openURL:(NSURL*)url -{ - return [studyplus openURL:url]; -} - -// callback methods --(void)studyplusDidConnect:(SPLStudyplus*)studyplus -{ - NSLog(@"Auth or Login succeeded"); -} - --(void)studyplusDidFailToConnect:(SPLStudyplus*)studyplus withError:(NSError*)error -{ - NSLog(@"Auth or Login failed"); -} - -- (void)studyplusDidCancel:(SPLStudyplus*)studyplus -{ - NSLog(@"Auth or Login canceled"); -} -``` - -### Post study record to Studyplus - -```Objective-C --(void)post -{ - - // Create new study record. - SPLStudyplusRecord *studyplusRecord = - [SPLStudyplusRecord - - /** - @see SPLStopwatch - */ - recordWithDuration:[studyplus.stopwatch elapsedSeconds] - - /** You can add optional info. - options:@{ - // Time the learning is ended. 学習を終えた日時。 - @"recordedAt" : [NSDate date], - // Studyplus timeline comment. Studyplusのタイムライン上で表示されるコメント。 - @"comment" : @"アプリ◯◯で勉強しました!!", - // @see SPLStudyplusRecordAmount - @"amount" : [SPLStudyplusRecordAmount amount:100], - } - */ - - ]; - - // post - [studyplus postStudyRecord:studyplusRecord]; - -} - -// callback methods --(void)studyplusDidPostStudyRecord:(SPLStudyplus*)studyplus -{ - NSLog(@"Post to Studyplus succeeded"); -} - --(void)studyplusDidFailToPostStudyRecord:(SPLStudyplus*)studyplus withError:(NSError*)error -{ - NSLog(@"Post to Studyplus failed"); -} -``` - -### More info about SDK interface - - * StudyplusSDK/SPLStudyplus.h - * StudyplusSDK/SPLStudyplusDelegate.h - * StudyplusSDK/SPLStudyplusRecord.h - * StudyplusSDK/SPLStudyplusRecordAmount.h - -## License - -[MIT License.](http://opensource.org/licenses/mit-license.php) diff --git a/build/Debug/deliverables/StudyplusSDK/SPLStopwatch.h b/build/Debug/deliverables/StudyplusSDK/SPLStopwatch.h deleted file mode 100644 index c1e82ca..0000000 --- a/build/Debug/deliverables/StudyplusSDK/SPLStopwatch.h +++ /dev/null @@ -1,55 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -/** - Simple stopwatch with [start/stop/reset] functions. Useful for measuring the learning duration.
- シンプルなストップウォッチです。学習時間(duration)を計測するのに便利です。 - */ -@interface SPLStopwatch : NSObject - -/** - Begin or resume measuring.
- 測定を開始または再開します。 - */ --(void)start; - -/** - Pause measuring. Elapsed seconds will not be reset.
- 測定を一時停止します。経過秒数はリセットされません。 - */ --(void)pause; - -/** - Reset elapsed seconds. Elapsed seconds will be 0, and measuring will not stop.
- 経過秒数を0にリセットします。測定中の場合、測定は止まりません。 - */ --(void)reset; - -/** - Returns total elapsed seconds.
- 現時点の累計経過秒数を返します。 - */ --(NSUInteger)elapsedSeconds; - -@end diff --git a/build/Debug/deliverables/StudyplusSDK/SPLStudyplus.h b/build/Debug/deliverables/StudyplusSDK/SPLStudyplus.h deleted file mode 100644 index 692393a..0000000 --- a/build/Debug/deliverables/StudyplusSDK/SPLStudyplus.h +++ /dev/null @@ -1,185 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "SPLStudyplusDelegate.h" -#import "SPLStudyplusRecord.h" -#import "SPLStudyplusRecordAmount.h" -#import "SPLStopwatch.h" - -/** - The class for using Studyplus.
- For example, you can authenticate in Studyplus account, de-authentication, and post study record. - - Studyplusの各機能を使うためのクラスです。
- Studyplusアカウントとの連携、連携解除、勉強記録の投稿ができます。 - */ -@interface SPLStudyplus : NSObject - -/** - The version of the StudyplusAPI. Default value is 1.
- StudyplusAPI のバージョンを指定します。デフォルトは 1 です。 - - https://external-api.studyplus.jp/v{apiVersion}/endpoint_name - */ -@property (nonatomic) NSInteger apiVersion; - -/** - Debug mode switch.
- When set to YES, then call back to the delegate without posting the actual processing.
- Default value is NO. - - StudyplusAPI のバージョンを指定します。
- debug=YESの場合、勉強記録の投稿時に実際の通信は行わずdelegateのコールバックメソッドを呼び出して処理を終了します。 - */ -@property (nonatomic) BOOL debug; - -/** - StudyplusAPI用のConsumer Keyです。
- Consumer Key for Studyplus API. - */ -@property (nonatomic, copy, readonly) NSString *consumerKey; - -/** - StudyplusAPI用のConsumer Secretです。
- Consumer Secret for Studyplus API. - */ -@property (nonatomic, copy, readonly) NSString *consumerSecret; - -/** - @see SPLStudyplusDelegate protocol - */ -@property (nonatomic, weak) id delegate; - -/** - When set to YES, if Studyplus is not installed, AppStore application starts when auth/login methods are called. Default value is YES.
- YESに設定すると、auth、loginメソッドを呼び出したとき、StudyplusアプリがインストールされていなければAppStoreを起動します。デフォルトは YES です。 - */ -@property (nonatomic) BOOL openAppStoreIfNotInstalled; - -/** - Username of Studyplus account. It is set when the auth or login is successful. Default value is nil.
- Studyplusアカウントのユーザ名です。login または authが成功したとき設定されます。設定されるまではnilです。 - */ -@property (nonatomic, copy, readonly) NSString *username; - -/** - Access token of Studyplus API. It is set when the auth or login is successful. Default value is nil.
- StudyplusAPIのアクセストークンです。login または authが成功したとき設定されます。設定されるまではnilです。 - */ -@property (nonatomic, copy, readonly) NSString *accessToken; - -/** - @see SPLStopwatch class - */ -@property (nonatomic, readonly) SPLStopwatch *stopwatch; - -/** - The convenience constructor of SPLStudyplus class. - - SPLStudyplusクラスのオブジェクトを生成して返します。 - - @param consumerKey Specify a Consumer Key for StudyplusAPI.
- StudyplusAPI用のコンシューマキーを指定してください。 - - @param consumerSecret Specify a Consumer Secret for StudyplusAPI.
- StudyplusAPI用のコンシューマシークレットを指定してください。 - - @return SPLStudyplus object.
- SPLStudyplusオブジェクト。 - */ -+ (SPLStudyplus*)studyplusWithConsumerKey:(NSString*)consumerKey - andConsumerSecret:(NSString*)consumerSecret; - -/** - Opens the auth screen by invoking the Studyplus application. - - Studyplusアプリを起動して連携許可画面を開きます。 - - If Studyplus app is not installed and openAppStoreIfNotInstalled is YES, then open the Studyplus page in AppStore.
- If openAppStoreIfNotInstalled is NO, do nothing.
- After the process has returned from Studyplus application, delegate method will be called back. - - Studyplusアプリがインストールされていない場合、 openAppStoreIfNotInstalled がYESであれば、AppStoreを起動してStudyplusページを開きます。
- openAppStoreIfNotInstalled がNOであれば何もしません。
- Studyplusアプリから操作が戻ってきた後、delegateオブジェクトのコールバックメソッドを呼び出します。 - - @return It returns YES when you started Studyplus application. If Studyplus application is not installed, it returns NO.
- Studyplusアプリが起動した時点でYESを返します。Studyplusアプリがインストールされていない場合、NOを返します。 - */ -- (BOOL)auth; - -/** - Opens the login screen by invoking the Studyplus application. - - Studyplusアプリを起動してStudyplusログイン画面を開きます。 - - If Studyplus app is not installed and openAppStoreIfNotInstalled is YES, then open the Studyplus page in AppStore.
- If openAppStoreIfNotInstalled is NO, do nothing.
- After the process has returned from Studyplus application, delegate method will be called back. - - Studyplusアプリがインストールされていない場合、 openAppStoreIfNotInstalled がYESであれば、AppStoreを起動してStudyplusページを開きます。
- openAppStoreIfNotInstalled がNOであれば何もしません。
- Studyplusアプリから操作が戻ってきた後、delegateオブジェクトのコールバックメソッドを呼び出します。 - - @return It returns YES when you started Studyplus application. If Studyplus application is not installed, it returns NO.
- Studyplusアプリが起動した時点でYESを返します。Studyplusアプリがインストールされていない場合、NOを返します。 - */ -- (BOOL)login; - -/** - Posts new study record to Studyplus.
- Studyplusに勉強記録を新規投稿します。 - - @param studyRecord @see SPLStudyplusRecord - */ -- (void)postStudyRecord:(SPLStudyplusRecord*)studyRecord; - -/** - Cancels the cooperation with Studyplus application.
- Studyplusアプリとの連携を解除します。 - */ -- (void)logout; - -/** - Returns to whether or not it is in conjunction with Studyplus application.
- Studyplusアプリと連携されているか否かを返します。 - */ -- (BOOL)isConnected; - -/** - It is responsible for processing custom URL scheme when it came back from the authorization / login screen of Stuudyplus app.
- After handling openURL method in AppDelegate, pass the url parameter to this method.
- If the URL is passed by Studyplus application, calls the callback method of the delegate object. - - Studyplusアプリの認可・ログイン画面から戻ってきた時のカスタムURLスキーム処理を担当します。
- AppDelegateでopenURLをハンドリングしてから、このメソッドにurlを渡して委譲してください。
- Studyplusアプリ関連のURLであれば、delegateオブジェクトのコールバックメソッドを呼び出します。 - - @param url The parameter of AppDelegate#openURL method.
- AppDelegate#openURLメソッドで受け取ったurlパラメータをそのまま渡して下さい。 - - @return If the url is supported by StudyplusSDK, returns YES. The valid URL has a "studyplus-{consumerKey}://" scheme, and right pathComponents and host.
- 渡されたurlがStudyplusSDKで対応すべきURL(スキームが"studyplus-{consumerKey}"であり、host/pathComponentsが想定内であるもの)であればYES、それ以外はNOを返します。 - */ -- (BOOL)openURL:(NSURL*)url; - -@end diff --git a/build/Debug/deliverables/StudyplusSDK/SPLStudyplusAPIRequest.h b/build/Debug/deliverables/StudyplusSDK/SPLStudyplusAPIRequest.h deleted file mode 100644 index 4ee1987..0000000 --- a/build/Debug/deliverables/StudyplusSDK/SPLStudyplusAPIRequest.h +++ /dev/null @@ -1,35 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -@interface SPLStudyplusAPIRequest : NSObject - -+ (SPLStudyplusAPIRequest*)newRequestWithAccessToken:(NSString*)accessToken - options:(NSDictionary*)options; - -- (void)postRequestWithPath:(NSString *)path - requestParameter:(NSDictionary *)requestParameter - completed:(void(^)(NSDictionary *response))completed - failed:(void(^)(NSError *error))failed; - -@end diff --git a/build/Debug/deliverables/StudyplusSDK/SPLStudyplusDelegate.h b/build/Debug/deliverables/StudyplusSDK/SPLStudyplusDelegate.h deleted file mode 100644 index 1345488..0000000 --- a/build/Debug/deliverables/StudyplusSDK/SPLStudyplusDelegate.h +++ /dev/null @@ -1,85 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -@class SPLStudyplus; - -/** - The delegate to receive callbacks from SPLStudyplus. - - SPLStudyplusオブジェクトに対する各種操作後のコールバックを受けるdelegateです。 - */ -@protocol SPLStudyplusDelegate - -/** - Will be called after the SPLStudyplus#login or SPLStudyplus#auth was successful.
- SPLStudyplus#auth または SPLStudyplus#login が成功した後に呼ばれます。 - - @param studyplus SPLStudyplus object.
- SPLStudyplusオブジェクトです。 - */ -- (void)studyplusDidConnect:(SPLStudyplus*)studyplus; - -/** - Will be called after the SPLStudyplus#login or SPLStudyplus#auth was failure.
- SPLStudyplus#auth または SPLStudyplus#login が失敗した後に呼ばれます。 - - @param studyplus Studyplus object.
- Studyplusオブジェクトです。 - @param error Error object including failure reason.
- 失敗の理由を持つエラーオブジェクトです。 - @see StudyplusNSError.h - */ -- (void)studyplusDidFailToConnect:(SPLStudyplus*)studyplus withError:(NSError*)error; - -@optional - -/** - Will be called after the SPLStudyplus#login or SPLStudyplus#auth was cancelled.
- SPLStudyplus#auth または SPLStudyplus#login がキャンセルされた後に呼ばれます。 - - @param studyplus SPLStudyplus object.
- SPLStudyplusオブジェクトです。 - */ -- (void)studyplusDidCancel:(SPLStudyplus*)studyplus; - -/** - Will be called after the SPLStudyplus#postStudyRecord was successful.
- SPLStudyplus#postStudyRecord: が成功した後に呼ばれます。 - - @param studyplus SPLStudyplus object.
- SPLStudyplusオブジェクトです。 - */ -- (void)studyplusDidPostStudyRecord:(SPLStudyplus*)studyplus; - -/** - Will be called after the SPLStudyplus#postStudyRecord was failure. If this method is called, study record was not posted.
- SPLStudyplus#postStudyRecord: が失敗した後に呼ばれます。このメソッドが呼ばれた場合、勉強ログは投稿されていません。 - - @param error Error object including failure reason.
- 失敗の理由を持つエラーオブジェクトです。 - @see SPLStudyplusError - */ -- (void)studyplusDidFailToPostStudyRecord:(SPLStudyplus*)studyplus withError:(NSError*)error; - -@end diff --git a/build/Debug/deliverables/StudyplusSDK/SPLStudyplusError.h b/build/Debug/deliverables/StudyplusSDK/SPLStudyplusError.h deleted file mode 100644 index 9061051..0000000 --- a/build/Debug/deliverables/StudyplusSDK/SPLStudyplusError.h +++ /dev/null @@ -1,42 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -typedef NS_ENUM(NSInteger, SPLErrorCode) { - SPLErrorCodeGetAppDescription = 1000, - SPLErrorCodeAuthFailed = 2000, - SPLErrorCodeLoginFailed = 3000, - SPLErrorCodeStudyplusInMaintenance = 4000, - SPLErrorCodeInvalidStudyplusSession = 5000, - SPLErrorCodeNetworkUnavailable = 6000, - SPLErrorCodeServerError = 7000, - SPLErrorCodePostRecordFailed = 8000, - SPLErrorCodeUnknown = 90000 -}; - -@interface SPLStudyplusError : NSObject - -+ (NSError*)errorFromStudyplusErrorCode:(SPLErrorCode)studyplusErrorCode; -+ (NSError*)errorFromStudyRecordPostStatusCode:(NSInteger)httpStatusCode; - -@end diff --git a/build/Debug/deliverables/StudyplusSDK/SPLStudyplusLogger.h b/build/Debug/deliverables/StudyplusSDK/SPLStudyplusLogger.h deleted file mode 100644 index ec6a93e..0000000 --- a/build/Debug/deliverables/StudyplusSDK/SPLStudyplusLogger.h +++ /dev/null @@ -1,25 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// This file's name must be synchronized with code in StudyplusSDK.podspec and StudyplusSDK-Prefix.pch - -#define StudyplusSDKLog(format, ...) NSLog((@"%s[L%d]" format), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) diff --git a/build/Debug/deliverables/StudyplusSDK/SPLStudyplusRecord.h b/build/Debug/deliverables/StudyplusSDK/SPLStudyplusRecord.h deleted file mode 100644 index d23052a..0000000 --- a/build/Debug/deliverables/StudyplusSDK/SPLStudyplusRecord.h +++ /dev/null @@ -1,97 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -@class SPLStudyplusRecordAmount; - -/** - Study record object to post to Studyplus.
- Studyplusに投稿する一件の勉強記録を表現するクラスです。 - */ -@interface SPLStudyplusRecord : NSObject - -/** - The seconds of the learning.
- 勉強した時間(秒数)です。 - */ -@property (nonatomic, readonly) NSTimeInterval duration; - -/** - The date and time of learning.
- 勉強した日時です。 - */ -@property (nonatomic, readonly) NSDate *recordedAt; - -/** - The amount of learning.
- 勉強した量です。 - - @see StudyplusRecordAmount - */ -@property (nonatomic, readonly) SPLStudyplusRecordAmount *recordAmount; - -/** - The comment of learning.
- 勉強に関するコメントです。 - */ -@property (nonatomic, readonly) NSString *comment; - -/** - Creates and returns StudyplusRecord object that has number of seconds, no amount, and empty comment.
- 学習時間のみを指定した勉強記録オブジェクトを作成し、返します。学習量とコメントは無しです。 - - @param duration Specify the seconds of the learning.
- 勉強した時間(秒数)を指定してください。 - - @result StudyplusRecord object. - */ -+ (SPLStudyplusRecord*)recordWithDuration:(NSTimeInterval)duration; - -/** - Creates and returns StudyplusRecord object that has number of seconds and other attributes. - 学習時間とその他のオプション属性を指定した勉強記録オブジェクトを作成し、返します。 - - @param duration Specify the seconds of the learning.
- 勉強した時間(秒数)を指定してください。 - - @param options Dictionary with amount:StudyplusRecordAmount, comment:NSString, recordedAt:NSDate.
- // example.
- @{
- // @see StudyplusRecordAmount
- @"amount": [StudyplusRecordAmount amountAsRangeWithFrom:10 to:33],
- // Time the learning is ended. 学習を終えた日時。
- @"recordedAt": [NSDate date],
- // Studyplus timeline comment. Studyplusのタイムライン上で表示されるコメント。
- @"comment": @"アプリ◯◯で勉強しました!",
- }
- - @result StudyplusRecord object. - */ -+ (SPLStudyplusRecord*)recordWithDuration:(NSTimeInterval)duration options:(NSDictionary*)options; - -/** - @result Returns the parameters of the study record for posting API - */ -- (NSDictionary*)toRequestParam; - -@end diff --git a/build/Debug/deliverables/StudyplusSDK/SPLStudyplusRecordAmount.h b/build/Debug/deliverables/StudyplusSDK/SPLStudyplusRecordAmount.h deleted file mode 100644 index 811f6b0..0000000 --- a/build/Debug/deliverables/StudyplusSDK/SPLStudyplusRecordAmount.h +++ /dev/null @@ -1,62 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -/** - The class that represents the amount of learning.
- 学習量を表すクラスです。 - */ -@interface SPLStudyplusRecordAmount : NSObject - -/** - Creates and returns the Amount object with only the total amount of learning.
- 合計の学習量のみを持つAmountオブジェクトを生成して返します。 - - @param amount 学習量。 - @result SPLStudyplusRecordAmount* 生成したAmountオブジェクトです。 - */ -+ (SPLStudyplusRecordAmount*)amount:(NSUInteger)amount; - -/** - Creates and returns the Amount object with a range of learning amount.
- 学習量を範囲で持つAmountオブジェクトを生成して返します。 - - @param from 学習量の起点。 - @param to 学習量の終点。 - @result SPLStudyplusRecordAmount* 生成したAmountオブジェクトです。 - */ -+ (SPLStudyplusRecordAmount*)amountAsRangeWithFrom:(NSUInteger)from to:(NSUInteger)to; - -/** - Creates and returns the Amount object that has no learning amount.
- 学習量を持たないAmountオブジェクトを生成して返します。 - @result SPLStudyplusRecordAmount* 生成したAmountオブジェクトです。 - */ -+ (SPLStudyplusRecordAmount*)amountAsNone; - -/** - @result Returns the parameters of the study record for posting API - */ -- (NSDictionary*)toRequestParameter; - -@end diff --git a/build/Debug/deliverables/StudyplusSDK/libStudyplusSDK.a b/build/Debug/deliverables/StudyplusSDK/libStudyplusSDK.a deleted file mode 100644 index c39a7f6..0000000 Binary files a/build/Debug/deliverables/StudyplusSDK/libStudyplusSDK.a and /dev/null differ diff --git a/build/Release/deliverables/StudyplusSDK.zip b/build/Release/deliverables/StudyplusSDK.zip deleted file mode 100644 index ca85fb0..0000000 Binary files a/build/Release/deliverables/StudyplusSDK.zip and /dev/null differ diff --git a/build/Release/deliverables/StudyplusSDK/LICENSE.txt b/build/Release/deliverables/StudyplusSDK/LICENSE.txt deleted file mode 100644 index 33afa03..0000000 --- a/build/Release/deliverables/StudyplusSDK/LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Studyplus inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/build/Release/deliverables/StudyplusSDK/README.md b/build/Release/deliverables/StudyplusSDK/README.md deleted file mode 100644 index edf4fe1..0000000 --- a/build/Release/deliverables/StudyplusSDK/README.md +++ /dev/null @@ -1,192 +0,0 @@ -StudyplusSDK -======= - -Studyplus iOS SDK - -## Requirements - - * iOS 6.0 or above - * Xcode command line tools - * ARC - * [Studyplus iOS App 3.10.0 or adove](https://itunes.apple.com/jp/app/mian-qiangga-leshiku-xuku!/id505410049?mt=8) - * CocoaPods (Optional, but recommended) - -## Dependency - * [AFNetworking](https://github.com/AFNetworking/AFNetworking) - * [UICKeyChainStore](https://github.com/kishikawakatsumi/UICKeyChainStore) - -## Install - -### CocoaPods (Recommended) - -```ruby -# Edit your podfile -platform :ios, '6.0' -pod 'StudyplusSDK' -``` -and run -```pod install ``` - -### Manual install - -#### By library and headers - -1. Get StudyplusSDK. - * ```git clone https://github.com/studyplus/Studyplus-iOS-SDK``` or download zip from [this page](https://github.com/studyplus/Studyplus-iOS-SDK/releases). -2. Copy ```build/Release/deliverables/StudyplusSDK``` to your project. -3. Install [AFNetworking](https://github.com/AFNetworking/AFNetworking) and [UICKeyChainStore](https://github.com/kishikawakatsumi/UICKeyChainStore) too. -4. Add required frameworks(i.e. ```Security.framework, SystemConfiguration.framework, MobileCoreServices, CoreGraphics``` etc). See [AFNetworking](https://github.com/AFNetworking/AFNetworking) and [UICKeyChainStore](https://github.com/kishikawakatsumi/UICKeyChainStore). - -#### By source copy (iOS 7 required) - -1. Get StudyplusSDK - * ```git clone https://github.com/studyplus/Studyplus-iOS-SDK``` or download zip from [this page](https://github.com/studyplus/Studyplus-iOS-SDK/releases). -2. Copy Studyplus-iOS-SDK/StudyplusSDK directory to your project. -3. Install [AFNetworking](https://github.com/AFNetworking/AFNetworking) and [UICKeyChainStore](https://github.com/kishikawakatsumi/UICKeyChainStore) too. - -## Usage - -### Set up custom URL scheme - -set "studyplus-*{your consumer key}*" to URL Types. - -![xcode](https://raw.github.com/studyplus/Studyplus-iOS-SDK/master/docs/set_url_scheme.png) - -### Initialize - -```Objective-C -#import "SPLStudyplusDelegate.h" - -@interface YourClass --(BOOL)openURL:(NSURL*)url; -@end -``` - -```Objective-C -#import "SPLStudyplus.h" - -static NSString * const ConsumerKey = @"Your Studyplus consumer key"; -static NSString * const ConsumerSecret = @"Your Studyplus consumer secret"; - -@implementation YourClass -{ - SPLStudyplus *studyplus; -} - --(id) init { - - if (self = [super init]) { - studyplus = [SPLStudyplus studyplusWithConsumerKey:ConsumerKey - andConsumerSecret:ConsumerSecret]; - studyplus.delegate = self; - } - return self; -} -``` - -### Auth or Login -```Objective-C -@implementation AppDelegate - -- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation -{ - return [yourClassObject openURL:url]; -} -``` - -```Objective-C -@interface YourClass --(BOOL)openURL:(NSURL*)url; -@end -``` - -```Objective-C -@implementation YourClass - --(void) doAuth { - [studyplus auth]; -} - --(void) doLogin -{ - [studyplus login]; -} - -// Called by AppDelegate --(BOOL) openURL:(NSURL*)url -{ - return [studyplus openURL:url]; -} - -// callback methods --(void)studyplusDidConnect:(SPLStudyplus*)studyplus -{ - NSLog(@"Auth or Login succeeded"); -} - --(void)studyplusDidFailToConnect:(SPLStudyplus*)studyplus withError:(NSError*)error -{ - NSLog(@"Auth or Login failed"); -} - -- (void)studyplusDidCancel:(SPLStudyplus*)studyplus -{ - NSLog(@"Auth or Login canceled"); -} -``` - -### Post study record to Studyplus - -```Objective-C --(void)post -{ - - // Create new study record. - SPLStudyplusRecord *studyplusRecord = - [SPLStudyplusRecord - - /** - @see SPLStopwatch - */ - recordWithDuration:[studyplus.stopwatch elapsedSeconds] - - /** You can add optional info. - options:@{ - // Time the learning is ended. 学習を終えた日時。 - @"recordedAt" : [NSDate date], - // Studyplus timeline comment. Studyplusのタイムライン上で表示されるコメント。 - @"comment" : @"アプリ◯◯で勉強しました!!", - // @see SPLStudyplusRecordAmount - @"amount" : [SPLStudyplusRecordAmount amount:100], - } - */ - - ]; - - // post - [studyplus postStudyRecord:studyplusRecord]; - -} - -// callback methods --(void)studyplusDidPostStudyRecord:(SPLStudyplus*)studyplus -{ - NSLog(@"Post to Studyplus succeeded"); -} - --(void)studyplusDidFailToPostStudyRecord:(SPLStudyplus*)studyplus withError:(NSError*)error -{ - NSLog(@"Post to Studyplus failed"); -} -``` - -### More info about SDK interface - - * StudyplusSDK/SPLStudyplus.h - * StudyplusSDK/SPLStudyplusDelegate.h - * StudyplusSDK/SPLStudyplusRecord.h - * StudyplusSDK/SPLStudyplusRecordAmount.h - -## License - -[MIT License.](http://opensource.org/licenses/mit-license.php) diff --git a/build/Release/deliverables/StudyplusSDK/SPLStopwatch.h b/build/Release/deliverables/StudyplusSDK/SPLStopwatch.h deleted file mode 100644 index c1e82ca..0000000 --- a/build/Release/deliverables/StudyplusSDK/SPLStopwatch.h +++ /dev/null @@ -1,55 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -/** - Simple stopwatch with [start/stop/reset] functions. Useful for measuring the learning duration.
- シンプルなストップウォッチです。学習時間(duration)を計測するのに便利です。 - */ -@interface SPLStopwatch : NSObject - -/** - Begin or resume measuring.
- 測定を開始または再開します。 - */ --(void)start; - -/** - Pause measuring. Elapsed seconds will not be reset.
- 測定を一時停止します。経過秒数はリセットされません。 - */ --(void)pause; - -/** - Reset elapsed seconds. Elapsed seconds will be 0, and measuring will not stop.
- 経過秒数を0にリセットします。測定中の場合、測定は止まりません。 - */ --(void)reset; - -/** - Returns total elapsed seconds.
- 現時点の累計経過秒数を返します。 - */ --(NSUInteger)elapsedSeconds; - -@end diff --git a/build/Release/deliverables/StudyplusSDK/SPLStudyplus.h b/build/Release/deliverables/StudyplusSDK/SPLStudyplus.h deleted file mode 100644 index 692393a..0000000 --- a/build/Release/deliverables/StudyplusSDK/SPLStudyplus.h +++ /dev/null @@ -1,185 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "SPLStudyplusDelegate.h" -#import "SPLStudyplusRecord.h" -#import "SPLStudyplusRecordAmount.h" -#import "SPLStopwatch.h" - -/** - The class for using Studyplus.
- For example, you can authenticate in Studyplus account, de-authentication, and post study record. - - Studyplusの各機能を使うためのクラスです。
- Studyplusアカウントとの連携、連携解除、勉強記録の投稿ができます。 - */ -@interface SPLStudyplus : NSObject - -/** - The version of the StudyplusAPI. Default value is 1.
- StudyplusAPI のバージョンを指定します。デフォルトは 1 です。 - - https://external-api.studyplus.jp/v{apiVersion}/endpoint_name - */ -@property (nonatomic) NSInteger apiVersion; - -/** - Debug mode switch.
- When set to YES, then call back to the delegate without posting the actual processing.
- Default value is NO. - - StudyplusAPI のバージョンを指定します。
- debug=YESの場合、勉強記録の投稿時に実際の通信は行わずdelegateのコールバックメソッドを呼び出して処理を終了します。 - */ -@property (nonatomic) BOOL debug; - -/** - StudyplusAPI用のConsumer Keyです。
- Consumer Key for Studyplus API. - */ -@property (nonatomic, copy, readonly) NSString *consumerKey; - -/** - StudyplusAPI用のConsumer Secretです。
- Consumer Secret for Studyplus API. - */ -@property (nonatomic, copy, readonly) NSString *consumerSecret; - -/** - @see SPLStudyplusDelegate protocol - */ -@property (nonatomic, weak) id delegate; - -/** - When set to YES, if Studyplus is not installed, AppStore application starts when auth/login methods are called. Default value is YES.
- YESに設定すると、auth、loginメソッドを呼び出したとき、StudyplusアプリがインストールされていなければAppStoreを起動します。デフォルトは YES です。 - */ -@property (nonatomic) BOOL openAppStoreIfNotInstalled; - -/** - Username of Studyplus account. It is set when the auth or login is successful. Default value is nil.
- Studyplusアカウントのユーザ名です。login または authが成功したとき設定されます。設定されるまではnilです。 - */ -@property (nonatomic, copy, readonly) NSString *username; - -/** - Access token of Studyplus API. It is set when the auth or login is successful. Default value is nil.
- StudyplusAPIのアクセストークンです。login または authが成功したとき設定されます。設定されるまではnilです。 - */ -@property (nonatomic, copy, readonly) NSString *accessToken; - -/** - @see SPLStopwatch class - */ -@property (nonatomic, readonly) SPLStopwatch *stopwatch; - -/** - The convenience constructor of SPLStudyplus class. - - SPLStudyplusクラスのオブジェクトを生成して返します。 - - @param consumerKey Specify a Consumer Key for StudyplusAPI.
- StudyplusAPI用のコンシューマキーを指定してください。 - - @param consumerSecret Specify a Consumer Secret for StudyplusAPI.
- StudyplusAPI用のコンシューマシークレットを指定してください。 - - @return SPLStudyplus object.
- SPLStudyplusオブジェクト。 - */ -+ (SPLStudyplus*)studyplusWithConsumerKey:(NSString*)consumerKey - andConsumerSecret:(NSString*)consumerSecret; - -/** - Opens the auth screen by invoking the Studyplus application. - - Studyplusアプリを起動して連携許可画面を開きます。 - - If Studyplus app is not installed and openAppStoreIfNotInstalled is YES, then open the Studyplus page in AppStore.
- If openAppStoreIfNotInstalled is NO, do nothing.
- After the process has returned from Studyplus application, delegate method will be called back. - - Studyplusアプリがインストールされていない場合、 openAppStoreIfNotInstalled がYESであれば、AppStoreを起動してStudyplusページを開きます。
- openAppStoreIfNotInstalled がNOであれば何もしません。
- Studyplusアプリから操作が戻ってきた後、delegateオブジェクトのコールバックメソッドを呼び出します。 - - @return It returns YES when you started Studyplus application. If Studyplus application is not installed, it returns NO.
- Studyplusアプリが起動した時点でYESを返します。Studyplusアプリがインストールされていない場合、NOを返します。 - */ -- (BOOL)auth; - -/** - Opens the login screen by invoking the Studyplus application. - - Studyplusアプリを起動してStudyplusログイン画面を開きます。 - - If Studyplus app is not installed and openAppStoreIfNotInstalled is YES, then open the Studyplus page in AppStore.
- If openAppStoreIfNotInstalled is NO, do nothing.
- After the process has returned from Studyplus application, delegate method will be called back. - - Studyplusアプリがインストールされていない場合、 openAppStoreIfNotInstalled がYESであれば、AppStoreを起動してStudyplusページを開きます。
- openAppStoreIfNotInstalled がNOであれば何もしません。
- Studyplusアプリから操作が戻ってきた後、delegateオブジェクトのコールバックメソッドを呼び出します。 - - @return It returns YES when you started Studyplus application. If Studyplus application is not installed, it returns NO.
- Studyplusアプリが起動した時点でYESを返します。Studyplusアプリがインストールされていない場合、NOを返します。 - */ -- (BOOL)login; - -/** - Posts new study record to Studyplus.
- Studyplusに勉強記録を新規投稿します。 - - @param studyRecord @see SPLStudyplusRecord - */ -- (void)postStudyRecord:(SPLStudyplusRecord*)studyRecord; - -/** - Cancels the cooperation with Studyplus application.
- Studyplusアプリとの連携を解除します。 - */ -- (void)logout; - -/** - Returns to whether or not it is in conjunction with Studyplus application.
- Studyplusアプリと連携されているか否かを返します。 - */ -- (BOOL)isConnected; - -/** - It is responsible for processing custom URL scheme when it came back from the authorization / login screen of Stuudyplus app.
- After handling openURL method in AppDelegate, pass the url parameter to this method.
- If the URL is passed by Studyplus application, calls the callback method of the delegate object. - - Studyplusアプリの認可・ログイン画面から戻ってきた時のカスタムURLスキーム処理を担当します。
- AppDelegateでopenURLをハンドリングしてから、このメソッドにurlを渡して委譲してください。
- Studyplusアプリ関連のURLであれば、delegateオブジェクトのコールバックメソッドを呼び出します。 - - @param url The parameter of AppDelegate#openURL method.
- AppDelegate#openURLメソッドで受け取ったurlパラメータをそのまま渡して下さい。 - - @return If the url is supported by StudyplusSDK, returns YES. The valid URL has a "studyplus-{consumerKey}://" scheme, and right pathComponents and host.
- 渡されたurlがStudyplusSDKで対応すべきURL(スキームが"studyplus-{consumerKey}"であり、host/pathComponentsが想定内であるもの)であればYES、それ以外はNOを返します。 - */ -- (BOOL)openURL:(NSURL*)url; - -@end diff --git a/build/Release/deliverables/StudyplusSDK/SPLStudyplusAPIRequest.h b/build/Release/deliverables/StudyplusSDK/SPLStudyplusAPIRequest.h deleted file mode 100644 index 4ee1987..0000000 --- a/build/Release/deliverables/StudyplusSDK/SPLStudyplusAPIRequest.h +++ /dev/null @@ -1,35 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -@interface SPLStudyplusAPIRequest : NSObject - -+ (SPLStudyplusAPIRequest*)newRequestWithAccessToken:(NSString*)accessToken - options:(NSDictionary*)options; - -- (void)postRequestWithPath:(NSString *)path - requestParameter:(NSDictionary *)requestParameter - completed:(void(^)(NSDictionary *response))completed - failed:(void(^)(NSError *error))failed; - -@end diff --git a/build/Release/deliverables/StudyplusSDK/SPLStudyplusDelegate.h b/build/Release/deliverables/StudyplusSDK/SPLStudyplusDelegate.h deleted file mode 100644 index 1345488..0000000 --- a/build/Release/deliverables/StudyplusSDK/SPLStudyplusDelegate.h +++ /dev/null @@ -1,85 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -@class SPLStudyplus; - -/** - The delegate to receive callbacks from SPLStudyplus. - - SPLStudyplusオブジェクトに対する各種操作後のコールバックを受けるdelegateです。 - */ -@protocol SPLStudyplusDelegate - -/** - Will be called after the SPLStudyplus#login or SPLStudyplus#auth was successful.
- SPLStudyplus#auth または SPLStudyplus#login が成功した後に呼ばれます。 - - @param studyplus SPLStudyplus object.
- SPLStudyplusオブジェクトです。 - */ -- (void)studyplusDidConnect:(SPLStudyplus*)studyplus; - -/** - Will be called after the SPLStudyplus#login or SPLStudyplus#auth was failure.
- SPLStudyplus#auth または SPLStudyplus#login が失敗した後に呼ばれます。 - - @param studyplus Studyplus object.
- Studyplusオブジェクトです。 - @param error Error object including failure reason.
- 失敗の理由を持つエラーオブジェクトです。 - @see StudyplusNSError.h - */ -- (void)studyplusDidFailToConnect:(SPLStudyplus*)studyplus withError:(NSError*)error; - -@optional - -/** - Will be called after the SPLStudyplus#login or SPLStudyplus#auth was cancelled.
- SPLStudyplus#auth または SPLStudyplus#login がキャンセルされた後に呼ばれます。 - - @param studyplus SPLStudyplus object.
- SPLStudyplusオブジェクトです。 - */ -- (void)studyplusDidCancel:(SPLStudyplus*)studyplus; - -/** - Will be called after the SPLStudyplus#postStudyRecord was successful.
- SPLStudyplus#postStudyRecord: が成功した後に呼ばれます。 - - @param studyplus SPLStudyplus object.
- SPLStudyplusオブジェクトです。 - */ -- (void)studyplusDidPostStudyRecord:(SPLStudyplus*)studyplus; - -/** - Will be called after the SPLStudyplus#postStudyRecord was failure. If this method is called, study record was not posted.
- SPLStudyplus#postStudyRecord: が失敗した後に呼ばれます。このメソッドが呼ばれた場合、勉強ログは投稿されていません。 - - @param error Error object including failure reason.
- 失敗の理由を持つエラーオブジェクトです。 - @see SPLStudyplusError - */ -- (void)studyplusDidFailToPostStudyRecord:(SPLStudyplus*)studyplus withError:(NSError*)error; - -@end diff --git a/build/Release/deliverables/StudyplusSDK/SPLStudyplusError.h b/build/Release/deliverables/StudyplusSDK/SPLStudyplusError.h deleted file mode 100644 index 9061051..0000000 --- a/build/Release/deliverables/StudyplusSDK/SPLStudyplusError.h +++ /dev/null @@ -1,42 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -typedef NS_ENUM(NSInteger, SPLErrorCode) { - SPLErrorCodeGetAppDescription = 1000, - SPLErrorCodeAuthFailed = 2000, - SPLErrorCodeLoginFailed = 3000, - SPLErrorCodeStudyplusInMaintenance = 4000, - SPLErrorCodeInvalidStudyplusSession = 5000, - SPLErrorCodeNetworkUnavailable = 6000, - SPLErrorCodeServerError = 7000, - SPLErrorCodePostRecordFailed = 8000, - SPLErrorCodeUnknown = 90000 -}; - -@interface SPLStudyplusError : NSObject - -+ (NSError*)errorFromStudyplusErrorCode:(SPLErrorCode)studyplusErrorCode; -+ (NSError*)errorFromStudyRecordPostStatusCode:(NSInteger)httpStatusCode; - -@end diff --git a/build/Release/deliverables/StudyplusSDK/SPLStudyplusLogger.h b/build/Release/deliverables/StudyplusSDK/SPLStudyplusLogger.h deleted file mode 100644 index ec6a93e..0000000 --- a/build/Release/deliverables/StudyplusSDK/SPLStudyplusLogger.h +++ /dev/null @@ -1,25 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -// This file's name must be synchronized with code in StudyplusSDK.podspec and StudyplusSDK-Prefix.pch - -#define StudyplusSDKLog(format, ...) NSLog((@"%s[L%d]" format), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) diff --git a/build/Release/deliverables/StudyplusSDK/SPLStudyplusRecord.h b/build/Release/deliverables/StudyplusSDK/SPLStudyplusRecord.h deleted file mode 100644 index d23052a..0000000 --- a/build/Release/deliverables/StudyplusSDK/SPLStudyplusRecord.h +++ /dev/null @@ -1,97 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -@class SPLStudyplusRecordAmount; - -/** - Study record object to post to Studyplus.
- Studyplusに投稿する一件の勉強記録を表現するクラスです。 - */ -@interface SPLStudyplusRecord : NSObject - -/** - The seconds of the learning.
- 勉強した時間(秒数)です。 - */ -@property (nonatomic, readonly) NSTimeInterval duration; - -/** - The date and time of learning.
- 勉強した日時です。 - */ -@property (nonatomic, readonly) NSDate *recordedAt; - -/** - The amount of learning.
- 勉強した量です。 - - @see StudyplusRecordAmount - */ -@property (nonatomic, readonly) SPLStudyplusRecordAmount *recordAmount; - -/** - The comment of learning.
- 勉強に関するコメントです。 - */ -@property (nonatomic, readonly) NSString *comment; - -/** - Creates and returns StudyplusRecord object that has number of seconds, no amount, and empty comment.
- 学習時間のみを指定した勉強記録オブジェクトを作成し、返します。学習量とコメントは無しです。 - - @param duration Specify the seconds of the learning.
- 勉強した時間(秒数)を指定してください。 - - @result StudyplusRecord object. - */ -+ (SPLStudyplusRecord*)recordWithDuration:(NSTimeInterval)duration; - -/** - Creates and returns StudyplusRecord object that has number of seconds and other attributes. - 学習時間とその他のオプション属性を指定した勉強記録オブジェクトを作成し、返します。 - - @param duration Specify the seconds of the learning.
- 勉強した時間(秒数)を指定してください。 - - @param options Dictionary with amount:StudyplusRecordAmount, comment:NSString, recordedAt:NSDate.
- // example.
- @{
- // @see StudyplusRecordAmount
- @"amount": [StudyplusRecordAmount amountAsRangeWithFrom:10 to:33],
- // Time the learning is ended. 学習を終えた日時。
- @"recordedAt": [NSDate date],
- // Studyplus timeline comment. Studyplusのタイムライン上で表示されるコメント。
- @"comment": @"アプリ◯◯で勉強しました!",
- }
- - @result StudyplusRecord object. - */ -+ (SPLStudyplusRecord*)recordWithDuration:(NSTimeInterval)duration options:(NSDictionary*)options; - -/** - @result Returns the parameters of the study record for posting API - */ -- (NSDictionary*)toRequestParam; - -@end diff --git a/build/Release/deliverables/StudyplusSDK/SPLStudyplusRecordAmount.h b/build/Release/deliverables/StudyplusSDK/SPLStudyplusRecordAmount.h deleted file mode 100644 index 811f6b0..0000000 --- a/build/Release/deliverables/StudyplusSDK/SPLStudyplusRecordAmount.h +++ /dev/null @@ -1,62 +0,0 @@ -// The MIT License (MIT) -// -// Copyright (c) 2014 Studyplus inc. -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -/** - The class that represents the amount of learning.
- 学習量を表すクラスです。 - */ -@interface SPLStudyplusRecordAmount : NSObject - -/** - Creates and returns the Amount object with only the total amount of learning.
- 合計の学習量のみを持つAmountオブジェクトを生成して返します。 - - @param amount 学習量。 - @result SPLStudyplusRecordAmount* 生成したAmountオブジェクトです。 - */ -+ (SPLStudyplusRecordAmount*)amount:(NSUInteger)amount; - -/** - Creates and returns the Amount object with a range of learning amount.
- 学習量を範囲で持つAmountオブジェクトを生成して返します。 - - @param from 学習量の起点。 - @param to 学習量の終点。 - @result SPLStudyplusRecordAmount* 生成したAmountオブジェクトです。 - */ -+ (SPLStudyplusRecordAmount*)amountAsRangeWithFrom:(NSUInteger)from to:(NSUInteger)to; - -/** - Creates and returns the Amount object that has no learning amount.
- 学習量を持たないAmountオブジェクトを生成して返します。 - @result SPLStudyplusRecordAmount* 生成したAmountオブジェクトです。 - */ -+ (SPLStudyplusRecordAmount*)amountAsNone; - -/** - @result Returns the parameters of the study record for posting API - */ -- (NSDictionary*)toRequestParameter; - -@end diff --git a/build/Release/deliverables/StudyplusSDK/libStudyplusSDK.a b/build/Release/deliverables/StudyplusSDK/libStudyplusSDK.a deleted file mode 100644 index b3854dc..0000000 Binary files a/build/Release/deliverables/StudyplusSDK/libStudyplusSDK.a and /dev/null differ diff --git a/docs/demoapp.jpg b/docs/demoapp.jpg new file mode 100644 index 0000000..d1e5484 Binary files /dev/null and b/docs/demoapp.jpg differ diff --git a/docs/demoapp.png b/docs/demoapp.png deleted file mode 100644 index a0dc26e..0000000 Binary files a/docs/demoapp.png and /dev/null differ diff --git a/script/build.sh b/script/build.sh deleted file mode 100755 index 04856d7..0000000 --- a/script/build.sh +++ /dev/null @@ -1,86 +0,0 @@ -#!/bin/sh - -LOCKFILE=nowbuilding.lock - -if [ -e $LOCKFILE ]; then - exit 0 -fi - -touch $LOCKFILE -pod install - -run() { - MODE=$1 - PRODUCT_NAME=StudyplusSDK - HEADERS_DIR=./${PRODUCT_NAME} - MODE_DIR=./build/${MODE} - WORKING_DIR=${MODE_DIR}/working - ARM_DIR=${WORKING_DIR}/arm - I386_DIR=${WORKING_DIR}/i386 - X86_64_DIR=${WORKING_DIR}/x86_64 - DELIVERABLES_DIR=${MODE_DIR}/deliverables - PROUDCT_DIR=${DELIVERABLES_DIR}/${PRODUCT_NAME} - LIB_FILE_NAME=lib${PRODUCT_NAME}.a - - rm -rf $MODE_DIR - mkdir -p $WORKING_DIR - mkdir -p $ARM_DIR - mkdir -p $I386_DIR - mkdir -p $X86_64_DIR - mkdir -p $DELIVERABLES_DIR - mkdir -p $PROUDCT_DIR - - # iPhone - xcodebuild -workspace StudyplusSDK.xcworkspace -scheme StudyplusSDK -configuration ${MODE} -sdk iphoneos clean build ARCHS='armv7 armv7s arm64' VALID_ARCHS='armv7 armv7s arm64' - xcodebuild -workspace StudyplusSDK.xcworkspace -scheme StudyplusSDK -configuration ${MODE} -sdk iphoneos clean build ARCHS='armv7 armv7s arm64' VALID_ARCHS='armv7 armv7s arm64' TARGET_BUILD_DIR="${ARM_DIR}" - - # iPhone Simulator(32bit) - xcodebuild -workspace StudyplusSDK.xcworkspace -scheme StudyplusSDK -configuration ${MODE} -sdk iphonesimulator clean build ARCHS='i386' - xcodebuild -workspace StudyplusSDK.xcworkspace -scheme StudyplusSDK -configuration ${MODE} -sdk iphonesimulator clean build ARCHS='i386' TARGET_BUILD_DIR="${I386_DIR}" - - # iPhone Simulator(64bit) - xcodebuild -workspace StudyplusSDK.xcworkspace -scheme StudyplusSDK -configuration ${MODE} -sdk iphonesimulator clean build ARCHS='x86_64' VALID_ARCHS='armv7 armv7s arm64 i386 x86_64' - xcodebuild -workspace StudyplusSDK.xcworkspace -scheme StudyplusSDK -configuration ${MODE} -sdk iphonesimulator clean build ARCHS='x86_64' VALID_ARCHS='armv7 armv7s arm64 i386 x86_64' TARGET_BUILD_DIR="${X86_64_DIR}" - - # make universal library - echo create $ARM_DIR/$LIB_FILE_NAME $I386_DIR/$LIB_FILE_NAME $X86_64_DIR/$LIB_FILE_NAME -output "${PROUDCT_DIR}/${LIB_FILE_NAME}" - lipo -create $ARM_DIR/$LIB_FILE_NAME $I386_DIR/$LIB_FILE_NAME $X86_64_DIR/$LIB_FILE_NAME -output "${PROUDCT_DIR}/${LIB_FILE_NAME}" - - # headers - cp -Rp $HEADERS_DIR/*.h $PROUDCT_DIR - - # documents - cp -p ./LICENSE.txt $PROUDCT_DIR - cp -p ./README.md $PROUDCT_DIR - - # zip - cd $DELIVERABLES_DIR - zip -9 -r ${PRODUCT_NAME}.zip ${PRODUCT_NAME} - cd - - - return 0 -} - -archive() { - ARCHIVE_DIR=build/archives - ARCHIVE_NAME=`date +%Y_%m_%d_%H_%M_%S`.zip - mkdir -p $ARCHIVE_DIR - zip -r9 $ARCHIVE_DIR/$ARCHIVE_NAME build/Debug build/Release -} - -echo "Archiving old deliverables..." -archive > /dev/null -echo "finish." -echo "====================================" -echo "Building with Debug configuration..." -run Debug > /dev/null -echo "finish." -echo "====================================" -echo "Building with Release configuration..." -run Release > /dev/null -echo "finish." -echo "====================================" -ls -lh build/**/deliverables/*.zip -echo "====================================" - -rm $LOCKFILE diff --git a/script/resolve_dups.sh b/script/resolve_dups.sh deleted file mode 100755 index 7717a55..0000000 --- a/script/resolve_dups.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/sh - -CWD=`echo $(cd $(dirname $0);pwd)` -cd $CWD - -WORKING_DIR=work_`date +%Y%m%d%H%M%S` -mkdir $WORKING_DIR - -ARMV7_TMP=$WORKING_DIR/libStudyplusSDK_armv7_tmp.a -ARMV7S_TMP=$WORKING_DIR/libStudyplusSDK_armv7s_tmp.a -ARM64_TMP=$WORKING_DIR/libStudyplusSDK_arm64_tmp.a -I386_TMP=$WORKING_DIR/libStudyplusSDK_i386_tmp.a -X86_64_TMP=$WORKING_DIR/libStudyplusSDK_x86_64_tmp.a - -# backup -cp -p libStudyplusSDK.a libStudyplusSDK.a_`date +%Y%m%d%H%M%S` - -divide_lib() { - lipo -thin armv7 libStudyplusSDK.a -output $ARMV7_TMP - xcrun -sdk iphoneos lipo -thin armv7s libStudyplusSDK.a -output $ARMV7S_TMP - xcrun -sdk iphoneos lipo -thin arm64 libStudyplusSDK.a -output $ARM64_TMP - lipo -thin i386 libStudyplusSDK.a -output $I386_TMP - lipo -thin x86_64 libStudyplusSDK.a -output $X86_64_TMP -} - -remove_dup() { - LIB=$1 - DUP=$2 - ar -dv $LIB $DUP -} - -divide_lib - -for dup in $@ -do - for lib in $ARMV7_TMP $ARMV7S_TMP $ARM64_TMP $I386_TMP $X86_64_TMP - do - remove_dup $lib $dup - done -done - -# to fat lib -lipo -create $ARMV7_TMP $ARMV7S_TMP $ARM64_TMP $I386_TMP $X86_64_TMP -output libStudyplusSDK.a - -# clean -rm -rf $WORKING_DIR -