first

0 parents
Showing 86 changed ファイルs with 14954 additions and 0 deletions
*.xcodeproj/*
!*.xcodeproj/project.pbxproj
!*.xcworkspace/contents.xcworkspacedata
.DS_Store
// 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 <Foundation/Foundation.h>
#if !TARGET_OS_WATCH
#import <SystemConfiguration/SystemConfiguration.h>
#endif
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
#import <MobileCoreServices/MobileCoreServices.h>
#else
#import <CoreServices/CoreServices.h>
#endif
#import "AFURLSessionManager.h"
/**
`AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths.
## Subclassing Notes
Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application.
For developers targeting iOS 6 or Mac OS X 10.8 or earlier, `AFHTTPRequestOperationManager` may be used to similar effect.
## Methods to Override
To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:`.
## Serialization
Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to `<AFURLRequestSerialization>`.
Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `<AFURLResponseSerialization>`
## 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 <NSSecureCoding, NSCopying>
/**
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 <AFURLRequestSerialization> * 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 <AFURLResponseSerialization> * 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 <AFMultipartFormData> 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 <AFMultipartFormData> 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
// 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 <Availability.h>
#import <TargetConditionals.h>
#import <Security/Security.h>
#import <netinet/in.h>
#import <netinet6/in6.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <netdb.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import <UIKit/UIKit.h>
#elif TARGET_OS_WATCH
#import <WatchKit/WatchKit.h>
#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 <AFURLRequestSerialization> *)requestSerializer {
NSParameterAssert(requestSerializer);
_requestSerializer = requestSerializer;
}
- (void)setResponseSerializer:(AFHTTPResponseSerializer <AFURLResponseSerialization> *)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<AFMultipartFormData> _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 <AFMultipartFormData> formData))block
progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
if (serializationError) {
if (failure) {
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
}
return nil;
}
__block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
if (error) {
if (failure) {
failure(task, error);
}
} else {
if (success) {
success(task, responseObject);
}
}
}];
[task resume];
return task;
}
- (NSURLSessionDataTask *)PUT:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)PATCH:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)DELETE:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters uploadProgress:nil downloadProgress:nil success:success failure:failure];
[dataTask resume];
return dataTask;
}
- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
success:(void (^)(NSURLSessionDataTask *, id))success
failure:(void (^)(NSURLSessionDataTask *, NSError *))failure
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
if (serializationError) {
if (failure) {
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
failure(nil, serializationError);
});
}
return nil;
}
__block NSURLSessionDataTask *dataTask = nil;
dataTask = [self dataTaskWithRequest:request
uploadProgress:uploadProgress
downloadProgress:downloadProgress
completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
if (error) {
if (failure) {
failure(dataTask, error);
}
} else {
if (success) {
success(dataTask, responseObject);
}
}
}];
return dataTask;
}
#pragma mark - NSObject
- (NSString *)description {
return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue];
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (instancetype)initWithCoder:(NSCoder *)decoder {
NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))];
NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"];
if (!configuration) {
NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"];
if (configurationIdentifier) {
#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1100)
configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier];
#else
configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:configurationIdentifier];
#endif
}
}
self = [self initWithBaseURL:baseURL sessionConfiguration:configuration];
if (!self) {
return nil;
}
self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))];
self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))];
AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))];
if (decodedPolicy) {
self.securityPolicy = decodedPolicy;
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))];
if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) {
[coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"];
} else {
[coder encodeObject:self.session.configuration.identifier forKey:@"identifier"];
}
[coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))];
[coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))];
[coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))];
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone {
AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration];
HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone];
HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone];
HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone];
return HTTPClient;
}
@end
// 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 <Foundation/Foundation.h>
#if !TARGET_OS_WATCH
#import <SystemConfiguration/SystemConfiguration.h>
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 <SystemConfiguration/SystemConfiguration.h>` 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
// 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 <netinet/in.h>
#import <netinet6/in6.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <netdb.h>
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
// 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 <Foundation/Foundation.h>
#import <Availability.h>
#import <TargetConditionals.h>
#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_ */
// 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 <Foundation/Foundation.h>
#import <Security/Security.h>
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 <NSSecureCoding, NSCopying>
/**
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 <NSData *> *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 <NSData *> *)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 <NSData *> *)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.
*/
// 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 <AssertMacros.h>
#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
// 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 <Foundation/Foundation.h>
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import <UIKit/UIKit.h>
#elif TARGET_OS_WATCH
#import <WatchKit/WatchKit.h>
#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 <NSObject, NSSecureCoding, NSCopying>
/**
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 <AFURLRequestSerialization>
/**
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 <NSString *, NSString *> *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 <NSString *> *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 <NSString *, id> *)parameters
constructingBodyWithBlock:(nullable void (^)(id <AFMultipartFormData> 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 <NSString *, NSString *> *)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
// 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 <MobileCoreServices/MobileCoreServices.h>
#else
#import <CoreServices/CoreServices.h>
#endif
NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request";
NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response";
typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error);
/**
Returns a percent-escaped string following RFC 3986 for a query string key or value.
RFC 3986 states that the following characters are "reserved" characters.
- General Delimiters: ":", "#", "[", "]", "@", "?", "/"
- Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
should be percent-escaped in the query string.
- parameter string: The string to be percent-escaped.
- returns: The percent-escaped string.
*/
NSString * AFPercentEscapedStringFromString(NSString *string) {
static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4
static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]];
// FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028
// return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
static NSUInteger const batchSize = 50;
NSUInteger index = 0;
NSMutableString *escaped = @"".mutableCopy;
while (index < string.length) {
NSUInteger length = MIN(string.length - index, batchSize);
NSRange range = NSMakeRange(index, length);
// To avoid breaking up character sequences such as 👴🏻👮🏽
range = [string rangeOfComposedCharacterSequencesForRange:range];
NSString *substring = [string substringWithRange:range];
NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
[escaped appendString:encoded];
index += range.length;
}
return escaped;
}
#pragma mark -
@interface AFQueryStringPair : NSObject
@property (readwrite, nonatomic, strong) id field;
@property (readwrite, nonatomic, strong) id value;
- (instancetype)initWithField:(id)field value:(id)value;
- (NSString *)URLEncodedStringValue;
@end
@implementation AFQueryStringPair
- (instancetype)initWithField:(id)field value:(id)value {
self = [super init];
if (!self) {
return nil;
}
self.field = field;
self.value = value;
return self;
}
- (NSString *)URLEncodedStringValue {
if (!self.value || [self.value isEqual:[NSNull null]]) {
return AFPercentEscapedStringFromString([self.field description]);
} else {
return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedStringFromString([self.field description]), AFPercentEscapedStringFromString([self.value description])];
}
}
@end
#pragma mark -
FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary);
FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value);
NSString * AFQueryStringFromParameters(NSDictionary *parameters) {
NSMutableArray *mutablePairs = [NSMutableArray array];
for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
[mutablePairs addObject:[pair URLEncodedStringValue]];
}
return [mutablePairs componentsJoinedByString:@"&"];
}
NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) {
return AFQueryStringPairsFromKeyAndValue(nil, dictionary);
}
NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
NSMutableArray *mutableQueryStringComponents = [NSMutableArray array];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)];
if ([value isKindOfClass:[NSDictionary class]]) {
NSDictionary *dictionary = value;
// Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries
for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
id nestedValue = dictionary[nestedKey];
if (nestedValue) {
[mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)];
}
}
} else if ([value isKindOfClass:[NSArray class]]) {
NSArray *array = value;
for (id nestedValue in array) {
[mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)];
}
} else if ([value isKindOfClass:[NSSet class]]) {
NSSet *set = value;
for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) {
[mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)];
}
} else {
[mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]];
}
return mutableQueryStringComponents;
}
#pragma mark -
@interface AFStreamingMultipartFormData : NSObject <AFMultipartFormData>
- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest
stringEncoding:(NSStringEncoding)encoding;
- (NSMutableURLRequest *)requestByFinalizingMultipartFormData;
@end
#pragma mark -
static NSArray * AFHTTPRequestSerializerObservedKeyPaths() {
static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))];
});
return _AFHTTPRequestSerializerObservedKeyPaths;
}
static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerObserverContext;
@interface AFHTTPRequestSerializer ()
@property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths;
@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders;
@property (readwrite, nonatomic, strong) dispatch_queue_t requestHeaderModificationQueue;
@property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle;
@property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization;
@end
@implementation AFHTTPRequestSerializer
+ (instancetype)serializer {
return [[self alloc] init];
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.stringEncoding = NSUTF8StringEncoding;
self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary];
self.requestHeaderModificationQueue = dispatch_queue_create("requestHeaderModificationQueue", DISPATCH_QUEUE_CONCURRENT);
// Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
NSMutableArray *acceptLanguagesComponents = [NSMutableArray array];
[[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
float q = 1.0f - (idx * 0.1f);
[acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]];
*stop = q <= 0.5f;
}];
[self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"];
NSString *userAgent = nil;
#if TARGET_OS_IOS
// User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]];
#elif TARGET_OS_WATCH
// User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
userAgent = [NSString stringWithFormat:@"%@/%@ (%@; watchOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[WKInterfaceDevice currentDevice] model], [[WKInterfaceDevice currentDevice] systemVersion], [[WKInterfaceDevice currentDevice] screenScale]];
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]];
#endif
if (userAgent) {
if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) {
NSMutableString *mutableUserAgent = [userAgent mutableCopy];
if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) {
userAgent = mutableUserAgent;
}
}
[self setValue:userAgent forHTTPHeaderField:@"User-Agent"];
}
// HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil];
self.mutableObservedChangedKeyPaths = [NSMutableSet set];
for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
[self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext];
}
}
return self;
}
- (void)dealloc {
for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
if ([self respondsToSelector:NSSelectorFromString(keyPath)]) {
[self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext];
}
}
}
#pragma mark -
// Workarounds for crashing behavior using Key-Value Observing with XCTest
// See https://github.com/AFNetworking/AFNetworking/issues/2523
- (void)setAllowsCellularAccess:(BOOL)allowsCellularAccess {
[self willChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))];
_allowsCellularAccess = allowsCellularAccess;
[self didChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))];
}
- (void)setCachePolicy:(NSURLRequestCachePolicy)cachePolicy {
[self willChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))];
_cachePolicy = cachePolicy;
[self didChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))];
}
- (void)setHTTPShouldHandleCookies:(BOOL)HTTPShouldHandleCookies {
[self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))];
_HTTPShouldHandleCookies = HTTPShouldHandleCookies;
[self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))];
}
- (void)setHTTPShouldUsePipelining:(BOOL)HTTPShouldUsePipelining {
[self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))];
_HTTPShouldUsePipelining = HTTPShouldUsePipelining;
[self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))];
}
- (void)setNetworkServiceType:(NSURLRequestNetworkServiceType)networkServiceType {
[self willChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))];
_networkServiceType = networkServiceType;
[self didChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))];
}
- (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval {
[self willChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))];
_timeoutInterval = timeoutInterval;
[self didChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))];
}
#pragma mark -
- (NSDictionary *)HTTPRequestHeaders {
NSDictionary __block *value;
dispatch_sync(self.requestHeaderModificationQueue, ^{
value = [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders];
});
return value;
}
- (void)setValue:(NSString *)value
forHTTPHeaderField:(NSString *)field
{
dispatch_barrier_async(self.requestHeaderModificationQueue, ^{
[self.mutableHTTPRequestHeaders setValue:value forKey:field];
});
}
- (NSString *)valueForHTTPHeaderField:(NSString *)field {
NSString __block *value;
dispatch_sync(self.requestHeaderModificationQueue, ^{
value = [self.mutableHTTPRequestHeaders valueForKey:field];
});
return value;
}
- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username
password:(NSString *)password
{
NSData *basicAuthCredentials = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64AuthCredentials = [basicAuthCredentials base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
[self setValue:[NSString stringWithFormat:@"Basic %@", base64AuthCredentials] forHTTPHeaderField:@"Authorization"];
}
- (void)clearAuthorizationHeader {
dispatch_barrier_async(self.requestHeaderModificationQueue, ^{
[self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"];
});
}
#pragma mark -
- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style {
self.queryStringSerializationStyle = style;
self.queryStringSerialization = nil;
}
- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, id, NSError *__autoreleasing *))block {
self.queryStringSerialization = block;
}
#pragma mark -
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(method);
NSParameterAssert(URLString);
NSURL *url = [NSURL URLWithString:URLString];
NSParameterAssert(url);
NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
mutableRequest.HTTPMethod = method;
for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) {
if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) {
[mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath];
}
}
mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy];
return mutableRequest;
}
- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(method);
NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]);
NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error];
__block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding];
if (parameters) {
for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
NSData *data = nil;
if ([pair.value isKindOfClass:[NSData class]]) {
data = pair.value;
} else if ([pair.value isEqual:[NSNull null]]) {
data = [NSData data];
} else {
data = [[pair.value description] dataUsingEncoding:self.stringEncoding];
}
if (data) {
[formData appendPartWithFormData:data name:[pair.field description]];
}
}
}
if (block) {
block(formData);
}
return [formData requestByFinalizingMultipartFormData];
}
- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request
writingStreamContentsToFile:(NSURL *)fileURL
completionHandler:(void (^)(NSError *error))handler
{
NSParameterAssert(request.HTTPBodyStream);
NSParameterAssert([fileURL isFileURL]);
NSInputStream *inputStream = request.HTTPBodyStream;
NSOutputStream *outputStream = [[NSOutputStream alloc] initWithURL:fileURL append:NO];
__block NSError *error = nil;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
while ([inputStream hasBytesAvailable] && [outputStream hasSpaceAvailable]) {
uint8_t buffer[1024];
NSInteger bytesRead = [inputStream read:buffer maxLength:1024];
if (inputStream.streamError || bytesRead < 0) {
error = inputStream.streamError;
break;
}
NSInteger bytesWritten = [outputStream write:buffer maxLength:(NSUInteger)bytesRead];
if (outputStream.streamError || bytesWritten < 0) {
error = outputStream.streamError;
break;
}
if (bytesRead == 0 && bytesWritten == 0) {
break;
}
}
[outputStream close];
[inputStream close];
if (handler) {
dispatch_async(dispatch_get_main_queue(), ^{
handler(error);
});
}
});
NSMutableURLRequest *mutableRequest = [request mutableCopy];
mutableRequest.HTTPBodyStream = nil;
return mutableRequest;
}
#pragma mark - AFURLRequestSerialization
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(request);
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
if (![request valueForHTTPHeaderField:field]) {
[mutableRequest setValue:value forHTTPHeaderField:field];
}
}];
NSString *query = nil;
if (parameters) {
if (self.queryStringSerialization) {
NSError *serializationError;
query = self.queryStringSerialization(request, parameters, &serializationError);
if (serializationError) {
if (error) {
*error = serializationError;
}
return nil;
}
} else {
switch (self.queryStringSerializationStyle) {
case AFHTTPRequestQueryStringDefaultStyle:
query = AFQueryStringFromParameters(parameters);
break;
}
}
}
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
if (query && query.length > 0) {
mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]];
}
} else {
// #2864: an empty string is a valid x-www-form-urlencoded payload
if (!query) {
query = @"";
}
if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
[mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
}
[mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]];
}
return mutableRequest;
}
#pragma mark - NSKeyValueObserving
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) {
return NO;
}
return [super automaticallyNotifiesObserversForKey:key];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(__unused id)object
change:(NSDictionary *)change
context:(void *)context
{
if (context == AFHTTPRequestSerializerObserverContext) {
if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) {
[self.mutableObservedChangedKeyPaths removeObject:keyPath];
} else {
[self.mutableObservedChangedKeyPaths addObject:keyPath];
}
}
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (instancetype)initWithCoder:(NSCoder *)decoder {
self = [self init];
if (!self) {
return nil;
}
self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy];
self.queryStringSerializationStyle = (AFHTTPRequestQueryStringSerializationStyle)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue];
return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
dispatch_sync(self.requestHeaderModificationQueue, ^{
[coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))];
});
[coder encodeInteger:self.queryStringSerializationStyle forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))];
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone {
AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init];
dispatch_sync(self.requestHeaderModificationQueue, ^{
serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone];
});
serializer.queryStringSerializationStyle = self.queryStringSerializationStyle;
serializer.queryStringSerialization = self.queryStringSerialization;
return serializer;
}
@end
#pragma mark -
static NSString * AFCreateMultipartFormBoundary() {
return [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()];
}
static NSString * const kAFMultipartFormCRLF = @"\r\n";
static inline NSString * AFMultipartFormInitialBoundary(NSString *boundary) {
return [NSString stringWithFormat:@"--%@%@", boundary, kAFMultipartFormCRLF];
}
static inline NSString * AFMultipartFormEncapsulationBoundary(NSString *boundary) {
return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF];
}
static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) {
return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF];
}
static inline NSString * AFContentTypeForPathExtension(NSString *extension) {
NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL);
NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
if (!contentType) {
return @"application/octet-stream";
} else {
return contentType;
}
}
NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16;
NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2;
@interface AFHTTPBodyPart : NSObject
@property (nonatomic, assign) NSStringEncoding stringEncoding;
@property (nonatomic, strong) NSDictionary *headers;
@property (nonatomic, copy) NSString *boundary;
@property (nonatomic, strong) id body;
@property (nonatomic, assign) unsigned long long bodyContentLength;
@property (nonatomic, strong) NSInputStream *inputStream;
@property (nonatomic, assign) BOOL hasInitialBoundary;
@property (nonatomic, assign) BOOL hasFinalBoundary;
@property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable;
@property (readonly, nonatomic, assign) unsigned long long contentLength;
- (NSInteger)read:(uint8_t *)buffer
maxLength:(NSUInteger)length;
@end
@interface AFMultipartBodyStream : NSInputStream <NSStreamDelegate>
@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 () <NSCopying>
@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding;
@property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts;
@property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator;
@property (readwrite, nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart;
@property (readwrite, nonatomic, strong) NSOutputStream *outputStream;
@property (readwrite, nonatomic, strong) NSMutableData *buffer;
@end
@implementation AFMultipartBodyStream
#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1100)
@synthesize delegate;
#endif
@synthesize streamStatus;
@synthesize streamError;
- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding {
self = [super init];
if (!self) {
return nil;
}
self.stringEncoding = encoding;
self.HTTPBodyParts = [NSMutableArray array];
self.numberOfBytesInPacket = NSIntegerMax;
return self;
}
- (void)setInitialAndFinalBoundaries {
if ([self.HTTPBodyParts count] > 0) {
for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
bodyPart.hasInitialBoundary = NO;
bodyPart.hasFinalBoundary = NO;
}
[[self.HTTPBodyParts firstObject] setHasInitialBoundary:YES];
[[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES];
}
}
- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart {
[self.HTTPBodyParts addObject:bodyPart];
}
- (BOOL)isEmpty {
return [self.HTTPBodyParts count] == 0;
}
#pragma mark - NSInputStream
- (NSInteger)read:(uint8_t *)buffer
maxLength:(NSUInteger)length
{
if ([self streamStatus] == NSStreamStatusClosed) {
return 0;
}
NSInteger totalNumberOfBytesRead = 0;
while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) {
if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) {
if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) {
break;
}
} else {
NSUInteger maxLength = MIN(length, self.numberOfBytesInPacket) - (NSUInteger)totalNumberOfBytesRead;
NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength];
if (numberOfBytesRead == -1) {
self.streamError = self.currentHTTPBodyPart.inputStream.streamError;
break;
} else {
totalNumberOfBytesRead += numberOfBytesRead;
if (self.delay > 0.0f) {
[NSThread sleepForTimeInterval:self.delay];
}
}
}
}
return totalNumberOfBytesRead;
}
- (BOOL)getBuffer:(__unused uint8_t **)buffer
length:(__unused NSUInteger *)len
{
return NO;
}
- (BOOL)hasBytesAvailable {
return [self streamStatus] == NSStreamStatusOpen;
}
#pragma mark - NSStream
- (void)open {
if (self.streamStatus == NSStreamStatusOpen) {
return;
}
self.streamStatus = NSStreamStatusOpen;
[self setInitialAndFinalBoundaries];
self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator];
}
- (void)close {
self.streamStatus = NSStreamStatusClosed;
}
- (id)propertyForKey:(__unused NSString *)key {
return nil;
}
- (BOOL)setProperty:(__unused id)property
forKey:(__unused NSString *)key
{
return NO;
}
- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop
forMode:(__unused NSString *)mode
{}
- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop
forMode:(__unused NSString *)mode
{}
- (unsigned long long)contentLength {
unsigned long long length = 0;
for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
length += [bodyPart contentLength];
}
return length;
}
#pragma mark - Undocumented CFReadStream Bridged Methods
- (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop
forMode:(__unused CFStringRef)aMode
{}
- (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop
forMode:(__unused CFStringRef)aMode
{}
- (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags
callback:(__unused CFReadStreamClientCallBack)inCallback
context:(__unused CFStreamClientContext *)inContext {
return NO;
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone {
AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding];
for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) {
[bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]];
}
[bodyStreamCopy setInitialAndFinalBoundaries];
return bodyStreamCopy;
}
@end
#pragma mark -
typedef enum {
AFEncapsulationBoundaryPhase = 1,
AFHeaderPhase = 2,
AFBodyPhase = 3,
AFFinalBoundaryPhase = 4,
} AFHTTPBodyPartReadPhase;
@interface AFHTTPBodyPart () <NSCopying> {
AFHTTPBodyPartReadPhase _phase;
NSInputStream *_inputStream;
unsigned long long _phaseReadOffset;
}
- (BOOL)transitionToNextPhase;
- (NSInteger)readData:(NSData *)data
intoBuffer:(uint8_t *)buffer
maxLength:(NSUInteger)length;
@end
@implementation AFHTTPBodyPart
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
[self transitionToNextPhase];
return self;
}
- (void)dealloc {
if (_inputStream) {
[_inputStream close];
_inputStream = nil;
}
}
- (NSInputStream *)inputStream {
if (!_inputStream) {
if ([self.body isKindOfClass:[NSData class]]) {
_inputStream = [NSInputStream inputStreamWithData:self.body];
} else if ([self.body isKindOfClass:[NSURL class]]) {
_inputStream = [NSInputStream inputStreamWithURL:self.body];
} else if ([self.body isKindOfClass:[NSInputStream class]]) {
_inputStream = self.body;
} else {
_inputStream = [NSInputStream inputStreamWithData:[NSData data]];
}
}
return _inputStream;
}
- (NSString *)stringForHeaders {
NSMutableString *headerString = [NSMutableString string];
for (NSString *field in [self.headers allKeys]) {
[headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]];
}
[headerString appendString:kAFMultipartFormCRLF];
return [NSString stringWithString:headerString];
}
- (unsigned long long)contentLength {
unsigned long long length = 0;
NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding];
length += [encapsulationBoundaryData length];
NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
length += [headersData length];
length += _bodyContentLength;
NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]);
length += [closingBoundaryData length];
return length;
}
- (BOOL)hasBytesAvailable {
// Allows `read:maxLength:` to be called again if `AFMultipartFormFinalBoundary` doesn't fit into the available buffer
if (_phase == AFFinalBoundaryPhase) {
return YES;
}
switch (self.inputStream.streamStatus) {
case NSStreamStatusNotOpen:
case NSStreamStatusOpening:
case NSStreamStatusOpen:
case NSStreamStatusReading:
case NSStreamStatusWriting:
return YES;
case NSStreamStatusAtEnd:
case NSStreamStatusClosed:
case NSStreamStatusError:
default:
return NO;
}
}
- (NSInteger)read:(uint8_t *)buffer
maxLength:(NSUInteger)length
{
NSInteger totalNumberOfBytesRead = 0;
if (_phase == AFEncapsulationBoundaryPhase) {
NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding];
totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
}
if (_phase == AFHeaderPhase) {
NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding];
totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
}
if (_phase == AFBodyPhase) {
NSInteger numberOfBytesRead = 0;
numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
if (numberOfBytesRead == -1) {
return -1;
} else {
totalNumberOfBytesRead += numberOfBytesRead;
if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) {
[self transitionToNextPhase];
}
}
}
if (_phase == AFFinalBoundaryPhase) {
NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]);
totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)];
}
return totalNumberOfBytesRead;
}
- (NSInteger)readData:(NSData *)data
intoBuffer:(uint8_t *)buffer
maxLength:(NSUInteger)length
{
NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length));
[data getBytes:buffer range:range];
_phaseReadOffset += range.length;
if (((NSUInteger)_phaseReadOffset) >= [data length]) {
[self transitionToNextPhase];
}
return (NSInteger)range.length;
}
- (BOOL)transitionToNextPhase {
if (![[NSThread currentThread] isMainThread]) {
dispatch_sync(dispatch_get_main_queue(), ^{
[self transitionToNextPhase];
});
return YES;
}
switch (_phase) {
case AFEncapsulationBoundaryPhase:
_phase = AFHeaderPhase;
break;
case AFHeaderPhase:
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[self.inputStream open];
_phase = AFBodyPhase;
break;
case AFBodyPhase:
[self.inputStream close];
_phase = AFFinalBoundaryPhase;
break;
case AFFinalBoundaryPhase:
default:
_phase = AFEncapsulationBoundaryPhase;
break;
}
_phaseReadOffset = 0;
return YES;
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(NSZone *)zone {
AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init];
bodyPart.stringEncoding = self.stringEncoding;
bodyPart.headers = self.headers;
bodyPart.bodyContentLength = self.bodyContentLength;
bodyPart.body = self.body;
bodyPart.boundary = self.boundary;
return bodyPart;
}
@end
#pragma mark -
@implementation AFJSONRequestSerializer
+ (instancetype)serializer {
return [self serializerWithWritingOptions:(NSJSONWritingOptions)0];
}
+ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions
{
AFJSONRequestSerializer *serializer = [[self alloc] init];
serializer.writingOptions = writingOptions;
return serializer;
}
#pragma mark - AFURLRequestSerialization
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(request);
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
return [super requestBySerializingRequest:request withParameters:parameters error:error];
}
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
if (![request valueForHTTPHeaderField:field]) {
[mutableRequest setValue:value forHTTPHeaderField:field];
}
}];
if (parameters) {
if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
[mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
}
[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
// 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 <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h>
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 <NSObject, NSSecureCoding, NSCopying>
/**
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 <AFURLResponseSerialization>
- (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 <NSString *> *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 <id<AFURLResponseSerialization>> *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 <id<AFURLResponseSerialization>> *)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
// 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 <TargetConditionals.h>
#if TARGET_OS_IOS
#import <UIKit/UIKit.h>
#elif TARGET_OS_WATCH
#import <WatchKit/WatchKit.h>
#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
#import <Cocoa/Cocoa.h>
#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 <NSCopying> 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 <CoreGraphics/CoreGraphics.h>
#import <UIKit/UIKit.h>
@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 <AFURLResponseSerialization> 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
// 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 <Foundation/Foundation.h>
#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 `<NSURLSessionTaskDelegate>`, `<NSURLSessionDataDelegate>`, `<NSURLSessionDownloadDelegate>`, and `<NSURLSessionDelegate>`.
## 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 <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate, NSSecureCoding, NSCopying>
/**
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 <AFURLResponseSerialization> 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 <NSURLSessionTask *> *tasks;
/**
The data tasks currently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray <NSURLSessionDataTask *> *dataTasks;
/**
The upload tasks currently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray <NSURLSessionUploadTask *> *uploadTasks;
/**
The download tasks currently run by the managed session.
*/
@property (readonly, nonatomic, strong) NSArray <NSURLSessionDownloadTask *> *downloadTasks;
///-------------------------------
/// @name Managing Callback Queues
///-------------------------------
/**
The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used.
*/
@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue;
/**
The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used.
*/
@property (nonatomic, strong, nullable) dispatch_group_t completionGroup;
///---------------------------------
/// @name Working Around System Bugs
///---------------------------------
/**
Whether to attempt to retry creation of upload tasks for background sessions when initial call returns `nil`. `NO` by default.
@bug As of iOS 7.0, there is a bug where upload tasks created for background tasks are sometimes `nil`. As a workaround, if this property is `YES`, AFNetworking will follow Apple's recommendation to try creating the task again.
@see https://github.com/AFNetworking/AFNetworking/issues/1675
*/
@property (nonatomic, assign) BOOL attemptsToRecreateUploadTasksForBackgroundSessions;
///---------------------
/// @name Initialization
///---------------------
/**
Creates and returns a manager for a session created with the specified configuration. This is the designated initializer.
@param configuration The configuration used to create the managed session.
@return A manager for a newly-created session.
*/
- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
/**
Invalidates the managed session, optionally canceling pending tasks.
@param cancelPendingTasks Whether or not to cancel pending tasks.
*/
- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks;
///-------------------------
/// @name Running Data Tasks
///-------------------------
/**
Creates an `NSURLSessionDataTask` with the specified request.
@param request The HTTP request for the request.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
*/
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler DEPRECATED_ATTRIBUTE;
/**
Creates an `NSURLSessionDataTask` with the specified request.
@param request The HTTP request for the request.
@param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
@param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
*/
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
///---------------------------
/// @name Running Upload Tasks
///---------------------------
/**
Creates an `NSURLSessionUploadTask` with the specified request for a local file.
@param request The HTTP request for the request.
@param fileURL A URL to the local file to be uploaded.
@param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
@see `attemptsToRecreateUploadTasksForBackgroundSessions`
*/
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromFile:(NSURL *)fileURL
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
/**
Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body.
@param request The HTTP request for the request.
@param bodyData A data object containing the HTTP body to be uploaded.
@param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
*/
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromData:(nullable NSData *)bodyData
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
/**
Creates an `NSURLSessionUploadTask` with the specified streaming request.
@param request The HTTP request for the request.
@param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue.
@param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any.
*/
- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request
progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler;
///-----------------------------
/// @name Running Download Tasks
///-----------------------------
/**
Creates an `NSURLSessionDownloadTask` with the specified request.
@param request The HTTP request for the request.
@param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
@param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
@param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
@warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method.
*/
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request
progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler;
/**
Creates an `NSURLSessionDownloadTask` with the specified resume data.
@param resumeData The data used to resume downloading.
@param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue.
@param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL.
@param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any.
*/
- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData
progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock
destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination
completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler;
///---------------------------------
/// @name Getting Progress for Tasks
///---------------------------------
/**
Returns the upload progress of the specified task.
@param task The session task. Must not be `nil`.
@return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable.
*/
- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task;
/**
Returns the download progress of the specified task.
@param task The session task. Must not be `nil`.
@return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable.
*/
- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task;
///-----------------------------------------
/// @name Setting Session Delegate Callbacks
///-----------------------------------------
/**
Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`.
@param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation.
*/
- (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block;
/**
Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`.
@param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge.
*/
- (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block;
///--------------------------------------
/// @name Setting Task Delegate Callbacks
///--------------------------------------
/**
Sets a block to be executed when a task requires a new request body stream to send to the remote server, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:needNewBodyStream:`.
@param block A block object to be executed when a task requires a new request body stream.
*/
- (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block;
/**
Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`.
@param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response.
*/
- (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * (^)(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
// 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 <objc/runtime.h>
#ifndef NSFoundationVersionNumber_iOS_8_0
#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug 1140.11
#else
#define NSFoundationVersionNumber_With_Fixed_5871104061079552_bug NSFoundationVersionNumber_iOS_8_0
#endif
static dispatch_queue_t url_session_manager_creation_queue() {
static dispatch_queue_t af_url_session_manager_creation_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_url_session_manager_creation_queue = dispatch_queue_create("com.alamofire.networking.session.manager.creation", DISPATCH_QUEUE_SERIAL);
});
return af_url_session_manager_creation_queue;
}
static void url_session_manager_create_task_safely(dispatch_block_t block) {
if (NSFoundationVersionNumber < NSFoundationVersionNumber_With_Fixed_5871104061079552_bug) {
// Fix of bug
// Open Radar:http://openradar.appspot.com/radar?id=5871104061079552 (status: Fixed in iOS8)
// Issue about:https://github.com/AFNetworking/AFNetworking/issues/2093
dispatch_sync(url_session_manager_creation_queue(), block);
} else {
block();
}
}
static dispatch_queue_t url_session_manager_processing_queue() {
static dispatch_queue_t af_url_session_manager_processing_queue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_url_session_manager_processing_queue = dispatch_queue_create("com.alamofire.networking.session.manager.processing", DISPATCH_QUEUE_CONCURRENT);
});
return af_url_session_manager_processing_queue;
}
static dispatch_group_t url_session_manager_completion_group() {
static dispatch_group_t af_url_session_manager_completion_group;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
af_url_session_manager_completion_group = dispatch_group_create();
});
return af_url_session_manager_completion_group;
}
NSString * const AFNetworkingTaskDidResumeNotification = @"com.alamofire.networking.task.resume";
NSString * const AFNetworkingTaskDidCompleteNotification = @"com.alamofire.networking.task.complete";
NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend";
NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate";
NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error";
NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse";
NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer";
NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata";
NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error";
NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath";
static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock";
static NSUInteger const AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask = 3;
typedef void (^AFURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error);
typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential);
typedef NSURLRequest * (^AFURLSessionTaskWillPerformHTTPRedirectionBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request);
typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionTaskDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential);
typedef void (^AFURLSessionDidFinishEventsForBackgroundURLSessionBlock)(NSURLSession *session);
typedef NSInputStream * (^AFURLSessionTaskNeedNewBodyStreamBlock)(NSURLSession *session, NSURLSessionTask *task);
typedef void (^AFURLSessionTaskDidSendBodyDataBlock)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend);
typedef void (^AFURLSessionTaskDidCompleteBlock)(NSURLSession *session, NSURLSessionTask *task, NSError *error);
typedef NSURLSessionResponseDisposition (^AFURLSessionDataTaskDidReceiveResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response);
typedef void (^AFURLSessionDataTaskDidBecomeDownloadTaskBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask);
typedef void (^AFURLSessionDataTaskDidReceiveDataBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data);
typedef NSCachedURLResponse * (^AFURLSessionDataTaskWillCacheResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse);
typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location);
typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite);
typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes);
typedef void (^AFURLSessionTaskProgressBlock)(NSProgress *);
typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error);
#pragma mark -
@interface AFURLSessionManagerTaskDelegate : NSObject <NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
@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<NSString *,id> *)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
{
__strong AFURLSessionManager *manager = self.manager;
__block id responseObject = nil;
__block NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer;
//Performance Improvement from #2672
NSData *data = nil;
if (self.mutableData) {
data = [self.mutableData copy];
//We no longer need the reference, so nil it out to gain back some memory.
self.mutableData = nil;
}
if (self.downloadFileURL) {
userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL;
} else if (data) {
userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data;
}
if (error) {
userInfo[AFNetworkingTaskDidCompleteErrorKey] = error;
dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
if (self.completionHandler) {
self.completionHandler(task.response, responseObject, error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
});
});
} else {
dispatch_async(url_session_manager_processing_queue(), ^{
NSError *serializationError = nil;
responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError];
if (self.downloadFileURL) {
responseObject = self.downloadFileURL;
}
if (responseObject) {
userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject;
}
if (serializationError) {
userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError;
}
dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{
if (self.completionHandler) {
self.completionHandler(task.response, responseObject, serializationError);
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo];
});
});
});
}
}
#pragma mark - 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 <AFURLResponseSerialization>)responseSerializer {
NSParameterAssert(responseSerializer);
_responseSerializer = responseSerializer;
}
#pragma mark -
- (void)addNotificationObserverForTask:(NSURLSessionTask *)task {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:task];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:task];
}
- (void)removeNotificationObserverForTask:(NSURLSessionTask *)task {
[[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidSuspendNotification object:task];
[[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidResumeNotification object:task];
}
#pragma mark -
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
return [self dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:completionHandler];
}
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock
downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock
completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler {
__block NSURLSessionDataTask *dataTask = nil;
url_session_manager_create_task_safely(^{
dataTask = [self.session dataTaskWithRequest:request];
});
[self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler];
return dataTask;
}
#pragma mark -
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromFile:(NSURL *)fileURL
progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
{
__block NSURLSessionUploadTask *uploadTask = nil;
url_session_manager_create_task_safely(^{
uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL];
});
// uploadTask may be nil on iOS7 because uploadTaskWithRequest:fromFile: may return nil despite being documented as nonnull (https://devforums.apple.com/message/926113#926113)
if (!uploadTask && self.attemptsToRecreateUploadTasksForBackgroundSessions && self.session.configuration.identifier) {
for (NSUInteger attempts = 0; !uploadTask && attempts < AFMaximumNumberOfAttemptsToRecreateBackgroundSessionUploadTask; attempts++) {
uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL];
}
}
[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
/*
Copyright (c) 2013-2014 RedBearLab
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/Foundation.h>
#if TARGET_OS_IPHONE
#import <CoreBluetooth/CoreBluetooth.h>
#else
#import <IOBluetooth/IOBluetooth.h>
#endif
@protocol BLEDelegate
@optional
-(void) bleDidConnect;
-(void) bleDidDisconnect;
-(void) bleDidUpdateRSSI:(NSNumber *) rssi;
-(void) bleDidReceiveData:(unsigned char *) data length:(int) length;
@required
@end
@interface BLE : NSObject <CBCentralManagerDelegate, CBPeripheralDelegate> {
}
@property (nonatomic,assign) id <BLEDelegate> delegate;
@property (strong, nonatomic) NSMutableArray *peripherals;
@property (strong, nonatomic) NSMutableArray *peripheralsRssi;
@property (strong, nonatomic) CBCentralManager *CM;
@property (strong, nonatomic) CBPeripheral *activePeripheral;
-(void) enableReadNotification:(CBPeripheral *)p;
-(void) read;
-(void) writeValue:(CBUUID *)serviceUUID characteristicUUID:(CBUUID *)characteristicUUID p:(CBPeripheral *)p data:(NSData *)data;
-(BOOL) isConnected;
-(void) write:(NSData *)d;
-(void) readRSSI;
-(void) controlSetup;
-(int) findBLEPeripherals:(int) timeout;
-(void) connectPeripheral:(CBPeripheral *)peripheral;
-(UInt16) swap:(UInt16) s;
-(const char *) centralManagerStateToString:(int)state;
-(void) scanTimer:(NSTimer *)timer;
-(void) printKnownPeripherals;
-(void) printPeripheralInfo:(CBPeripheral*)peripheral;
-(void) getAllServicesFromPeripheral:(CBPeripheral *)p;
-(void) getAllCharacteristicsFromPeripheral:(CBPeripheral *)p;
-(CBService *) findServiceFromUUID:(CBUUID *)UUID p:(CBPeripheral *)p;
-(CBCharacteristic *) findCharacteristicFromUUID:(CBUUID *)UUID service:(CBService*)service;
//-(NSString *) NSUUIDToString:(NSUUID *) UUID;
-(NSString *) CBUUIDToString:(CBUUID *) UUID;
-(int) compareCBUUID:(CBUUID *) UUID1 UUID2:(CBUUID *)UUID2;
-(int) compareCBUUIDToInt:(CBUUID *) UUID1 UUID2:(UInt16)UUID2;
-(UInt16) CBUUIDToInt:(CBUUID *) UUID;
-(BOOL) UUIDSAreEqual:(NSUUID *)UUID1 UUID2:(NSUUID *)UUID2;
@end
/*
Copyright (c) 2013-2014 RedBearLab
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 "BLE.h"
#import "BLEDefines.h"
@implementation BLE
@synthesize delegate;
@synthesize CM;
@synthesize peripherals;
@synthesize peripheralsRssi;
@synthesize activePeripheral;
static bool isConnected = false;
static int rssi = 0;
-(void) readRSSI
{
[activePeripheral readRSSI];
}
-(BOOL) isConnected
{
return isConnected;
}
-(void) read
{
CBUUID *uuid_service = [CBUUID UUIDWithString:@RBL_SERVICE_UUID];
CBUUID *uuid_char = [CBUUID UUIDWithString:@RBL_CHAR_TX_UUID];
[self readValue:uuid_service characteristicUUID:uuid_char p:activePeripheral];
}
-(void) write:(NSData *)d
{
CBUUID *uuid_service = [CBUUID UUIDWithString:@RBL_SERVICE_UUID];
CBUUID *uuid_char = [CBUUID UUIDWithString:@RBL_CHAR_RX_UUID];
[self writeValue:uuid_service characteristicUUID:uuid_char p:activePeripheral data:d];
}
-(void) enableReadNotification:(CBPeripheral *)p
{
CBUUID *uuid_service = [CBUUID UUIDWithString:@RBL_SERVICE_UUID];
CBUUID *uuid_char = [CBUUID UUIDWithString:@RBL_CHAR_TX_UUID];
[self notification:uuid_service characteristicUUID:uuid_char p:p on:YES];
}
-(void) notification:(CBUUID *)serviceUUID characteristicUUID:(CBUUID *)characteristicUUID p:(CBPeripheral *)p on:(BOOL)on
{
CBService *service = [self findServiceFromUUID:serviceUUID p:p];
if (!service)
{
NSLog(@"Could not find service with UUID %@ on peripheral with UUID %@",
[self CBUUIDToString:serviceUUID],
p.identifier.UUIDString);
return;
}
CBCharacteristic *characteristic = [self findCharacteristicFromUUID:characteristicUUID service:service];
if (!characteristic)
{
NSLog(@"Could not find characteristic with UUID %@ on service with UUID %@ on peripheral with UUID %@",
[self CBUUIDToString:characteristicUUID],
[self CBUUIDToString:serviceUUID],
p.identifier.UUIDString);
return;
}
[p setNotifyValue:on forCharacteristic:characteristic];
}
-(UInt16) frameworkVersion
{
return RBL_BLE_FRAMEWORK_VER;
}
-(NSString *) CBUUIDToString:(CBUUID *) cbuuid;
{
NSData *data = cbuuid.data;
if ([data length] == 2)
{
const unsigned char *tokenBytes = [data bytes];
return [NSString stringWithFormat:@"%02x%02x", tokenBytes[0], tokenBytes[1]];
}
else if ([data length] == 16)
{
NSUUID* nsuuid = [[NSUUID alloc] initWithUUIDBytes:[data bytes]];
return [nsuuid UUIDString];
}
return [cbuuid description];
}
-(void) readValue: (CBUUID *)serviceUUID characteristicUUID:(CBUUID *)characteristicUUID p:(CBPeripheral *)p
{
CBService *service = [self findServiceFromUUID:serviceUUID p:p];
if (!service)
{
NSLog(@"Could not find service with UUID %@ on peripheral with UUID %@",
[self CBUUIDToString:serviceUUID],
p.identifier.UUIDString);
return;
}
CBCharacteristic *characteristic = [self findCharacteristicFromUUID:characteristicUUID service:service];
if (!characteristic)
{
NSLog(@"Could not find characteristic with UUID %@ on service with UUID %@ on peripheral with UUID %@",
[self CBUUIDToString:characteristicUUID],
[self CBUUIDToString:serviceUUID],
p.identifier.UUIDString);
return;
}
[p readValueForCharacteristic:characteristic];
}
-(void) writeValue:(CBUUID *)serviceUUID characteristicUUID:(CBUUID *)characteristicUUID p:(CBPeripheral *)p data:(NSData *)data
{
CBService *service = [self findServiceFromUUID:serviceUUID p:p];
if (!service)
{
NSLog(@"Could not find service with UUID %@ on peripheral with UUID %@",
[self CBUUIDToString:serviceUUID],
p.identifier.UUIDString);
return;
}
CBCharacteristic *characteristic = [self findCharacteristicFromUUID:characteristicUUID service:service];
if (!characteristic)
{
NSLog(@"Could not find characteristic with UUID %@ on service with UUID %@ on peripheral with UUID %@",
[self CBUUIDToString:characteristicUUID],
[self CBUUIDToString:serviceUUID],
p.identifier.UUIDString);
return;
}
[p writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
}
-(UInt16) swap:(UInt16)s
{
UInt16 temp = s << 8;
temp |= (s >> 8);
return temp;
}
- (void) controlSetup
{
self.CM = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
- (int) findBLEPeripherals:(int) timeout
{
NSLog(@"start finding");
if (self.CM.state != CBCentralManagerStatePoweredOn)
{
NSLog(@"CoreBluetooth not correctly initialized !");
NSLog(@"State = %d (%s)\r\n", self.CM.state, [self centralManagerStateToString:self.CM.state]);
return -1;
}
[NSTimer scheduledTimerWithTimeInterval:(float)timeout target:self selector:@selector(scanTimer:) userInfo:nil repeats:NO];
#if TARGET_OS_IPHONE
[self.CM scanForPeripheralsWithServices:[NSArray arrayWithObject:[CBUUID UUIDWithString:@RBL_SERVICE_UUID]] options:nil];
#else
[self.CM scanForPeripheralsWithServices:nil options:nil]; // Start scanning
#endif
NSLog(@"scanForPeripheralsWithServices");
return 0; // Started scanning OK !
}
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;
{
[[self delegate] bleDidDisconnect];
isConnected = false;
}
- (void) connectPeripheral:(CBPeripheral *)peripheral
{
NSLog(@"Connecting to peripheral with UUID : %@", peripheral.identifier.UUIDString);
self.activePeripheral = peripheral;
self.activePeripheral.delegate = self;
[self.CM connectPeripheral:self.activePeripheral
options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
}
- (const char *) centralManagerStateToString: (int)state
{
switch(state)
{
case CBCentralManagerStateUnknown:
return "State unknown (CBCentralManagerStateUnknown)";
case CBCentralManagerStateResetting:
return "State resetting (CBCentralManagerStateUnknown)";
case CBCentralManagerStateUnsupported:
return "State BLE unsupported (CBCentralManagerStateResetting)";
case CBCentralManagerStateUnauthorized:
return "State unauthorized (CBCentralManagerStateUnauthorized)";
case CBCentralManagerStatePoweredOff:
return "State BLE powered off (CBCentralManagerStatePoweredOff)";
case CBCentralManagerStatePoweredOn:
return "State powered up and ready (CBCentralManagerStatePoweredOn)";
default:
return "State unknown";
}
return "Unknown state";
}
- (void) scanTimer:(NSTimer *)timer
{
[self.CM stopScan];
NSLog(@"Stopped Scanning");
NSLog(@"Known peripherals : %lu", (unsigned long)[self.peripherals count]);
[self printKnownPeripherals];
}
- (void) printKnownPeripherals
{
NSLog(@"List of currently known peripherals :");
for (int i = 0; i < self.peripherals.count; i++)
{
CBPeripheral *p = [self.peripherals objectAtIndex:i];
if (p.identifier != NULL)
NSLog(@"%d | %@", i, p.identifier.UUIDString);
else
NSLog(@"%d | NULL", i);
[self printPeripheralInfo:p];
}
}
- (void) printPeripheralInfo:(CBPeripheral*)peripheral
{
NSLog(@"------------------------------------");
NSLog(@"Peripheral Info :");
if (peripheral.identifier != NULL)
NSLog(@"UUID : %@", peripheral.identifier.UUIDString);
else
NSLog(@"UUID : NULL");
NSLog(@"Name : %@", peripheral.name);
NSLog(@"-------------------------------------");
}
- (BOOL) UUIDSAreEqual:(NSUUID *)UUID1 UUID2:(NSUUID *)UUID2
{
if ([UUID1.UUIDString isEqualToString:UUID2.UUIDString])
return TRUE;
else
return FALSE;
}
-(void) getAllServicesFromPeripheral:(CBPeripheral *)p
{
[p discoverServices:nil]; // Discover all services without filter
}
-(void) getAllCharacteristicsFromPeripheral:(CBPeripheral *)p
{
for (int i=0; i < p.services.count; i++)
{
CBService *s = [p.services objectAtIndex:i];
// printf("Fetching characteristics for service with UUID : %s\r\n",[self CBUUIDToString:s.UUID]);
[p discoverCharacteristics:nil forService:s];
}
}
-(int) compareCBUUID:(CBUUID *) UUID1 UUID2:(CBUUID *)UUID2
{
char b1[16];
char b2[16];
[UUID1.data getBytes:b1];
[UUID2.data getBytes:b2];
if (memcmp(b1, b2, UUID1.data.length) == 0)
return 1;
else
return 0;
}
-(int) compareCBUUIDToInt:(CBUUID *)UUID1 UUID2:(UInt16)UUID2
{
char b1[16];
[UUID1.data getBytes:b1];
UInt16 b2 = [self swap:UUID2];
if (memcmp(b1, (char *)&b2, 2) == 0)
return 1;
else
return 0;
}
-(UInt16) CBUUIDToInt:(CBUUID *) UUID
{
char b1[16];
[UUID.data getBytes:b1];
return ((b1[0] << 8) | b1[1]);
}
-(CBUUID *) IntToCBUUID:(UInt16)UUID
{
char t[16];
t[0] = ((UUID >> 8) & 0xff); t[1] = (UUID & 0xff);
NSData *data = [[NSData alloc] initWithBytes:t length:16];
return [CBUUID UUIDWithData:data];
}
-(CBService *) findServiceFromUUID:(CBUUID *)UUID p:(CBPeripheral *)p
{
for(int i = 0; i < p.services.count; i++)
{
CBService *s = [p.services objectAtIndex:i];
if ([self compareCBUUID:s.UUID UUID2:UUID])
return s;
}
return nil; //Service not found on this peripheral
}
-(CBCharacteristic *) findCharacteristicFromUUID:(CBUUID *)UUID service:(CBService*)service
{
for(int i=0; i < service.characteristics.count; i++)
{
CBCharacteristic *c = [service.characteristics objectAtIndex:i];
if ([self compareCBUUID:c.UUID UUID2:UUID]) return c;
}
return nil; //Characteristic not found on this service
}
#if TARGET_OS_IPHONE
//-- no need for iOS
#else
- (BOOL) isLECapableHardware
{
NSString * state = nil;
switch ([CM state])
{
case CBCentralManagerStateUnsupported:
state = @"The platform/hardware doesn't support Bluetooth Low Energy.";
break;
case CBCentralManagerStateUnauthorized:
state = @"The app is not authorized to use Bluetooth Low Energy.";
break;
case CBCentralManagerStatePoweredOff:
state = @"Bluetooth is currently powered off.";
break;
case CBCentralManagerStatePoweredOn:
return TRUE;
case CBCentralManagerStateUnknown:
default:
return FALSE;
}
NSLog(@"Central manager state: %@", state);
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:state];
[alert addButtonWithTitle:@"OK"];
[alert setIcon:[[NSImage alloc] initWithContentsOfFile:@"AppIcon"]];
[alert beginSheetModalForWindow:nil modalDelegate:self didEndSelector:nil contextInfo:nil];
return FALSE;
}
#endif
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
#if TARGET_OS_IPHONE
NSLog(@"Status of CoreBluetooth central manager changed %d (%s)", central.state, [self centralManagerStateToString:central.state]);
#else
[self isLECapableHardware];
#endif
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
if (!self.peripherals) {
self.peripherals = [[NSMutableArray alloc] initWithObjects:peripheral,nil];
self.peripheralsRssi = [[NSMutableArray alloc] initWithObjects:RSSI, nil];
}
else
{
for(int i = 0; i < self.peripherals.count; i++)
{
CBPeripheral *p = [self.peripherals objectAtIndex:i];
if ((p.identifier == NULL) || (peripheral.identifier == NULL))
continue;
if ([self UUIDSAreEqual:p.identifier UUID2:peripheral.identifier])
{
[self.peripherals replaceObjectAtIndex:i withObject:peripheral];
NSLog(@"Duplicate UUID found updating...");
return;
}
}
[self.peripherals addObject:peripheral];
[self.peripheralsRssi addObject:RSSI];
NSLog(@"New UUID, adding");
}
NSLog(@"didDiscoverPeripheral");
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
if (peripheral.identifier != NULL)
NSLog(@"Connected to %@ successful", peripheral.identifier.UUIDString);
else
NSLog(@"Connected to NULL successful");
self.activePeripheral = peripheral;
[self.activePeripheral discoverServices:nil];
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
if (!error)
{
// printf("Characteristics of service with UUID : %s found\n",[self CBUUIDToString:service.UUID]);
for (int i=0; i < service.characteristics.count; i++)
{
// CBCharacteristic *c = [service.characteristics objectAtIndex:i];
// printf("Found characteristic %s\n",[ self CBUUIDToString:c.UUID]);
CBService *s = [peripheral.services objectAtIndex:(peripheral.services.count - 1)];
if ([service.UUID isEqual:s.UUID])
{
[self enableReadNotification:activePeripheral];
[[self delegate] bleDidConnect];
isConnected = true;
break;
}
}
}
else
{
NSLog(@"Characteristic discorvery unsuccessful!");
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
if (!error)
{
// printf("Services of peripheral with UUID : %s found\n",[self UUIDToString:peripheral.UUID]);
[self getAllCharacteristicsFromPeripheral:peripheral];
}
else
{
NSLog(@"Service discovery was unsuccessful!");
}
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if (!error)
{
// printf("Updated notification state for characteristic with UUID %s on service with UUID %s on peripheral with UUID %s\r\n",[self CBUUIDToString:characteristic.UUID],[self CBUUIDToString:characteristic.service.UUID],[self UUIDToString:peripheral.UUID]);
}
else
{
NSLog(@"Error in setting notification state for characteristic with UUID %@ on service with UUID %@ on peripheral with UUID %@",
[self CBUUIDToString:characteristic.UUID],
[self CBUUIDToString:characteristic.service.UUID],
peripheral.identifier.UUIDString);
NSLog(@"Error code was %s", [[error description] cStringUsingEncoding:NSStringEncodingConversionAllowLossy]);
}
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
unsigned char data[20];
static unsigned char buf[512];
static int len = 0;
NSInteger data_len;
if (!error)
{
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@RBL_CHAR_TX_UUID]])
{
data_len = characteristic.value.length;
[characteristic.value getBytes:data length:data_len];
if (data_len == 20)
{
memcpy(&buf[len], data, 20);
len += data_len;
if (len >= 64)
{
[[self delegate] bleDidReceiveData:buf length:len];
len = 0;
}
}
else if (data_len < 20)
{
memcpy(&buf[len], data, data_len);
len += data_len;
[[self delegate] bleDidReceiveData:buf length:len];
len = 0;
}
}
}
else
{
NSLog(@"updateValueForCharacteristic failed!");
}
}
- (void)peripheralDidUpdateRSSI:(CBPeripheral *)peripheral error:(NSError *)error
{
if (!isConnected)
return;
if (rssi != peripheral.RSSI.intValue)
{
rssi = peripheral.RSSI.intValue;
[[self delegate] bleDidUpdateRSSI:activePeripheral.RSSI];
}
}
@end
/*
Copyright (c) 2013-2014 RedBearLab
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.
*/
// RBL Service
#define RBL_SERVICE_UUID "713D0000-503E-4C75-BA94-3148F18D941E"
#define RBL_CHAR_TX_UUID "713D0002-503E-4C75-BA94-3148F18D941E"
#define RBL_CHAR_RX_UUID "713D0003-503E-4C75-BA94-3148F18D941E"
#define RBL_BLE_FRAMEWORK_VER 0x0200
//
// BootSettingController.h
// jacket_test_ios
//
// Created by ドラッサル 亜嵐 on 2017/07/24.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "BleProtocol.h"
#import "BLE.h"
typedef enum {
EEPROM_WP_OFF,
EEPROM_WP_OFF_DONE,
EEPROM_WP_ON,
EEPROM_WP_ON_DONE,
FIRMWARE_IMAGE_SELECT_0,
FIRMWARE_IMAGE_SELECT_0_DONE,
FIRMWARE_IMAGE_SELECT_1,
FIRMWARE_IMAGE_SELECT_1_DONE,
RESET,
RESET_DONE,
DONE
} BootSettingBleCommandState;
@interface BootSettingController : UIViewController<BLEProtocolDelegate> {
BootSettingBleCommandState bleCommandState;
BootSettingBleCommandState bleCommandStateNext;
}
@property (strong, nonatomic) BleProtocol *protocol;
@property (nonatomic,assign) id <BLEProtocolDelegate> lastProtocolDelegate;
@end
//
// BootSettingController.m
// jacket_test_ios
//
// Created by ドラッサル 亜嵐 on 2017/07/24.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import "BootSettingController.h"
@interface BootSettingController ()
@end
@implementation BootSettingController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated {
self.lastProtocolDelegate = self.protocol.delegate;
self.protocol.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated {
self.protocol.delegate = self.lastProtocolDelegate;
}
- (void)showAlert:(NSString*)title message:(NSString*)message{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
- (IBAction)cancelButtonClicked:(id)sender {
[self dismissViewControllerAnimated:YES completion:Nil];
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)selectImage0Clicked:(id)sender {
bleCommandState = EEPROM_WP_OFF;
bleCommandStateNext = FIRMWARE_IMAGE_SELECT_0;
[self bleCommandTask];
NSLog(@"selectImage0Clicked done");
}
- (IBAction)selectImage1Clicked:(id)sender {
bleCommandState = EEPROM_WP_OFF;
bleCommandStateNext = FIRMWARE_IMAGE_SELECT_1;
[self bleCommandTask];
NSLog(@"selectImage0Clicked done");
}
- (BOOL)bleCommandTask {
switch(bleCommandState) {
case EEPROM_WP_OFF:
[[self protocol]putData:@"eepromWriteProtect" data:@"0"];
break;
case EEPROM_WP_OFF_DONE:
bleCommandState = bleCommandStateNext;
[self bleCommandTask];
break;
case EEPROM_WP_ON:
[[self protocol]putData:@"eepromWriteProtect" data:@"1"];
break;
case EEPROM_WP_ON_DONE:
bleCommandState = DONE;
[self bleCommandTask];
break;
case FIRMWARE_IMAGE_SELECT_0:
[[self protocol]putData:@"firmwareImageSelect" data:@"0"];
break;
case FIRMWARE_IMAGE_SELECT_0_DONE:
bleCommandState = EEPROM_WP_ON;
[self bleCommandTask];
break;
case FIRMWARE_IMAGE_SELECT_1:
[[self protocol]putData:@"firmwareImageSelect" data:@"1"];
break;
case FIRMWARE_IMAGE_SELECT_1_DONE:
bleCommandState = EEPROM_WP_ON;
[self bleCommandTask];
break;
case RESET:
[[self protocol]putData:@"systemReset" data:nil];
break;
case RESET_DONE:
{
NSLog(@"Ble command set done!");
break;
}
case DONE:
{
NSLog(@"Ble command set done!");
[self showAlert:@"EEPROM書き込み" message:@"EEPROMに保存しました。"];
break;
}
}
return false;
}
- (void)protocolDidGetData:(NSString *)dataType data:(NSString *)dataData {
if([dataType isEqualToString:@"firmwareImageSelect"]) {
if([dataData isEqualToString:@"0"]) {
NSLog(@"firmwareImageSelect 0");
bleCommandState = FIRMWARE_IMAGE_SELECT_0_DONE;
[self bleCommandTask];
} else if([dataData isEqualToString:@"1"]) {
NSLog(@"firmwareImageSelect 1");
bleCommandState = FIRMWARE_IMAGE_SELECT_1_DONE;
[self bleCommandTask];
}
} else if([dataType isEqualToString:@"eepromWriteProtect"]) {
if([dataData isEqualToString:@"0"]) {
NSLog(@"eepromWriteProtect 0");
bleCommandState = EEPROM_WP_OFF_DONE;
[self bleCommandTask];
} else if([dataData isEqualToString:@"1"]) {
NSLog(@"eepromWriteProtect 1");
bleCommandState = EEPROM_WP_ON_DONE;
[self bleCommandTask];
}
} else if([dataType isEqualToString:@"systemReset"]) {
NSLog(@"systemReset");
bleCommandState = RESET_DONE;
[self bleCommandTask];
}
}
@end
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="BootSettingController">
<connections>
<outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<navigationBar contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="fTM-mh-INi">
<rect key="frame" x="0.0" y="23" width="375" height="44"/>
<items>
<navigationItem title="起動設定" id="gUm-My-XyB">
<barButtonItem key="leftBarButtonItem" title="戻る" id="FKk-cz-oNn">
<connections>
<action selector="cancelButtonClicked:" destination="-1" id="2WK-pK-yx1"/>
</connections>
</barButtonItem>
</navigationItem>
</items>
</navigationBar>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="LXt-Fp-Egr">
<rect key="frame" x="149" y="157" width="77" height="30"/>
<state key="normal" title="イメージ1"/>
<connections>
<action selector="selectImage1Clicked:" destination="-1" eventType="touchUpInside" id="3DN-JD-Fh5"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="xKp-zn-ktL">
<rect key="frame" x="95" y="97" width="184" height="30"/>
<state key="normal" title="ファームウェア更新モード"/>
<connections>
<action selector="selectImage0Clicked:" destination="-1" eventType="touchUpInside" id="Hfa-rm-ZOf"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="xKp-zn-ktL" firstAttribute="top" secondItem="fTM-mh-INi" secondAttribute="bottom" constant="30" id="1On-Cz-oFe"/>
<constraint firstItem="fTM-mh-INi" firstAttribute="centerX" secondItem="xKp-zn-ktL" secondAttribute="centerX" id="8Vf-o5-eah"/>
<constraint firstAttribute="trailing" secondItem="fTM-mh-INi" secondAttribute="trailing" id="9Fe-2W-A8G"/>
<constraint firstItem="xKp-zn-ktL" firstAttribute="centerX" secondItem="LXt-Fp-Egr" secondAttribute="centerX" id="N6N-OR-fWN"/>
<constraint firstItem="LXt-Fp-Egr" firstAttribute="top" secondItem="xKp-zn-ktL" secondAttribute="bottom" constant="30" id="ZOf-Ae-7hS"/>
<constraint firstItem="fTM-mh-INi" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" id="iZR-EP-iEa"/>
<constraint firstItem="xKp-zn-ktL" firstAttribute="centerX" secondItem="i5M-Pr-FkT" secondAttribute="centerX" id="kul-HK-4Cd"/>
<constraint firstItem="fTM-mh-INi" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="23" id="m5P-3V-zcJ"/>
<constraint firstItem="LXt-Fp-Egr" firstAttribute="centerX" secondItem="i5M-Pr-FkT" secondAttribute="centerX" id="wEs-z8-waM"/>
</constraints>
</view>
</objects>
</document>
//
// DBManager.h
// SQLite3DBSample
//
// Created by ドラッサル 亜嵐 on 2016/02/03.
// Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol DBManagerDelegate
@optional
- (void)gotData:(NSString *)data;
@required
@end
@interface DBManager : NSObject
@property (nonatomic,assign) id <DBManagerDelegate> delegate;
@property (nonatomic, strong) NSMutableArray *arrColumnNames;
@property (nonatomic) int affectedRows;
@property (nonatomic) long long lastInsertedRowID;
-(NSArray *)loadDataFromDB:(NSString *)query;
-(void)executeQuery:(NSString *)query;
- (NSArray*)getFirmwareDataList;
- (NSArray*)getEepromTemplateData;
- (bool)saveFirmwareData:(NSString *)uuid
deviceType:(NSString *)deviceType
deviceModel:(NSString *)deviceModel
version:(NSString *)version
versionStamp:(NSString *)versionStamp
file:(NSString *)file;
- (bool)saveEepromTemplateData:(NSString *)recordId
recordName:(NSString *)recordName
dataId:(NSString *)dataId
deviceModel:(NSString *)dataModel
dataType:(NSString *)dataType
dataOs:(NSString *)dataOs
dataPin:(NSString *)dataPin;
- (bool)deleteFirmwareData:(NSString *)recordId;
- (bool)deleteEepromTemplateData:(NSString *)recordId;
+ (NSString*) createDatabaseIfRequiredAtPath:(NSString*)databasePath;
+ (instancetype)sharedInstance;
@end
//
// DBManager.m
// SQLite3DBSample
//
// Created by ドラッサル 亜嵐 on 2016/02/03.
// Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//
#import "DBManager.h"
#import <sqlite3.h>
@interface DBManager ()
@property (nonatomic, strong) NSString *documentsDirectory;
@property (nonatomic, strong) NSString *databaseFilename;
@property (nonatomic, strong) NSMutableArray *arrResults;
-(void)copyDatabaseIntoDocumentsDirectory;
-(void)runQuery:(const char *)query isQueryExecutable:(BOOL)queryExecutable;
@end
@implementation DBManager {
NSLock* _lock;
}
+ (NSString*) createDatabaseIfRequiredAtPath:(NSString*)databasePath {
if (databasePath == nil)
return nil;
//NSString *path = [NSString stringWithFormat:@"%@/%@", databasePath, kMainDBName];
NSString *path = [NSString stringWithFormat:@"%@/%@", databasePath, DATABASE];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
if ([fileManager fileExistsAtPath:path] == NO)
{
// The writable database does not exist, so copy the default to the appropriate location.
//NSString *defaultDBPath = [[NSBundle mainBundle] pathForResource:kMainDBName
// ofType:nil];
NSString *defaultDBPath = [[NSBundle mainBundle] pathForResource:DATABASE
ofType:nil];
BOOL success = [fileManager copyItemAtPath:defaultDBPath
toPath:path
error:&error];
if (!success)
{
NSCAssert1(0, @"Failed to create writable database file with message '%@'.", [ error localizedDescription]);
return nil;
}
}
return path;
}
- (void)initFirst {
NSLog(@"[DBManager] initFirst");
// Set the documents directory path to the documentsDirectory property.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
self.documentsDirectory = [paths objectAtIndex:0];
//NSString *dbFilenameFixed = [DBManager createDatabaseIfRequiredAtPath:dbFilename];
NSString *dbFilenameFixed = DATABASE;
// Keep the database filename.
self.databaseFilename = dbFilenameFixed;
// Copy the database file into the documents directory if necessary.
[self copyDatabaseIntoDocumentsDirectory];
// Create a sqlite object.
sqlite3 *sqlite3Database;
// Set the database file path.
NSString *databasePath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];
// Open the database.
BOOL openDatabaseResult = sqlite3_open([databasePath UTF8String], &sqlite3Database);
if(openDatabaseResult == SQLITE_OK) {
const char *sqlStatement =
"CREATE TABLE IF NOT EXISTS FIRMWARE (ID INTEGER PRIMARY KEY, FIRMWARE_UUID TEXT, FIRMWARE_DEVICE_TYPE TEXT, FIRMWARE_DEVICE_MODEL TEXT, FIRMWARE_VERSION TEXT, FIRMWARE_VERSION_STAMP TEXT, FIRMWARE_FILE TEXT);"
"CREATE TABLE IF NOT EXISTS EEPROM_TEMPLATE (ID INTEGER PRIMARY KEY, EEPROM_TEMPLATE_NAME TEXT, EEPROM_TEMPLATE_ID TEXT, EEPROM_TEMPLATE_MODEL TEXT, EEPROM_TEMPLATE_TYPE TEXT, EEPROM_TEMPLATE_OS TEXT, EEPROM_TEMPLATE_PIN TEXT);";
char *error;
if(sqlite3_exec(sqlite3Database, sqlStatement, NULL, NULL, &error) == SQLITE_OK){
NSLog(@"All tables are created");
} else {
NSLog(@"Unable to create some table %s", error);
sqlite3_free(error);
error = NULL;
}
} else {
NSLog(@"Database creation error");
}
/* BEGIN insert column if needed */
NSString *query = @"PRAGMA table_info(EEPROM_TEMPLATE)";
NSArray *result = [self loadDataFromDB:query];
//NSLog(@"%@", result);
bool columnFoundEEPROM_TEMPLATE_PIN = false;
for(id key in result) {
NSLog(@"%@", [key objectAtIndex:1]);
if([[key objectAtIndex:1] isEqualToString:@"EEPROM_TEMPLATE_PIN"]) {
columnFoundEEPROM_TEMPLATE_PIN = true;
}
}
if(!columnFoundEEPROM_TEMPLATE_PIN) {
const char *sqlStatement =
"ALTER TABLE EEPROM_TEMPLATE ADD COLUMN EEPROM_TEMPLATE_PIN TEXT;";
char *error;
if(sqlite3_exec(sqlite3Database, sqlStatement, NULL, NULL, &error) == SQLITE_OK){
NSLog(@"All tables are altered");
} else {
NSLog(@"Unable to alter some table %s", error);
sqlite3_free(error);
error = NULL;
}
}
/* END insert column if needed */
// Close the database.
sqlite3_close(sqlite3Database);
}
-(void)copyDatabaseIntoDocumentsDirectory{
// Check if the database file exists in the documents directory.
NSString *destinationPath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];
if (![[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) {
// The database file does not exist in the documents directory, so copy it from the main bundle now.
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseFilename];
NSError *error;
[[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:destinationPath error:&error];
// Check if any error occurred during copying and display it.
if (error != nil) {
NSLog(@"%@", [error localizedDescription]);
}
}
}
-(void)runQuery:(const char *)query isQueryExecutable:(BOOL)queryExecutable{
// Create a sqlite object.
sqlite3 *sqlite3Database;
// Set the database file path.
NSString *databasePath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];
// Initialize the results array.
if (self.arrResults != nil) {
[self.arrResults removeAllObjects];
self.arrResults = nil;
}
self.arrResults = [[NSMutableArray alloc] init];
// Initialize the column names array.
if (self.arrColumnNames != nil) {
[self.arrColumnNames removeAllObjects];
self.arrColumnNames = nil;
}
self.arrColumnNames = [[NSMutableArray alloc] init];
// Open the database.
BOOL openDatabaseResult = sqlite3_open([databasePath UTF8String], &sqlite3Database);
if(openDatabaseResult == SQLITE_OK) {
// Declare a sqlite3_stmt object in which will be stored the query after having been compiled into a SQLite statement.
sqlite3_stmt *compiledStatement;
// Load all data from database to memory.
BOOL prepareStatementResult = sqlite3_prepare_v2(sqlite3Database, query, -1, &compiledStatement, NULL);
if(prepareStatementResult == SQLITE_OK) {
// Check if the query is non-executable.
if (!queryExecutable){
// In this case data must be loaded from the database.
// Declare an array to keep the data for each fetched row.
NSMutableArray *arrDataRow;
// Loop through the results and add them to the results array row by row.
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Initialize the mutable array that will contain the data of a fetched row.
arrDataRow = [[NSMutableArray alloc] init];
// Get the total number of columns.
int totalColumns = sqlite3_column_count(compiledStatement);
// Go through all columns and fetch each column data.
for (int i=0; i<totalColumns; i++){
// Convert the column data to text (characters).
char *dbDataAsChars = (char *)sqlite3_column_text(compiledStatement, i);
// If there are contents in the currenct column (field) then add them to the current row array.
if (dbDataAsChars != NULL) {
// Convert the characters to string.
[arrDataRow addObject:[NSString stringWithUTF8String:dbDataAsChars]];
} else {
[arrDataRow addObject:@""];
}
// Keep the current column name.
if (self.arrColumnNames.count != totalColumns) {
dbDataAsChars = (char *)sqlite3_column_name(compiledStatement, i);
[self.arrColumnNames addObject:[NSString stringWithUTF8String:dbDataAsChars]];
}
}
// Store each fetched data row in the results array, but first check if there is actually data.
if (arrDataRow.count > 0) {
[self.arrResults addObject:arrDataRow];
}
}
}
else {
// This is the case of an executable query (insert, update, ...).
// Execute the query.
int executeQueryResults = sqlite3_step(compiledStatement);
if (executeQueryResults == SQLITE_DONE) {
// Keep the affected rows.
self.affectedRows = sqlite3_changes(sqlite3Database);
// Keep the last inserted row ID.
self.lastInsertedRowID = sqlite3_last_insert_rowid(sqlite3Database);
}
else {
// If could not execute the query show the error message on the debugger.
NSLog(@"DB Error: %s", sqlite3_errmsg(sqlite3Database));
}
}
}
else {
// In the database cannot be opened then show the error message on the debugger.
NSLog(@"%s", sqlite3_errmsg(sqlite3Database));
}
// Release the compiled statement from memory.
sqlite3_finalize(compiledStatement);
// Close the database.
sqlite3_close(sqlite3Database);
}
}
-(NSArray *)loadDataFromDB:(NSString *)query{
// Run the query and indicate that is not executable.
// The query string is converted to a char* object.
[self runQuery:[query UTF8String] isQueryExecutable:NO];
// Returned the loaded results.
return (NSArray *)self.arrResults;
}
-(void)executeQuery:(NSString *)query{
// Run the query and indicate that is executable.
[self runQuery:[query UTF8String] isQueryExecutable:YES];
}
- (NSArray*)getFirmwareDataList {
NSString *query = @"SELECT ID, FIRMWARE_UUID, FIRMWARE_DEVICE_TYPE, FIRMWARE_DEVICE_MODEL, FIRMWARE_VERSION, FIRMWARE_VERSION_STAMP, FIRMWARE_FILE FROM FIRMWARE";
NSArray *result = [self loadDataFromDB:query];
return result;
}
- (NSArray*)getEepromTemplateData {
NSString *query = @"SELECT ID, EEPROM_TEMPLATE_NAME, EEPROM_TEMPLATE_ID, EEPROM_TEMPLATE_MODEL, EEPROM_TEMPLATE_TYPE, EEPROM_TEMPLATE_OS, EEPROM_TEMPLATE_PIN FROM EEPROM_TEMPLATE";
NSArray *result = [self loadDataFromDB:query];
return result;
}
- (bool)saveFirmwareData:(NSString *)uuid
deviceType:(NSString *)deviceType
deviceModel:(NSString *)deviceModel
version:(NSString *)version
versionStamp:(NSString *)versionStamp
file:(NSString *)file
{
NSString *queryCheck = [NSString stringWithFormat:@"SELECT FIRMWARE_UUID FROM FIRMWARE WHERE FIRMWARE_UUID = '%@'",uuid];
NSArray *queryCheckResult = [self loadDataFromDB:queryCheck];
if([queryCheckResult count] != 0) {
NSString *queryUpdate = [NSString stringWithFormat:@"UPDATE FIRMWARE SET FIRMWARE_DEVICE_MODEL = '%@', FIRMWARE_DEVICE_TYPE = '%@', FIRMWARE_VERSION = '%@', FIRMWARE_VERSION_STAMP = '%@', FIRMWARE_FILE = '%@' WHERE FIRMWARE_UUID = '%@'",deviceType,deviceModel,version,versionStamp,file,uuid];
[self executeQuery:queryUpdate];
} else {
NSString *queryInsert = [NSString stringWithFormat:@"INSERT INTO FIRMWARE (FIRMWARE_UUID, FIRMWARE_DEVICE_TYPE, FIRMWARE_DEVICE_MODEL, FIRMWARE_VERSION, FIRMWARE_VERSION_STAMP, FIRMWARE_FILE) VALUES ('%@','%@','%@','%@','%@','%@')",uuid, deviceType, deviceModel, version, versionStamp, file];
[self executeQuery:queryInsert];
}
return true;
}
- (bool)saveEepromTemplateData:(NSString *)recordId
recordName:(NSString *)recordName
dataId:(NSString *)dataId
deviceModel:(NSString *)dataModel
dataType:(NSString *)dataType
dataOs:(NSString *)dataOs
dataPin:(NSString *)dataPin
{
NSString *queryCheck = [NSString stringWithFormat:@"SELECT ID FROM EEPROM_TEMPLATE WHERE ID = '%@'",recordId];
NSArray *queryCheckResult = [self loadDataFromDB:queryCheck];
if([queryCheckResult count] != 0) {
NSString *queryUpdate = [NSString stringWithFormat:@"UPDATE EEPROM_TEMPLATE SET EEPROM_TEMPLATE_NAME = '%@', EEPROM_TEMPLATE_ID = '%@', EEPROM_TEMPLATE_MODEL = '%@', EEPROM_TEMPLATE_TYPE = '%@', EEPROM_TEMPLATE_OS = '%@', EEPROM_TEMPLATE_PIN = '%@', WHERE ID = '%@'",recordName, dataId, dataModel, dataType, dataOs, dataPin, recordId];
[self executeQuery:queryUpdate];
} else {
NSString *queryInsert = [NSString stringWithFormat:@"INSERT INTO EEPROM_TEMPLATE (EEPROM_TEMPLATE_NAME, EEPROM_TEMPLATE_ID, EEPROM_TEMPLATE_MODEL, EEPROM_TEMPLATE_TYPE, EEPROM_TEMPLATE_OS, EEPROM_TEMPLATE_PIN) VALUES ('%@','%@','%@','%@','%@','%@')",recordName, dataId, dataModel, dataType, dataOs, dataPin];
[self executeQuery:queryInsert];
}
return true;
}
- (bool)deleteFirmwareData:(NSString *)recordId {
NSString *queryDelete = [NSString stringWithFormat:@"DELETE FROM FIRMWARE WHERE ID = '%@'",recordId];
[self executeQuery:queryDelete];
return true;
}
- (bool)deleteEepromTemplateData:(NSString *)recordId {
NSString *queryDelete = [NSString stringWithFormat:@"DELETE FROM EEPROM_TEMPLATE WHERE ID = '%@'",recordId];
[self executeQuery:queryDelete];
return true;
}
- (BOOL)checkForField:(NSString *)tblName colName:(NSString *)colName {
// Create a sqlite object.
sqlite3 *sqlite3Database;
// Set the database file path.
NSString *databasePath = [self.documentsDirectory stringByAppendingPathComponent:self.databaseFilename];
// Open the database.
BOOL openDatabaseResult = sqlite3_open([databasePath UTF8String], &sqlite3Database);
if(openDatabaseResult == SQLITE_OK) {
NSString *sql = [NSString stringWithFormat:@"PRAGMA table_info(%@)", tblName];
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(sqlite3Database, [sql UTF8String], -1, &stmt, NULL) != SQLITE_OK)
{
return NO;
}
while(sqlite3_step(stmt) == SQLITE_ROW)
{
NSString *fieldName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 1)];
if([colName isEqualToString:fieldName]) {
// Close the database.
sqlite3_close(sqlite3Database);
return YES;
}
}
// Close the database.
sqlite3_close(sqlite3Database);
}
return NO;
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
# pragma mark - Singleton pattern
static DBManager *_sharedInstance;
- (instancetype)init {
@throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"[Operation] Use 'sharedInstance' instead of 'init' as this class is singleton." userInfo:nil];
}
+ (instancetype)sharedInstance {
@synchronized(self) {
if (_sharedInstance == nil) {
(void) [[self alloc] initPrivate]; // ここでは代入していない
}
}
return _sharedInstance;
}
- (instancetype)initPrivate {
self = [super init];
if (self) {
// 初期処理
_lock = [[NSLock alloc] init];
[self initFirst];
}
return self;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
if (_sharedInstance == nil) {
_sharedInstance = [super allocWithZone:zone];
return _sharedInstance; // 最初の割り当てで代入し、返す
}
}
return nil;
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
@end
//
// DemoView.swift
// jacket_test_ios
//
// Created by USER on 2017/10/11.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
import UIKit
class DemoView: UIView {
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
let label = UILabel()
label.text = "Demo"
label.sizeToFit()
self.addSubview(label)
}
}
//
// EepromController.h
// jacket_test_ios
//
// Created by ドラッサル 亜嵐 on 2017/07/24.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "BleProtocol.h"
#import "BLE.h"
#import "EepromTemplateController.h"
typedef enum {
EEPROM__EEPROM_WP_OFF,
EEPROM__EEPROM_WP_OFF_DONE,
EEPROM__EEPROM_WP_ON,
EEPROM__EEPROM_WP_ON_DONE,
EEPROM__EEPROM_READ_ID,
EEPROM__EEPROM_READ_ID_DONE,
EEPROM__EEPROM_READ_MODEL,
EEPROM__EEPROM_READ_MODEL_DONE,
EEPROM__EEPROM_READ_TYPE,
EEPROM__EEPROM_READ_TYPE_DONE,
EEPROM__EEPROM_READ_OS,
EEPROM__EEPROM_READ_OS_DONE,
EEPROM__EEPROM_READ_PIN,
EEPROM__EEPROM_READ_PIN_DONE,
EEPROM__EEPROM_WRITE_ID,
EEPROM__EEPROM_WRITE_ID_DONE,
EEPROM__EEPROM_WRITE_MODEL,
EEPROM__EEPROM_WRITE_MODEL_DONE,
EEPROM__EEPROM_WRITE_TYPE,
EEPROM__EEPROM_WRITE_TYPE_DONE,
EEPROM__EEPROM_WRITE_OS,
EEPROM__EEPROM_WRITE_OS_DONE,
EEPROM__EEPROM_WRITE_PIN,
EEPROM__EEPROM_WRITE_PIN_DONE,
EEPROM__DONE
} EepromCommandState;
@interface EepromController : UIViewController<EepromTemplateControllerDelegate, BLEProtocolDelegate> {
IBOutlet UITextField *txtId;
IBOutlet UITextField *txtModel;
IBOutlet UITextField *txtType;
IBOutlet UITextField *txtOs;
IBOutlet UITextField *txtPin;
NSString *strId;
NSString *strModel;
NSString *strType;
NSString *strOs;
NSString *strPin;
EepromCommandState bleCommandState;
IBOutlet UIScrollView *scrollView;
UITextField *activeField;
}
- (IBAction)cancelButtonClicked:(id)sender;
- (IBAction)saveButtonClicked:(id)sender;
@property (strong, nonatomic) BleProtocol *protocol;
@property (nonatomic,assign) id <BLEProtocolDelegate> lastProtocolDelegate;
@end
//
// EepromController.m
// jacket_test_ios
//
// Created by ドラッサル 亜嵐 on 2017/07/24.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import "EepromController.h"
#import "EepromTemplateController.h"
#import "DBManager.h"
@interface EepromController ()
@end
@implementation EepromController
- (void)viewDidLoad {
[super viewDidLoad];
//The setup code (in viewDidLoad in your view controller)
UITapGestureRecognizer *singleFingerTap =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(handleSingleTap:)];
[self.view addGestureRecognizer:singleFingerTap];
// Do any additional setup after loading the view from its nib.
txtId.text = @"";
txtModel.text = @"";
txtType.text = @"";
txtOs.text = @"";
txtPin.text = @"";
bleCommandState = EEPROM__EEPROM_READ_ID;
[self bleCommandTask];
}
- (void)viewWillAppear:(BOOL)animated {
[self registerForKeyboardNotifications];
self.lastProtocolDelegate = self.protocol.delegate;
self.protocol.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated {
[self unregisterFromKeyboardNotifications];
self.protocol.delegate = self.lastProtocolDelegate;
}
- (void)showAlert:(NSString*)title message:(NSString*)message{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
- (void)unregisterFromKeyboardNotifications
{
/*
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
*/
}
// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
activeField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
activeField = nil;
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
scrollView.contentInset = contentInsets;
scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
[scrollView scrollRectToVisible:activeField.frame animated:YES];
}
}
/*
There are other ways you can scroll the edited area in a scroll view above an obscuring keyboard. Instead of altering the bottom content inset of the scroll view, you can extend the height of the content view by the height of the keyboard and then scroll the edited text object into view. Although the UIScrollView class has a contentSize property that you can set for this purpose, you can also adjust the frame of the content view, as shown in Listing 4-3. This code also uses the setContentOffset:animated: method to scroll the edited field into view, in this case scrolling it just above the top of the keyboard.
*/
/*
- (void)keyboardWasShown:(NSNotification*)aNotification {
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGRect bkgndRect = activeField.superview.frame;
bkgndRect.size.height += kbSize.height;
[activeField.superview setFrame:bkgndRect];
[scrollView setContentOffset:CGPointMake(0.0, activeField.frame.origin.y-kbSize.height) animated:YES];
}
*/
//The event handling method
- (void)handleSingleTap:(UITapGestureRecognizer *)recognizer
{
//CGPoint location = [recognizer locationInView:[recognizer.view superview]];
//Do stuff here...
[self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)cancelButtonClicked:(id)sender {
[self dismissViewControllerAnimated:YES completion:Nil];
}
- (IBAction)saveButtonClicked:(id)sender {
bleCommandState = EEPROM__EEPROM_WP_OFF;
[self bleCommandTask];
}
- (IBAction)resetButtonClicked:(id)sender {
txtId.text = @"";
txtModel.text = @"";
txtType.text = @"";
txtOs.text = @"";
bleCommandState = EEPROM__EEPROM_READ_ID;
[self bleCommandTask];
}
- (IBAction)templateLoadButtonClicked:(id)sender {
EepromTemplateController *viewObj=[[EepromTemplateController alloc] initWithNibName:@"EepromTemplateController" bundle:nil];
viewObj.delegate = self;
[self presentViewController:viewObj animated:YES completion: nil];
}
- (IBAction)templateSaveButtonClicked:(id)sender {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Title"
message:nil
preferredStyle:UIAlertControllerStyleAlert];
[alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
// optionally configure the text field
textField.keyboardType = UIKeyboardTypeAlphabet;
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"キャンセル"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
UITextField *textField = [alert.textFields firstObject];
textField.placeholder = @"Enter Input";
}];
[alert addAction:cancelAction];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"保存"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *action) {
UITextField *textField = [alert.textFields firstObject];
textField.placeholder = @"Enter Input";
[self clickedSaveNameInput:textField.text];
}];
[alert addAction:okAction];
[self presentViewController:alert animated:YES completion:nil];
}
- (void)clickedSaveNameInput:(NSString *)textFieldText {
NSLog(@"clickedSaveNameInput:'%@'",textFieldText);
NSString *dataIdText = txtId.text;
NSString *dataModelText = txtModel.text;
NSString *dataTypeText = txtType.text;
NSString *dataOsText = txtOs.text;
NSString *dataPinText = txtPin.text;
[[DBManager sharedInstance] saveEepromTemplateData:nil
recordName:textFieldText
dataId:dataIdText
deviceModel:dataModelText
dataType:dataTypeText
dataOs:dataOsText
dataPin:dataPinText];
}
- (void)didChoose:(NSString *)recordId
recordName:(NSString *)recordName
dataId:(NSString *)dataId
dataModel:(NSString *)dataModel
dataType:(NSString *)dataType
dataOs:(NSString *)dataOs
dataPin:(NSString *)dataPin {
txtId.text = dataId;
txtModel.text = dataModel;
txtType.text = dataType;
txtOs.text = dataOs;
txtPin.text = dataPin;
}
- (BOOL)bleCommandTask {
switch(bleCommandState) {
case EEPROM__EEPROM_WP_OFF:
[[self protocol]putData:@"eepromWriteProtect" data:@"0"];
break;
case EEPROM__EEPROM_WP_OFF_DONE:
bleCommandState = EEPROM__EEPROM_WRITE_ID;
[self bleCommandTask];
break;
case EEPROM__EEPROM_WP_ON:
[[self protocol]putData:@"eepromWriteProtect" data:@"1"];
break;
case EEPROM__EEPROM_WP_ON_DONE:
bleCommandState = EEPROM__DONE;
[self bleCommandTask];
break;
case EEPROM__EEPROM_READ_ID:
[[self protocol]putData:@"readDeviceId" data:nil];
break;
case EEPROM__EEPROM_READ_MODEL:
[[self protocol]putData:@"readDeviceModel" data:nil];
break;
case EEPROM__EEPROM_READ_TYPE:
[[self protocol]putData:@"readDeviceType" data:nil];
break;
case EEPROM__EEPROM_READ_OS:
[[self protocol]putData:@"readDeviceOs" data:nil];
break;
case EEPROM__EEPROM_READ_PIN:
[[self protocol]putData:@"readDevicePin" data:nil];
break;
case EEPROM__EEPROM_READ_ID_DONE:
bleCommandState = EEPROM__EEPROM_READ_MODEL;
[self bleCommandTask];
break;
case EEPROM__EEPROM_READ_MODEL_DONE:
bleCommandState = EEPROM__EEPROM_READ_TYPE;
[self bleCommandTask];
break;
case EEPROM__EEPROM_READ_TYPE_DONE:
bleCommandState = EEPROM__EEPROM_READ_OS;
[self bleCommandTask];
break;
case EEPROM__EEPROM_READ_OS_DONE:
bleCommandState = EEPROM__EEPROM_READ_PIN;
[self bleCommandTask];
break;
case EEPROM__EEPROM_READ_PIN_DONE:
bleCommandState = EEPROM__DONE;
[self bleCommandTask];
break;
case EEPROM__EEPROM_WRITE_ID:
if(![strId isEqualToString:txtId.text]) {
[[self protocol]putData:@"writeDeviceId" data:txtId.text];
} else {
bleCommandState = EEPROM__EEPROM_WRITE_ID_DONE;
[self bleCommandTask];
}
break;
case EEPROM__EEPROM_WRITE_MODEL:
if(![strModel isEqualToString:txtModel.text]) {
[[self protocol]putData:@"writeDeviceModel" data:txtModel.text];
} else {
bleCommandState = EEPROM__EEPROM_WRITE_MODEL_DONE;
[self bleCommandTask];
}
break;
case EEPROM__EEPROM_WRITE_TYPE:
if(![strType isEqualToString:txtType.text]) {
[[self protocol]putData:@"writeDeviceType" data:txtType.text];
} else {
bleCommandState = EEPROM__EEPROM_WRITE_TYPE_DONE;
[self bleCommandTask];
}
break;
case EEPROM__EEPROM_WRITE_OS:
if(![strOs isEqualToString:txtOs.text]) {
[[self protocol]putData:@"writeDeviceOs" data:txtOs.text];
} else {
bleCommandState = EEPROM__EEPROM_WRITE_OS_DONE;
[self bleCommandTask];
}
break;
case EEPROM__EEPROM_WRITE_PIN:
if(![strOs isEqualToString:txtPin.text]) {
[[self protocol]putData:@"writeDevicePin" data:txtPin.text];
} else {
bleCommandState = EEPROM__EEPROM_WRITE_PIN_DONE;
[self bleCommandTask];
}
break;
case EEPROM__EEPROM_WRITE_ID_DONE:
bleCommandState = EEPROM__EEPROM_WRITE_MODEL;
[self bleCommandTask];
break;
case EEPROM__EEPROM_WRITE_MODEL_DONE:
bleCommandState = EEPROM__EEPROM_WRITE_TYPE;
[self bleCommandTask];
break;
case EEPROM__EEPROM_WRITE_TYPE_DONE:
bleCommandState = EEPROM__EEPROM_WRITE_OS;
[self bleCommandTask];
break;
case EEPROM__EEPROM_WRITE_OS_DONE:
bleCommandState = EEPROM__EEPROM_WRITE_PIN;
[self bleCommandTask];
break;
case EEPROM__EEPROM_WRITE_PIN_DONE:
bleCommandState = EEPROM__EEPROM_WP_ON;
[self showAlert:@"EEPROM書き込み" message:@"EEPROMに保存しました。"];
[self bleCommandTask];
break;
case EEPROM__DONE:
{
NSLog(@"Ble command set done!");
break;
}
}
return false;
}
- (void)protocolDidGetData:(NSString *)dataType data:(NSString *)dataData {
if([dataType isEqualToString:@"eepromWriteProtect"]) {
if([dataData isEqualToString:@"0"]) {
NSLog(@"eepromWriteProtect 0");
bleCommandState = EEPROM__EEPROM_WP_OFF_DONE;
[self bleCommandTask];
} else if([dataData isEqualToString:@"1"]) {
NSLog(@"eepromWriteProtect 1");
bleCommandState = EEPROM__EEPROM_WP_ON_DONE;
[self bleCommandTask];
}
} else if([dataType isEqualToString:@"readDeviceId"]) {
NSLog(@"infoDeviceId");
strId = dataData;
txtId.text = dataData;
bleCommandState = EEPROM__EEPROM_READ_ID_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"readDeviceModel"]) {
NSLog(@"infoDeviceModel");
strModel = dataData;
txtModel.text = dataData;
bleCommandState = EEPROM__EEPROM_READ_MODEL_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"readDeviceType"]) {
NSLog(@"infoDeviceType");
strType = dataData;
txtType.text = dataData;
bleCommandState = EEPROM__EEPROM_READ_TYPE_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"readDeviceOs"]) {
NSLog(@"infoDeviceOs");
strOs = dataData;
txtOs.text = dataData;
bleCommandState = EEPROM__EEPROM_READ_OS_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"readDevicePin"]) {
NSLog(@"infoDevicePin");
strPin = dataData;
txtPin.text = dataData;
bleCommandState = EEPROM__EEPROM_READ_PIN_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"writeDeviceId"]) {
NSLog(@"writeDeviceId");
bleCommandState = EEPROM__EEPROM_WRITE_ID_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"writeDeviceModel"]) {
NSLog(@"writeDeviceModel");
bleCommandState = EEPROM__EEPROM_WRITE_MODEL_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"writeDeviceType"]) {
NSLog(@"writeDeviceType");
bleCommandState = EEPROM__EEPROM_WRITE_TYPE_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"writeDeviceOs"]) {
NSLog(@"writeDeviceOs");
bleCommandState = EEPROM__EEPROM_WRITE_OS_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"writeDevicePin"]) {
NSLog(@"writeDevicePin");
bleCommandState = EEPROM__EEPROM_WRITE_PIN_DONE;
[self bleCommandTask];
}
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
<device id="retina4_0" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="EepromController">
<connections>
<outlet property="scrollView" destination="Qfe-fH-Hfv" id="lXM-aQ-FXJ"/>
<outlet property="txtId" destination="jmd-K8-5dg" id="ec5-oZ-Y0Z"/>
<outlet property="txtModel" destination="pY8-yj-AoT" id="0fs-fo-dhx"/>
<outlet property="txtOs" destination="NgZ-hI-GtN" id="BPP-0p-OEY"/>
<outlet property="txtPin" destination="8hP-og-fMY" id="Fip-no-OYL"/>
<outlet property="txtType" destination="fHz-BN-gtb" id="IJ2-JN-Jx2"/>
<outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT">
<rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<navigationBar contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="IfS-pJ-JXb">
<rect key="frame" x="0.0" y="23" width="320" height="44"/>
<items>
<navigationItem title="EEPROM設定" id="GLk-is-6zE">
<barButtonItem key="leftBarButtonItem" title="戻る" id="IQj-B6-LM1">
<connections>
<action selector="cancelButtonClicked:" destination="-1" id="o3Y-f5-6x4"/>
</connections>
</barButtonItem>
<barButtonItem key="rightBarButtonItem" title="保存" id="mdn-zs-McT">
<connections>
<action selector="saveButtonClicked:" destination="-1" id="sks-Kk-yBR"/>
</connections>
</barButtonItem>
</navigationItem>
</items>
</navigationBar>
<scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Qfe-fH-Hfv">
<rect key="frame" x="0.0" y="67" width="320" height="501"/>
<subviews>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Y4h-pJ-JSj" userLabel="Content">
<rect key="frame" x="0.0" y="0.0" width="320" height="502"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="jmd-K8-5dg">
<rect key="frame" x="20" y="49" width="288" height="30"/>
<nil key="textColor"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no"/>
</textField>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="ID" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Q7T-oe-kRb">
<rect key="frame" x="20" y="20" width="17" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="pY8-yj-AoT">
<rect key="frame" x="20" y="128" width="288" height="30"/>
<nil key="textColor"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no"/>
</textField>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="MODEL" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="hIO-x4-poN">
<rect key="frame" x="20" y="99" width="59" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="fHz-BN-gtb">
<rect key="frame" x="20" y="207" width="288" height="30"/>
<nil key="textColor"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no"/>
</textField>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="TYPE" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="YHb-SQ-GZw">
<rect key="frame" x="20" y="178" width="42" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="NgZ-hI-GtN">
<rect key="frame" x="20" y="288" width="288" height="30"/>
<nil key="textColor"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no"/>
</textField>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="OS" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="yOB-oe-lIs">
<rect key="frame" x="20" y="259" width="24" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="8hP-og-fMY">
<rect key="frame" x="20" y="368" width="288" height="30"/>
<nil key="textColor"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no"/>
</textField>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="PIN" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="svC-S5-7yd">
<rect key="frame" x="20" y="339" width="27" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="6T6-T4-HhO">
<rect key="frame" x="188" y="408" width="46" height="30"/>
<state key="normal" title="セーブ"/>
<connections>
<action selector="templateSaveButtonClicked:" destination="-1" eventType="touchUpInside" id="tf6-8x-hyl"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="8Je-bg-zen">
<rect key="frame" x="133" y="452" width="62" height="30"/>
<state key="normal" title="リセット"/>
<connections>
<action selector="resetButtonClicked:" destination="-1" eventType="touchUpInside" id="4nK-yx-4Tm"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="yAu-89-NQb">
<rect key="frame" x="93" y="408" width="46" height="30"/>
<state key="normal" title="ロード"/>
<connections>
<action selector="templateLoadButtonClicked:" destination="-1" eventType="touchUpInside" id="BvH-XD-IaO"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="Q7T-oe-kRb" firstAttribute="leading" secondItem="jmd-K8-5dg" secondAttribute="leading" id="34q-kf-sRF"/>
<constraint firstItem="fHz-BN-gtb" firstAttribute="trailing" secondItem="NgZ-hI-GtN" secondAttribute="trailing" id="7a4-LL-5B7"/>
<constraint firstItem="NgZ-hI-GtN" firstAttribute="leading" secondItem="svC-S5-7yd" secondAttribute="leading" id="9QZ-KW-Eag"/>
<constraint firstItem="pY8-yj-AoT" firstAttribute="top" secondItem="hIO-x4-poN" secondAttribute="bottom" constant="8" symbolic="YES" id="BJp-me-e5P"/>
<constraint firstItem="svC-S5-7yd" firstAttribute="top" secondItem="NgZ-hI-GtN" secondAttribute="bottom" constant="21" id="C8k-pf-wpT"/>
<constraint firstItem="8hP-og-fMY" firstAttribute="top" secondItem="svC-S5-7yd" secondAttribute="bottom" constant="8" symbolic="YES" id="D9W-LK-na6"/>
<constraint firstItem="yAu-89-NQb" firstAttribute="top" secondItem="8hP-og-fMY" secondAttribute="bottom" constant="10" id="FxX-iZ-wVQ"/>
<constraint firstItem="yOB-oe-lIs" firstAttribute="leading" secondItem="NgZ-hI-GtN" secondAttribute="leading" id="GTw-Qo-h9f"/>
<constraint firstItem="8Je-bg-zen" firstAttribute="top" secondItem="yAu-89-NQb" secondAttribute="bottom" constant="14" id="JPc-Ak-yre"/>
<constraint firstItem="Q7T-oe-kRb" firstAttribute="leading" secondItem="Y4h-pJ-JSj" secondAttribute="leading" constant="20" id="LFx-zF-3cm"/>
<constraint firstItem="YHb-SQ-GZw" firstAttribute="leading" secondItem="fHz-BN-gtb" secondAttribute="leading" id="LhX-9v-mA6"/>
<constraint firstItem="hIO-x4-poN" firstAttribute="top" secondItem="jmd-K8-5dg" secondAttribute="bottom" constant="20" id="Lu9-1B-Meu"/>
<constraint firstItem="jmd-K8-5dg" firstAttribute="top" secondItem="Q7T-oe-kRb" secondAttribute="bottom" constant="8" symbolic="YES" id="SiJ-qx-AAu"/>
<constraint firstItem="pY8-yj-AoT" firstAttribute="trailing" secondItem="fHz-BN-gtb" secondAttribute="trailing" id="VdP-zv-qpf"/>
<constraint firstItem="jmd-K8-5dg" firstAttribute="leading" secondItem="hIO-x4-poN" secondAttribute="leading" id="WSX-p0-Nud"/>
<constraint firstItem="fHz-BN-gtb" firstAttribute="leading" secondItem="yOB-oe-lIs" secondAttribute="leading" id="X09-ii-JR1"/>
<constraint firstItem="yOB-oe-lIs" firstAttribute="top" secondItem="fHz-BN-gtb" secondAttribute="bottom" constant="22" id="Zw5-us-oKD"/>
<constraint firstItem="8hP-og-fMY" firstAttribute="centerX" secondItem="8Je-bg-zen" secondAttribute="centerX" id="c31-8u-MDo"/>
<constraint firstItem="Q7T-oe-kRb" firstAttribute="top" secondItem="Y4h-pJ-JSj" secondAttribute="top" constant="20" id="d6Q-gG-PmN"/>
<constraint firstItem="svC-S5-7yd" firstAttribute="leading" secondItem="8hP-og-fMY" secondAttribute="leading" id="eEd-Cl-6lf"/>
<constraint firstItem="yAu-89-NQb" firstAttribute="leading" secondItem="Y4h-pJ-JSj" secondAttribute="leading" constant="93" id="hB6-yF-fsK"/>
<constraint firstItem="yAu-89-NQb" firstAttribute="baseline" secondItem="6T6-T4-HhO" secondAttribute="baseline" id="hVI-o6-fOE"/>
<constraint firstItem="pY8-yj-AoT" firstAttribute="leading" secondItem="YHb-SQ-GZw" secondAttribute="leading" id="i34-ti-Ng1"/>
<constraint firstItem="hIO-x4-poN" firstAttribute="leading" secondItem="pY8-yj-AoT" secondAttribute="leading" id="kQY-so-a1C"/>
<constraint firstItem="NgZ-hI-GtN" firstAttribute="trailing" secondItem="8hP-og-fMY" secondAttribute="trailing" id="lER-6n-iNx"/>
<constraint firstItem="6T6-T4-HhO" firstAttribute="leading" secondItem="yAu-89-NQb" secondAttribute="trailing" constant="49" id="nK6-hC-Xte"/>
<constraint firstItem="NgZ-hI-GtN" firstAttribute="top" secondItem="yOB-oe-lIs" secondAttribute="bottom" constant="8" symbolic="YES" id="nwc-fP-zwh"/>
<constraint firstAttribute="trailing" secondItem="jmd-K8-5dg" secondAttribute="trailing" constant="12" id="omi-XO-Quv"/>
<constraint firstItem="YHb-SQ-GZw" firstAttribute="top" secondItem="pY8-yj-AoT" secondAttribute="bottom" constant="20" id="pvD-8w-rx7"/>
<constraint firstItem="fHz-BN-gtb" firstAttribute="top" secondItem="YHb-SQ-GZw" secondAttribute="bottom" constant="8" symbolic="YES" id="yx3-pV-wHX"/>
<constraint firstItem="jmd-K8-5dg" firstAttribute="trailing" secondItem="pY8-yj-AoT" secondAttribute="trailing" id="zW1-dc-xfs"/>
</constraints>
</view>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="Y4h-pJ-JSj" secondAttribute="bottom" id="BBM-HT-Vbq"/>
<constraint firstAttribute="trailing" secondItem="Y4h-pJ-JSj" secondAttribute="trailing" id="FyK-gd-Via"/>
<constraint firstItem="Y4h-pJ-JSj" firstAttribute="centerY" secondItem="Qfe-fH-Hfv" secondAttribute="centerY" id="Gue-mo-e3c"/>
<constraint firstItem="Y4h-pJ-JSj" firstAttribute="top" secondItem="Qfe-fH-Hfv" secondAttribute="top" id="NGn-wv-7da"/>
<constraint firstItem="Y4h-pJ-JSj" firstAttribute="centerX" secondItem="Qfe-fH-Hfv" secondAttribute="centerX" id="YLA-PQ-YfF"/>
<constraint firstItem="Y4h-pJ-JSj" firstAttribute="leading" secondItem="Qfe-fH-Hfv" secondAttribute="leading" id="maX-xJ-VPb"/>
</constraints>
</scrollView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="IfS-pJ-JXb" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="23" id="1yP-fd-d6Y"/>
<constraint firstItem="IfS-pJ-JXb" firstAttribute="leading" secondItem="Qfe-fH-Hfv" secondAttribute="leading" id="Epr-ZY-vqh"/>
<constraint firstItem="IfS-pJ-JXb" firstAttribute="trailing" secondItem="Qfe-fH-Hfv" secondAttribute="trailing" id="PZF-lX-b4H"/>
<constraint firstItem="IfS-pJ-JXb" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" id="ZZM-xe-gxx"/>
<constraint firstItem="Qfe-fH-Hfv" firstAttribute="top" secondItem="IfS-pJ-JXb" secondAttribute="bottom" id="i0o-qh-JSM"/>
<constraint firstAttribute="bottom" secondItem="Qfe-fH-Hfv" secondAttribute="bottom" id="neI-1C-ByC"/>
<constraint firstAttribute="trailing" secondItem="IfS-pJ-JXb" secondAttribute="trailing" id="zoy-gH-9sf"/>
</constraints>
<point key="canvasLocation" x="24" y="52"/>
</view>
</objects>
</document>
//
// EepromTemplateController.h
// jacket_test_ios
//
// Created by ドラッサル 亜嵐 on 2017/07/24.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol EepromTemplateControllerDelegate
@optional
- (void)didChoose:(NSString *)recordId
recordName:(NSString *)recordName
dataId:(NSString *)dataId
dataModel:(NSString *)dataModel
dataType:(NSString *)dataType
dataOs:(NSString *)dataOs
dataPin:(NSString *)dataPin;
@required
@end
@interface EepromTemplateController : UIViewController<UITableViewDelegate, UITableViewDataSource> {
IBOutlet UITableView *tblResult;
NSMutableArray *arrResult;
}
@property (nonatomic,assign) id <EepromTemplateControllerDelegate> delegate;
@end
//
// EepromTemplateController.m
// jacket_test_ios
//
// Created by ドラッサル 亜嵐 on 2017/07/24.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import "EepromTemplateController.h"
#import "EepromTemplateTableViewCell.h"
#import "DBManager.h"
@interface EepromTemplateController ()
@end
@implementation EepromTemplateController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewWillAppear:(BOOL)animated {
arrResult = [[NSMutableArray alloc] init];
UINib *nib = [UINib nibWithNibName:@"EepromTemplateTableViewCell" bundle:nil];
[tblResult registerNib:nib forCellReuseIdentifier:@"mycell"];
tblResult.delegate = self;
tblResult.dataSource = self;
[arrResult removeAllObjects];
NSArray *result = [[DBManager sharedInstance] getEepromTemplateData];
for(id key in result) {
NSString *valueRecordId = [key objectAtIndex:0];
NSString *valueRecordName = [key objectAtIndex:1];
NSString *valueDataId = [key objectAtIndex:2];
NSString *valueDataModel = [key objectAtIndex:3];
NSString *valueDataType = [key objectAtIndex:4];
NSString *valueDataOs = [key objectAtIndex:5];
NSString *valueDataPin = [key objectAtIndex:6];
NSMutableDictionary *newDict = [NSMutableDictionary dictionary];
[newDict setObject:valueRecordId forKey:@"recordId"];
[newDict setObject:valueRecordName forKey:@"recordName"];
[newDict setObject:valueDataId forKey:@"dataId"];
[newDict setObject:valueDataModel forKey:@"dataModel"];
[newDict setObject:valueDataType forKey:@"dataType"];
[newDict setObject:valueDataOs forKey:@"dataOs"];
[newDict setObject:valueDataPin forKey:@"dataPin"];
[arrResult addObject:newDict];
}
[tblResult reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)cancelButtonClicked:(id)sender {
[self dismissViewControllerAnimated:YES completion:Nil];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger row = [indexPath row];
NSDictionary *dataRecord = [arrResult objectAtIndex:row];
[self.delegate didChoose:[dataRecord valueForKey:@"recordId"]
recordName:[dataRecord valueForKey:@"recordName"]
dataId:[dataRecord valueForKey:@"dataId"]
dataModel:[dataRecord valueForKey:@"dataModel"]
dataType:[dataRecord valueForKey:@"dataType"]
dataOs:[dataRecord valueForKey:@"dataOs"]
dataPin:[dataRecord valueForKey:@"dataPin"]];
[self dismissViewControllerAnimated:YES completion:Nil];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [arrResult count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"mycell";
EepromTemplateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
NSInteger row = [indexPath row];
NSDictionary *dataRecord = [arrResult objectAtIndex:row];
// Configure the cell...
UIFont *newFont = [UIFont fontWithName:@"Arial" size:17.0];
cell.lblRecordName.font = newFont;
cell.lblRecordName.text = [dataRecord valueForKey:@"recordName"];
newFont = [UIFont fontWithName:@"Arial" size:12.0];
cell.lblRecordId.font = newFont;
cell.lblRecordId.text = [dataRecord valueForKey:@"recordId"];
cell.lblDataId.font = newFont;
cell.lblDataId.text = [dataRecord valueForKey:@"dataId"];
cell.lblDataModel.font = newFont;
cell.lblDataModel.text = [dataRecord valueForKey:@"dataModel"];
cell.lblDataType.font = newFont;
cell.lblDataType.text = [dataRecord valueForKey:@"dataType"];
cell.lblDataOs.font = newFont;
cell.lblDataOs.text = [dataRecord valueForKey:@"dataOs"];
cell.lblDataPin.font = newFont;
cell.lblDataPin.text = [dataRecord valueForKey:@"dataPin"];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 100;
}
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
return @[
[UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive
title:@"削除"
handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
// own delete action
// Distructive button tapped.
NSLog(@"削除の確認");
NSDictionary * selectedData = [arrResult objectAtIndex:indexPath.row];
NSString *firmwareTitle = [selectedData valueForKey:@"file"];
UIAlertController *actionSheetConfirm = [UIAlertController alertControllerWithTitle:@"削除の確認" message:[NSString stringWithFormat:@"「%@」を削除します。よろしいですか?",firmwareTitle] preferredStyle:UIAlertControllerStyleAlert];
[actionSheetConfirm addAction:[UIAlertAction actionWithTitle:@"削除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *actionConfirm) {
// Get the record ID of the selected name and set it to the recordIDToEdit property.
NSDictionary * selectedData = [arrResult objectAtIndex:indexPath.row];
NSString *recordId = [selectedData valueForKey:@"recordId"];
NSLog(@"recordId = %@",recordId);
[[DBManager sharedInstance] deleteEepromTemplateData:recordId];
//[self populateDetail];
//[self.tblResult reloadData];
[arrResult removeObjectAtIndex:indexPath.row];
[tblResult deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}]];
[actionSheetConfirm addAction:[UIAlertAction actionWithTitle:@"キャンセル" style:UIAlertActionStyleDefault handler:^(UIAlertAction *actionConfirm) {
// Distructive button tapped.
NSLog(@"キャンセルの確認");
}]];
[self presentViewController:actionSheetConfirm animated:YES completion:nil];
}],
];
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="12121" systemVersion="16F73" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="EepromTemplateController">
<connections>
<outlet property="tblResult" destination="ApV-bw-Rn1" id="zPh-Vf-P8V"/>
<outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<navigationBar contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="tFr-RW-xCk">
<rect key="frame" x="0.0" y="23" width="375" height="44"/>
<items>
<navigationItem title="テンプレート選択" id="9cH-Zh-eej">
<barButtonItem key="leftBarButtonItem" title="戻る" id="u5c-K3-4uI">
<connections>
<action selector="cancelButtonClicked:" destination="-1" id="45e-6T-qfA"/>
</connections>
</barButtonItem>
</navigationItem>
</items>
</navigationBar>
<tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="ApV-bw-Rn1">
<rect key="frame" x="0.0" y="67" width="375" height="600"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
</tableView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="tFr-RW-xCk" firstAttribute="leading" secondItem="ApV-bw-Rn1" secondAttribute="leading" id="4cX-M9-u63"/>
<constraint firstItem="tFr-RW-xCk" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="23" id="6cd-hA-zhv"/>
<constraint firstAttribute="bottom" secondItem="ApV-bw-Rn1" secondAttribute="bottom" id="9Qe-KE-6Ho"/>
<constraint firstItem="tFr-RW-xCk" firstAttribute="trailing" secondItem="ApV-bw-Rn1" secondAttribute="trailing" id="FXl-z1-bN7"/>
<constraint firstItem="tFr-RW-xCk" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" id="NGB-Xr-cIf"/>
<constraint firstAttribute="trailing" secondItem="tFr-RW-xCk" secondAttribute="trailing" id="ZyS-Vn-LV4"/>
<constraint firstItem="ApV-bw-Rn1" firstAttribute="top" secondItem="tFr-RW-xCk" secondAttribute="bottom" id="ad4-Qe-Nod"/>
</constraints>
<point key="canvasLocation" x="24.5" y="52.5"/>
</view>
</objects>
</document>
//
// EepromTemplateTableViewCell.h
// jacket_test_ios
//
// Created by ドラッサル 亜嵐 on 2017/07/24.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface EepromTemplateTableViewCell : UITableViewCell
@property (strong, nonatomic) IBOutlet UILabel *lblRecordId;
@property (strong, nonatomic) IBOutlet UILabel *lblRecordName;
@property (strong, nonatomic) IBOutlet UILabel *lblDataId;
@property (strong, nonatomic) IBOutlet UILabel *lblDataModel;
@property (strong, nonatomic) IBOutlet UILabel *lblDataType;
@property (strong, nonatomic) IBOutlet UILabel *lblDataOs;
@property (strong, nonatomic) IBOutlet UILabel *lblDataPin;
@end
//
// EepromTemplateTableViewCell.m
// jacket_test_ios
//
// Created by ドラッサル 亜嵐 on 2017/07/24.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import "EepromTemplateTableViewCell.h"
@implementation EepromTemplateTableViewCell
@synthesize lblRecordId = _lblRecordId;
@synthesize lblRecordName = _lblRecordName;
@synthesize lblDataId = _lblDataId;
@synthesize lblDataModel = _lblDataModel;
@synthesize lblDataType = _lblDataType;
@synthesize lblDataOs = _lblDataOs;
@synthesize lblDataPin = _lblDataPin;
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
<capability name="Constraints to layout margins" minToolsVersion="6.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<tableViewCell contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" rowHeight="100" id="KGk-i7-Jjw" customClass="EepromTemplateTableViewCell">
<rect key="frame" x="0.0" y="0.0" width="320" height="100"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="KGk-i7-Jjw" id="H2p-sc-9uM">
<rect key="frame" x="0.0" y="0.0" width="320" height="99.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="recordId" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="8fS-9z-HJ1">
<rect key="frame" x="8" y="0.0" width="304" height="15"/>
<fontDescription key="fontDescription" type="system" pointSize="12"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="dataId" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="ehd-h0-G5F">
<rect key="frame" x="8" y="30" width="304" height="14.5"/>
<fontDescription key="fontDescription" type="system" pointSize="12"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="dataModel" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Gwb-VU-QNL">
<rect key="frame" x="8" y="44" width="304" height="14.5"/>
<fontDescription key="fontDescription" type="system" pointSize="12"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="dataType" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Gc3-Sq-C9l">
<rect key="frame" x="8" y="58" width="304" height="14.5"/>
<fontDescription key="fontDescription" type="system" pointSize="12"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="dataOs" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="458-dR-dVU">
<rect key="frame" x="8" y="71" width="304" height="14.5"/>
<fontDescription key="fontDescription" type="system" pointSize="12"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="recordName" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="iT0-XG-TUh">
<rect key="frame" x="8" y="12" width="304" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="dataPin" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="eOf-Vq-Ned">
<rect key="frame" x="8" y="83" width="43" height="15"/>
<fontDescription key="fontDescription" type="system" pointSize="12"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstItem="Gwb-VU-QNL" firstAttribute="top" secondItem="iT0-XG-TUh" secondAttribute="bottom" constant="11" id="3Ah-wp-nlD"/>
<constraint firstAttribute="trailingMargin" secondItem="458-dR-dVU" secondAttribute="trailing" id="3q1-IV-Uu4"/>
<constraint firstItem="458-dR-dVU" firstAttribute="top" secondItem="Gwb-VU-QNL" secondAttribute="bottom" constant="12.5" id="662-hh-xov"/>
<constraint firstAttribute="trailingMargin" secondItem="Gc3-Sq-C9l" secondAttribute="trailing" id="87s-sY-8PO"/>
<constraint firstItem="8fS-9z-HJ1" firstAttribute="leading" secondItem="H2p-sc-9uM" secondAttribute="leadingMargin" id="95Q-rK-8K6"/>
<constraint firstItem="ehd-h0-G5F" firstAttribute="top" secondItem="8fS-9z-HJ1" secondAttribute="bottom" constant="15" id="LQ7-1v-xOY"/>
<constraint firstAttribute="trailingMargin" secondItem="Gwb-VU-QNL" secondAttribute="trailing" id="NcB-sA-bvl"/>
<constraint firstItem="iT0-XG-TUh" firstAttribute="top" secondItem="H2p-sc-9uM" secondAttribute="topMargin" constant="4" id="QJJ-js-QYu"/>
<constraint firstItem="ehd-h0-G5F" firstAttribute="leading" secondItem="H2p-sc-9uM" secondAttribute="leadingMargin" id="RC0-Ar-tZX"/>
<constraint firstItem="iT0-XG-TUh" firstAttribute="leading" secondItem="H2p-sc-9uM" secondAttribute="leadingMargin" id="VkX-0A-hRU"/>
<constraint firstItem="Gwb-VU-QNL" firstAttribute="leading" secondItem="H2p-sc-9uM" secondAttribute="leadingMargin" id="Vzs-yL-Pmn"/>
<constraint firstItem="eOf-Vq-Ned" firstAttribute="leading" secondItem="H2p-sc-9uM" secondAttribute="leading" constant="8" id="Xaf-Xh-Ozw"/>
<constraint firstItem="Gc3-Sq-C9l" firstAttribute="leading" secondItem="H2p-sc-9uM" secondAttribute="leadingMargin" id="bQ8-Fy-ebk"/>
<constraint firstItem="Gc3-Sq-C9l" firstAttribute="top" secondItem="ehd-h0-G5F" secondAttribute="bottom" constant="13.5" id="bTK-je-YxG"/>
<constraint firstItem="458-dR-dVU" firstAttribute="leading" secondItem="H2p-sc-9uM" secondAttribute="leadingMargin" id="d0r-nI-b5G"/>
<constraint firstAttribute="trailingMargin" secondItem="iT0-XG-TUh" secondAttribute="trailing" id="htH-3d-fAh"/>
<constraint firstAttribute="trailingMargin" secondItem="8fS-9z-HJ1" secondAttribute="trailing" id="iRy-KW-NVN"/>
<constraint firstItem="eOf-Vq-Ned" firstAttribute="top" secondItem="Gc3-Sq-C9l" secondAttribute="bottom" constant="10.5" id="lNL-bx-aIK"/>
<constraint firstAttribute="trailingMargin" secondItem="ehd-h0-G5F" secondAttribute="trailing" id="mwI-LD-DKm"/>
<constraint firstItem="8fS-9z-HJ1" firstAttribute="top" secondItem="H2p-sc-9uM" secondAttribute="top" id="ygd-9l-fh7"/>
</constraints>
</tableViewCellContentView>
<connections>
<outlet property="lblDataId" destination="ehd-h0-G5F" id="zNI-oH-grq"/>
<outlet property="lblDataModel" destination="Gwb-VU-QNL" id="UfO-sd-eLM"/>
<outlet property="lblDataOs" destination="458-dR-dVU" id="RBV-15-xGE"/>
<outlet property="lblDataPin" destination="eOf-Vq-Ned" id="5fK-t6-Guw"/>
<outlet property="lblDataType" destination="Gc3-Sq-C9l" id="G49-kF-3gj"/>
<outlet property="lblRecordId" destination="8fS-9z-HJ1" id="oAa-nz-13w"/>
<outlet property="lblRecordName" destination="iT0-XG-TUh" id="LAb-QQ-lFu"/>
</connections>
<point key="canvasLocation" x="25" y="80"/>
</tableViewCell>
</objects>
</document>
//
// FirmwareDownloadController.h
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2017/06/06.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "BleProtocol.h"
typedef enum {
FIRMWARE_DOWNLOAD__EEPROM_READ_ID,
FIRMWARE_DOWNLOAD__EEPROM_READ_ID_DONE,
FIRMWARE_DOWNLOAD__EEPROM_READ_MODEL,
FIRMWARE_DOWNLOAD__EEPROM_READ_MODEL_DONE,
FIRMWARE_DOWNLOAD__EEPROM_READ_TYPE,
FIRMWARE_DOWNLOAD__EEPROM_READ_TYPE_DONE,
FIRMWARE_DOWNLOAD__EEPROM_READ_OS,
FIRMWARE_DOWNLOAD__EEPROM_READ_OS_DONE,
FIRMWARE_DOWNLOAD__DONE
} FirmwareDownloadCommandState;
@interface FirmwareDownloadController : UIViewController<UITableViewDelegate, UITableViewDataSource, BLEProtocolDelegate> {
IBOutlet UITableView *tblFirmware;
IBOutlet UILabel *lblPercentComplete;
NSMutableArray *arrResult;
int selectionEnabled;
NSString *strId;
NSString *strModel;
NSString *strType;
NSString *strOs;
FirmwareDownloadCommandState bleCommandState;
}
@property (strong, nonatomic) BleProtocol *protocol;
@property (nonatomic,assign) id <BLEProtocolDelegate> lastProtocolDelegate;
@end
//
// FirmwareDownloadController.m
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2017/06/06.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import "FirmwareDownloadController.h"
#import "FirmwareDownloadControllerTableViewCell.h"
#import "Operation.h"
#import "DBManager.h"
@interface FirmwareDownloadController ()
@end
@implementation FirmwareDownloadController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewWillAppear:(BOOL)animated {
self.lastProtocolDelegate = self.protocol.delegate;
self.protocol.delegate = self;
bleCommandState = FIRMWARE_DOWNLOAD__EEPROM_READ_ID;
[self bleCommandTask];
}
- (void)viewWillDisappear:(BOOL)animated {
self.protocol.delegate = self.lastProtocolDelegate;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void) getDownloadList {
selectionEnabled = 1;
arrResult = [[NSMutableArray alloc] init];
UINib *nib = [UINib nibWithNibName:@"FirmwareDownloadControllerTableViewCell" bundle:nil];
[tblFirmware registerNib:nib forCellReuseIdentifier:@"mycell"];
tblFirmware.delegate = self;
tblFirmware.dataSource = self;
[[Operation sharedOperation] getFirmwareList:strId
deviceType:strType
deviceModel:strModel
deviceOs:strOs
appVersion:@"appVersion"
success:^(id JSON) {
NSLog(@"SUCCESS!");
if([JSON valueForKey:@"firmware_list"]) {
[arrResult removeAllObjects];
NSDictionary *firmwareList = [JSON valueForKey:@"firmware_list"];
for(id selectedKey in firmwareList) {
NSDictionary *firmwareListRecord = [firmwareList valueForKey:selectedKey];
NSMutableDictionary *detailDict = [[NSMutableDictionary alloc] init];
[detailDict setValue:selectedKey forKey:@"uuid"];
for(id selectedSubKey in firmwareListRecord) {
[detailDict setValue:[firmwareListRecord valueForKey:selectedSubKey] forKey:selectedSubKey];
}
[arrResult addObject:detailDict];
}
}
[tblFirmware reloadData];
} failure:^(NSError *error, id JSON) {
NSLog(@"FAIL!");
}];
}
- (IBAction)cancelButtonClicked:(id)sender {
[self dismissViewControllerAnimated:YES completion:Nil];
}
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(selectionEnabled == 1) {
return indexPath;
} else {
return nil;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger row = [indexPath row];
NSDictionary *dataRecord = [arrResult objectAtIndex:row];
NSString *filename = [dataRecord valueForKey:@"uuid"];
selectionEnabled = 0;
[[Operation sharedOperation] streamToFile:[NSString stringWithFormat:@"%@%@",URL_BASE,[NSString stringWithFormat:URL_PATH_STORE_FIRMWARE, filename]]
saveToPath:[NSString stringWithFormat:@"save/%@",filename]
progressBlock:^(double fractionCompleted) {
//NSLog(@"Progress: %f", fractionCompleted);
lblPercentComplete.text = [NSString stringWithFormat:@"%f%%", fractionCompleted * 100];
}
success:^(NSString *savedTo) {
NSLog(@"Saved to %@",savedTo);
[[DBManager sharedInstance] saveFirmwareData:[dataRecord valueForKey:@"uuid"]
deviceType:[dataRecord valueForKey:@"devicetype"]
deviceModel:[dataRecord valueForKey:@"devicemodel"]
version:[dataRecord valueForKey:@"version"]
versionStamp:[dataRecord valueForKey:@"version_Stamp"]
file:[dataRecord valueForKey:@"file"]];
//[self saveVideoInfo:video.identifier videoItag:[NSString stringWithFormat:@"%@",videoQuality] videoFilename:[NSString stringWithFormat:@"%@_%@.mp4",video.identifier,videoQuality]];
//[self showAlert:@"アプリに保存" message:@"保存完了"];
selectionEnabled = 1;
lblPercentComplete.text = @"完了";
}
failure:^(NSError *error) {
//[self showAlert:@"アプリに保存" message:@"保存完了"];
selectionEnabled = 1;
lblPercentComplete.text = @"失敗";
}];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [arrResult count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"mycell";
FirmwareDownloadControllerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
NSInteger row = [indexPath row];
NSDictionary *dataRecord = [arrResult objectAtIndex:row];
// Configure the cell...
UIFont *newFont = [UIFont fontWithName:@"Arial" size:11.0];
cell.lblTitle.font = newFont;
cell.lblTitle.text = [dataRecord valueForKey:@"file"];
newFont = [UIFont fontWithName:@"Arial" size:11.0];
cell.lblSubtitle.font = newFont;
cell.lblSubtitle.text = [dataRecord valueForKey:@"uuid"];
return cell;
}
- (BOOL)bleCommandTask {
switch(bleCommandState) {
case FIRMWARE_DOWNLOAD__EEPROM_READ_ID:
[[self protocol]putData:@"infoDeviceId" data:nil];
break;
case FIRMWARE_DOWNLOAD__EEPROM_READ_MODEL:
[[self protocol]putData:@"infoDeviceModel" data:nil];
break;
case FIRMWARE_DOWNLOAD__EEPROM_READ_TYPE:
[[self protocol]putData:@"infoDeviceType" data:nil];
break;
case FIRMWARE_DOWNLOAD__EEPROM_READ_OS:
[[self protocol]putData:@"infoDeviceOs" data:nil];
break;
case FIRMWARE_DOWNLOAD__EEPROM_READ_ID_DONE:
bleCommandState = FIRMWARE_DOWNLOAD__EEPROM_READ_MODEL;
[self bleCommandTask];
break;
case FIRMWARE_DOWNLOAD__EEPROM_READ_MODEL_DONE:
bleCommandState = FIRMWARE_DOWNLOAD__EEPROM_READ_TYPE;
[self bleCommandTask];
break;
case FIRMWARE_DOWNLOAD__EEPROM_READ_TYPE_DONE:
bleCommandState = FIRMWARE_DOWNLOAD__EEPROM_READ_OS;
[self bleCommandTask];
break;
case FIRMWARE_DOWNLOAD__EEPROM_READ_OS_DONE:
bleCommandState = FIRMWARE_DOWNLOAD__DONE;
[self bleCommandTask];
break;
case FIRMWARE_DOWNLOAD__DONE:
{
NSLog(@"Ble command set done!");
[self getDownloadList];
break;
}
}
return false;
}
- (void)protocolDidGetData:(NSString *)dataType data:(NSString *)dataData {
if([dataType isEqualToString:@"infoDeviceId"]) {
NSLog(@"infoDeviceId");
strId = dataData;
bleCommandState = FIRMWARE_DOWNLOAD__EEPROM_READ_ID_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"infoDeviceModel"]) {
NSLog(@"infoDeviceModel");
strModel = dataData;
bleCommandState = FIRMWARE_DOWNLOAD__EEPROM_READ_MODEL_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"infoDeviceType"]) {
NSLog(@"infoDeviceType");
strType = dataData;
bleCommandState = FIRMWARE_DOWNLOAD__EEPROM_READ_TYPE_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"infoDeviceOs"]) {
NSLog(@"infoDeviceOs");
strOs = dataData;
bleCommandState = FIRMWARE_DOWNLOAD__EEPROM_READ_OS_DONE;
[self bleCommandTask];
}
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="12120" systemVersion="16F73" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12088"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="FirmwareDownloadController">
<connections>
<outlet property="lblPercentComplete" destination="Mjh-27-eGB" id="13E-30-jj7"/>
<outlet property="tblFirmware" destination="erf-sK-RX7" id="tcE-GL-fEf"/>
<outlet property="view" destination="xbi-n3-MOM" id="qjE-58-VqO"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view contentMode="scaleToFill" id="xbi-n3-MOM">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<subviews>
<tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="erf-sK-RX7">
<rect key="frame" x="0.0" y="114" width="375" height="553"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
</tableView>
<navigationBar contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Oce-KB-tk0">
<rect key="frame" x="0.0" y="23" width="375" height="44"/>
<items>
<navigationItem title="ファームウェアDL" id="iQA-Ru-iNE">
<barButtonItem key="leftBarButtonItem" title="戻る" id="feZ-vp-UB8">
<connections>
<action selector="cancelButtonClicked:" destination="-1" id="BbS-7p-KWV"/>
</connections>
</barButtonItem>
</navigationItem>
</items>
</navigationBar>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Mjh-27-eGB">
<rect key="frame" x="0.0" y="85" width="375" height="21"/>
<constraints>
<constraint firstAttribute="height" constant="21" id="sgi-RD-ywG"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="erf-sK-RX7" firstAttribute="trailing" secondItem="Mjh-27-eGB" secondAttribute="trailing" id="8cr-0D-Wsn"/>
<constraint firstItem="Mjh-27-eGB" firstAttribute="top" secondItem="Oce-KB-tk0" secondAttribute="bottom" constant="18" id="ChU-4v-QTf"/>
<constraint firstItem="erf-sK-RX7" firstAttribute="top" secondItem="Mjh-27-eGB" secondAttribute="bottom" constant="8" symbolic="YES" id="F4t-w2-3Ki"/>
<constraint firstItem="erf-sK-RX7" firstAttribute="leading" secondItem="Mjh-27-eGB" secondAttribute="leading" id="JEl-P9-VO6"/>
<constraint firstAttribute="trailing" secondItem="erf-sK-RX7" secondAttribute="trailing" id="KGd-4x-ijs"/>
<constraint firstAttribute="bottom" secondItem="erf-sK-RX7" secondAttribute="bottom" id="Kyb-Se-oRR"/>
<constraint firstItem="Oce-KB-tk0" firstAttribute="top" secondItem="xbi-n3-MOM" secondAttribute="top" constant="23" id="WZ0-1l-eIW"/>
<constraint firstItem="Oce-KB-tk0" firstAttribute="trailing" secondItem="Mjh-27-eGB" secondAttribute="trailing" id="bVM-cw-kfp"/>
<constraint firstItem="erf-sK-RX7" firstAttribute="leading" secondItem="xbi-n3-MOM" secondAttribute="leading" id="fXw-QY-PLy"/>
<constraint firstItem="Oce-KB-tk0" firstAttribute="leading" secondItem="Mjh-27-eGB" secondAttribute="leading" id="zmz-jd-CrP"/>
</constraints>
<point key="canvasLocation" x="-203.5" y="147.5"/>
</view>
</objects>
</document>
//
// FirmwareDownloadControllerTableViewCell.h
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2017/06/06.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FirmwareDownloadControllerTableViewCell : UITableViewCell
@property (strong, nonatomic) IBOutlet UILabel *lblTitle;
@property (strong, nonatomic) IBOutlet UILabel *lblSubtitle;
@end
//
// FirmwareDownloadControllerTableCellTableViewCell.m
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2017/06/06.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import "FirmwareDownloadControllerTableViewCell.h"
@implementation FirmwareDownloadControllerTableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="12120" systemVersion="16F73" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12088"/>
<capability name="Constraints to layout margins" minToolsVersion="6.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<tableViewCell contentMode="scaleToFill" restorationIdentifier="mycell" selectionStyle="default" indentationWidth="10" id="KGk-i7-Jjw" userLabel="Firmware Download Controller Table View Cell" customClass="FirmwareDownloadControllerTableViewCell">
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="KGk-i7-Jjw" id="H2p-sc-9uM">
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="サブタイトル" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="FUj-Q3-Rtz">
<rect key="frame" x="17" y="22" width="303" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="12"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="タイトル" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="mMs-ai-Esq">
<rect key="frame" x="17" y="4" width="303" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstItem="FUj-Q3-Rtz" firstAttribute="top" secondItem="H2p-sc-9uM" secondAttribute="topMargin" constant="14" id="Ifu-3l-cZ2"/>
<constraint firstItem="FUj-Q3-Rtz" firstAttribute="leading" secondItem="mMs-ai-Esq" secondAttribute="leading" id="OZM-Dl-ddG"/>
<constraint firstItem="mMs-ai-Esq" firstAttribute="top" secondItem="H2p-sc-9uM" secondAttribute="topMargin" constant="-4" id="bey-do-AaT"/>
<constraint firstAttribute="bottomMargin" secondItem="FUj-Q3-Rtz" secondAttribute="bottom" constant="-7.5" id="hL8-P8-yuW"/>
<constraint firstItem="mMs-ai-Esq" firstAttribute="leading" secondItem="H2p-sc-9uM" secondAttribute="leadingMargin" constant="9" id="kHc-HS-oAw"/>
<constraint firstItem="FUj-Q3-Rtz" firstAttribute="trailing" secondItem="mMs-ai-Esq" secondAttribute="trailing" id="sWv-je-ezI"/>
<constraint firstAttribute="trailing" secondItem="mMs-ai-Esq" secondAttribute="trailing" id="tab-yq-GfI"/>
</constraints>
</tableViewCellContentView>
<connections>
<outlet property="lblSubtitle" destination="FUj-Q3-Rtz" id="y7i-UH-MNh"/>
<outlet property="lblTitle" destination="mMs-ai-Esq" id="ODY-6M-Ul5"/>
</connections>
</tableViewCell>
</objects>
</document>
//
// FirmwareUpdateController.h
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2017/06/05.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "BleProtocol.h"
#import "BLE.h"
typedef enum {
MODE_FIRMWARE_IMAGE_SELECT_0_EEPROM_WP_OFF,
MODE_FIRMWARE_IMAGE_SELECT_0_EEPROM_WP_OFF_DONE,
MODE_FIRMWARE_IMAGE_SELECT_0_RESET_IN_BOOTLOADER,
MODE_FIRMWARE_IMAGE_SELECT_1_EEPROM_WP_OFF,
MODE_FIRMWARE_IMAGE_SELECT_1_EEPROM_WP_OFF_DONE,
MODE_FIRMWARE_IMAGE_SELECT_1,
MODE_FIRMWARE_IMAGE_SELECT_1_DONE,
MODE_FIRMWARE_IMAGE_SELECT_1_RESET,
} ModeFirmwareUpdateState;
@interface FirmwareUpdateController : UIViewController <BLEProtocolDelegate> {
ModeFirmwareUpdateState firmwareUpdateState;
}
@property (strong, nonatomic) IBOutlet UILabel *lblStateDownload;
@property (strong, nonatomic) IBOutlet UILabel *lblStateMCUWrite;
@property (strong, nonatomic) BleProtocol *protocol;
@property (nonatomic,assign) id <BLEProtocolDelegate> lastProtocolDelegate;
@end
//
// FirmwareUpdateController.m
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2017/06/05.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import "FirmwareUpdateController.h"
#import "FirmwareWriteController.h"
@interface FirmwareUpdateController ()
@end
@implementation FirmwareUpdateController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated {
self.lastProtocolDelegate = self.protocol.delegate;
self.protocol.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated {
self.protocol.delegate = self.lastProtocolDelegate;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)modeBootloaderButtonClicked:(id)sender {
firmwareUpdateState = MODE_FIRMWARE_IMAGE_SELECT_0_EEPROM_WP_OFF;
[self firmwareWriteTask];
}
- (IBAction)modeImage1ButtonClicked:(id)sender {
firmwareUpdateState = MODE_FIRMWARE_IMAGE_SELECT_1_EEPROM_WP_OFF;
[self firmwareWriteTask];
}
- (IBAction)cancelButtonClicked:(id)sender {
[self dismissViewControllerAnimated:YES completion:Nil];
}
- (IBAction)mcuWriteButtonClicked:(id)sender {
FirmwareWriteController *viewObj=[[FirmwareWriteController alloc] initWithNibName:@"FirmwareWriteController" bundle:nil];
viewObj.protocol = self.protocol;
[self presentViewController:viewObj animated:YES completion: nil];
}
- (void)protocolDidGetData:(NSString *)dataType data:(NSString *)dataData {
if([dataType isEqualToString:@"firmwareImageSelect"]) {
if([dataData isEqualToString: @"0"]) {
[[self protocol]putData:@"systemReset" data:nil];
} else if([dataData isEqualToString: @"1"]) {
[[self protocol]putData:@"systemReset" data:nil];
}
} else if([dataType isEqualToString:@"eepromWriteProtect"]) {
if([dataData isEqualToString:@"0"]) {
NSLog(@"firmwareImageSelect 0");
switch(firmwareUpdateState) {
case MODE_FIRMWARE_IMAGE_SELECT_0_EEPROM_WP_OFF:
firmwareUpdateState = MODE_FIRMWARE_IMAGE_SELECT_0_EEPROM_WP_OFF_DONE;
break;
case MODE_FIRMWARE_IMAGE_SELECT_1_EEPROM_WP_OFF:
firmwareUpdateState = MODE_FIRMWARE_IMAGE_SELECT_1_EEPROM_WP_OFF_DONE;
break;
default:
break;
}
[self firmwareWriteTask];
}
}
}
- (void)firmwareWriteTask {
switch(firmwareUpdateState) {
case MODE_FIRMWARE_IMAGE_SELECT_0_EEPROM_WP_OFF:
[[self protocol]putData:@"eepromWriteProtect" data:@"0"];
break;
case MODE_FIRMWARE_IMAGE_SELECT_0_EEPROM_WP_OFF_DONE:
firmwareUpdateState = MODE_FIRMWARE_IMAGE_SELECT_0_RESET_IN_BOOTLOADER;
[self firmwareWriteTask];
break;
case MODE_FIRMWARE_IMAGE_SELECT_0_RESET_IN_BOOTLOADER:
[[self protocol]putData:@"systemResetInBootloader" data:nil];
break;
case MODE_FIRMWARE_IMAGE_SELECT_1_EEPROM_WP_OFF:
[[self protocol]putData:@"eepromWriteProtect" data:@"0"];
break;
case MODE_FIRMWARE_IMAGE_SELECT_1_EEPROM_WP_OFF_DONE:
firmwareUpdateState = MODE_FIRMWARE_IMAGE_SELECT_1;
[self firmwareWriteTask];
break;
case MODE_FIRMWARE_IMAGE_SELECT_1:
[[self protocol]putData:@"firmwareImageSelect" data:@"1"];
break;
case MODE_FIRMWARE_IMAGE_SELECT_1_DONE:
firmwareUpdateState = MODE_FIRMWARE_IMAGE_SELECT_1_RESET;
[self firmwareWriteTask];
break;
case MODE_FIRMWARE_IMAGE_SELECT_1_RESET:
[[self protocol]putData:@"systemReset" data:nil];
break;
}
}
@end
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="FirmwareUpdateController">
<connections>
<outlet property="lblStateMCUWrite" destination="4iS-Ml-6zs" id="O5y-do-L3o"/>
<outlet property="view" destination="Dee-Uj-9dH" id="pHd-FJ-YjS"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view contentMode="scaleToFill" id="Dee-Uj-9dH">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="FCe-34-Low">
<rect key="frame" x="118" y="165" width="138" height="30"/>
<state key="normal" title="選択して書込み開始"/>
<connections>
<action selector="mcuWriteButtonClicked:" destination="-1" eventType="touchUpInside" id="mav-u1-ZQe"/>
</connections>
</button>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="書き込み:なし" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="4iS-Ml-6zs">
<rect key="frame" x="126" y="111" width="122" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<navigationBar contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="SZv-OE-aWd">
<rect key="frame" x="0.0" y="23" width="375" height="44"/>
<items>
<navigationItem title="ファームウェア更新" id="uhQ-pe-SM8">
<barButtonItem key="leftBarButtonItem" title="戻る" id="48U-xg-bRO">
<connections>
<action selector="cancelButtonClicked:" destination="-1" id="fys-Tk-uSB"/>
</connections>
</barButtonItem>
</navigationItem>
</items>
</navigationBar>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="4iS-Ml-6zs" firstAttribute="top" secondItem="SZv-OE-aWd" secondAttribute="bottom" constant="44" id="8bo-uQ-mYp"/>
<constraint firstItem="FCe-34-Low" firstAttribute="top" secondItem="4iS-Ml-6zs" secondAttribute="bottom" constant="33" id="9dJ-NV-aIu"/>
<constraint firstItem="4iS-Ml-6zs" firstAttribute="centerX" secondItem="FCe-34-Low" secondAttribute="centerX" id="Lt9-oI-Js3"/>
<constraint firstAttribute="trailing" secondItem="SZv-OE-aWd" secondAttribute="trailing" id="PHa-jh-RdD"/>
<constraint firstItem="4iS-Ml-6zs" firstAttribute="centerX" secondItem="SZv-OE-aWd" secondAttribute="centerX" id="ZFH-JH-KIM"/>
<constraint firstItem="SZv-OE-aWd" firstAttribute="top" secondItem="Dee-Uj-9dH" secondAttribute="top" constant="23" id="ak4-yS-Orr"/>
<constraint firstItem="SZv-OE-aWd" firstAttribute="leading" secondItem="Dee-Uj-9dH" secondAttribute="leading" id="nZt-Jg-g8l"/>
</constraints>
<point key="canvasLocation" x="21.5" y="-37.5"/>
</view>
</objects>
</document>
//
// FirmwareWriteController.h
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2017/06/06.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "BleProtocol.h"
#import "BLE.h"
#import <QuartzCore/QuartzCore.h>
typedef enum {
ERASE_PAGE_1,
UPLOAD_PAGE_10_ERASE_TEMP,
UPLOAD_PAGE_10_BEGIN,
UPLOAD_PAGE_10_CONTINUE,
UPLOAD_PAGE_10_RETRY,
UPLOAD_PAGE_10_END,
WRITE_PAGE_10,
WRITE_PAGE_10_DONE,
UPLOAD_PAGE_11_ERASE_TEMP,
UPLOAD_PAGE_11_BEGIN,
UPLOAD_PAGE_11_CONTINUE,
UPLOAD_PAGE_11_RETRY,
UPLOAD_PAGE_11_END,
WRITE_PAGE_11,
WRITE_PAGE_11_DONE,
UPLOAD_PAGE_12_ERASE_TEMP,
UPLOAD_PAGE_12_BEGIN,
UPLOAD_PAGE_12_CONTINUE,
UPLOAD_PAGE_12_RETRY,
UPLOAD_PAGE_12_END,
WRITE_PAGE_12,
WRITE_PAGE_12_DONE,
UPLOAD_PAGE_13_ERASE_TEMP,
UPLOAD_PAGE_13_BEGIN,
UPLOAD_PAGE_13_CONTINUE,
UPLOAD_PAGE_13_RETRY,
UPLOAD_PAGE_13_END,
WRITE_PAGE_13,
WRITE_PAGE_13_DONE,
UPLOAD_DONE,
EEPROM_WP_OFF,
EEPROM_WP_OFF_DONE,
FIRMWARE_IMAGE_SELECT_1,
FIRMWARE_IMAGE_SELECT_1_DONE,
RESET,
RESET_DONE
} FirmwareUpdateState;
@interface FirmwareWriteController : UIViewController<UITableViewDelegate, UITableViewDataSource, BLEProtocolDelegate> {
IBOutlet UITableView *tblFirmware;
IBOutlet UILabel *lblPercentComplete;
NSMutableArray *arrResult;
int selectionEnabled;
NSInputStream *firmwareFileStream;
unsigned long long firmwareFileStreamSize;
unsigned long long firmwareFileStreamPointer;
NSData *firmwareWriteBuffer;
int firmwareWriteBufferRetry;
FirmwareUpdateState firmwareUpdateState;
unsigned long long firmwareFlashPagePointer;
CFTimeInterval startTime;
}
@property (strong, nonatomic) BleProtocol *protocol;
@property (nonatomic,assign) id <BLEProtocolDelegate> lastProtocolDelegate;
- (BOOL)firmwareWriteTask;
@end
//
// FirmwareWriteController.m
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2017/06/06.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import "FirmwareWriteController.h"
#import "FirmwareWriteControllerTableViewCell.h"
#import "Operation.h"
#import "DBManager.h"
#import "NSData+NSString.h"
@interface FirmwareWriteController ()
@end
@implementation FirmwareWriteController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
selectionEnabled = 1;
arrResult = [[NSMutableArray alloc] init];
UINib *nib = [UINib nibWithNibName:@"FirmwareWriteControllerTableViewCell" bundle:nil];
[tblFirmware registerNib:nib forCellReuseIdentifier:@"mycell"];
tblFirmware.delegate = self;
tblFirmware.dataSource = self;
[arrResult removeAllObjects];
NSArray *result = [[DBManager sharedInstance] getFirmwareDataList];
for(id key in result) {
NSString *valueId = [key objectAtIndex:0];
NSString *valueUuid = [key objectAtIndex:1];
NSString *valueDeviceType = [key objectAtIndex:2];
NSString *valueDeviceModel = [key objectAtIndex:3];
NSString *valueVersion = [key objectAtIndex:4];
NSString *valueVersionStamp = [key objectAtIndex:5];
NSString *valueFile = [key objectAtIndex:6];
NSMutableDictionary *newDict = [NSMutableDictionary dictionary];
[newDict setObject:valueId forKey:@"id"];
[newDict setObject:valueUuid forKey:@"uuid"];
[newDict setObject:valueDeviceType forKey:@"deviceType"];
[newDict setObject:valueDeviceModel forKey:@"deviceModel"];
[newDict setObject:valueVersion forKey:@"version"];
[newDict setObject:valueVersionStamp forKey:@"versionStamp"];
[newDict setObject:valueFile forKey:@"file"];
[arrResult addObject:newDict];
}
[tblFirmware reloadData];
}
- (void)viewWillAppear:(BOOL)animated {
self.lastProtocolDelegate = self.protocol.delegate;
self.protocol.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated {
self.protocol.delegate = self.lastProtocolDelegate;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)cancelButtonClicked:(id)sender {
[self dismissViewControllerAnimated:YES completion:Nil];
}
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(selectionEnabled == 1) {
return indexPath;
} else {
return nil;
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger row = [indexPath row];
NSDictionary *dataRecord = [arrResult objectAtIndex:row];
NSString *filename = [dataRecord valueForKey:@"uuid"];
//selectionEnabled = 0;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: @"/save/%@",filename]];
firmwareFileStreamSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil] fileSize];
firmwareFileStream = [[NSInputStream alloc] initWithFileAtPath:path];
[firmwareFileStream open];
startTime = CACurrentMediaTime();
firmwareUpdateState = ERASE_PAGE_1;
//firmwareUpdateState = UPLOAD_DONE;
firmwareFileStreamPointer = 0;
firmwareWriteBufferRetry = 0;
[self firmwareWriteTask];
NSLog(@"bin file readout complete");
}
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
return @[
[UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive
title:@"削除"
handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
// own delete action
// Distructive button tapped.
NSLog(@"削除の確認");
NSDictionary * selectedData = [arrResult objectAtIndex:indexPath.row];
NSString *firmwareTitle = [selectedData valueForKey:@"file"];
UIAlertController *actionSheetConfirm = [UIAlertController alertControllerWithTitle:@"削除の確認" message:[NSString stringWithFormat:@"「%@」を削除します。よろしいですか?",firmwareTitle] preferredStyle:UIAlertControllerStyleAlert];
[actionSheetConfirm addAction:[UIAlertAction actionWithTitle:@"削除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *actionConfirm) {
// Get the record ID of the selected name and set it to the recordIDToEdit property.
NSDictionary * selectedData = [arrResult objectAtIndex:indexPath.row];
NSString *recordId = [selectedData valueForKey:@"id"];
NSLog(@"recordId = %@",recordId);
//NSString *firmwareFilename = [selectedData valueForKey:@"file"];
NSString *firmwareFilename = [selectedData valueForKey:@"uuid"];
NSLog(@"firmwareFilename = %@",firmwareFilename);
NSString *docPath = [NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *docPathFull = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/save/%@",firmwareFilename]];
//NSURL *docPathFullUrl = [NSURL URLWithString:docPathFull];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
BOOL success = [fileManager removeItemAtPath:docPathFull error:&error];
if(success) {
NSLog(@"削除した");
[[DBManager sharedInstance] deleteFirmwareData:recordId];
//[self populateDetail];
//[self.tblResult reloadData];
[arrResult removeObjectAtIndex:indexPath.row];
[tblFirmware deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
} else {
NSLog(@"削除を失敗した");
[[DBManager sharedInstance] deleteFirmwareData:recordId];
//[self populateDetail];
//[self.tblResult reloadData];
[arrResult removeObjectAtIndex:indexPath.row];
[tblFirmware deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}]];
[actionSheetConfirm addAction:[UIAlertAction actionWithTitle:@"キャンセル" style:UIAlertActionStyleDefault handler:^(UIAlertAction *actionConfirm) {
// Distructive button tapped.
NSLog(@"キャンセルの確認");
}]];
[self presentViewController:actionSheetConfirm animated:YES completion:nil];
}],
];
}
- (BOOL)firmwareWriteTask {
int packetDataSize = 18;
int readLength = 18;
unsigned long long firmwareFlashPageSize = 0x8000;
//unsigned long long firmwareFlashPageSize = 0x100;
switch(firmwareUpdateState) {
case ERASE_PAGE_1:
[[self protocol]putData:@"firmwareFlashErase" data:@"1"];
break;
case UPLOAD_PAGE_10_ERASE_TEMP:
[[self protocol]putData:@"firmwareBufferClear" data:nil];
break;
case UPLOAD_PAGE_10_BEGIN:
case UPLOAD_PAGE_11_BEGIN:
case UPLOAD_PAGE_12_BEGIN:
case UPLOAD_PAGE_13_BEGIN:
firmwareFlashPagePointer = firmwareFlashPageSize;
switch(firmwareUpdateState) {
case UPLOAD_PAGE_10_BEGIN:
firmwareUpdateState = UPLOAD_PAGE_10_CONTINUE;
break;
case UPLOAD_PAGE_11_BEGIN:
firmwareUpdateState = UPLOAD_PAGE_11_CONTINUE;
break;
case UPLOAD_PAGE_12_BEGIN:
firmwareUpdateState = UPLOAD_PAGE_12_CONTINUE;
break;
case UPLOAD_PAGE_13_BEGIN:
firmwareUpdateState = UPLOAD_PAGE_13_CONTINUE;
break;
default:
break;
}
case UPLOAD_PAGE_10_CONTINUE:
case UPLOAD_PAGE_11_CONTINUE:
case UPLOAD_PAGE_12_CONTINUE:
case UPLOAD_PAGE_13_CONTINUE:
{
if([firmwareFileStream hasBytesAvailable]) {
switch(firmwareUpdateState) {
case UPLOAD_PAGE_10_CONTINUE:
if((firmwareFileStreamPointer + readLength) > (firmwareFlashPageSize - 1)) {
readLength = (int)(firmwareFlashPageSize - firmwareFileStreamPointer);
}
break;
case UPLOAD_PAGE_11_CONTINUE:
if((firmwareFileStreamPointer + readLength) > (firmwareFlashPageSize * 2 - 1)) {
readLength = (int)(firmwareFlashPageSize * 2 - firmwareFileStreamPointer);
}
break;
case UPLOAD_PAGE_12_CONTINUE:
if((firmwareFileStreamPointer + readLength) > (firmwareFlashPageSize * 3 - 1)) {
readLength = (int)(firmwareFlashPageSize * 3 - firmwareFileStreamPointer);
}
break;
case UPLOAD_PAGE_13_CONTINUE:
if((firmwareFileStreamPointer + readLength) > (firmwareFlashPageSize * 4 - 1)) {
readLength = (int)(firmwareFlashPageSize * 4 - firmwareFileStreamPointer);
}
break;
default:
break;
}
unsigned char outputBuffer[20];
unsigned char outputBufferData[20];
for(int i = 0; i < 20; i++) {
outputBuffer[i] = 0;
outputBufferData[i] = 0;
}
NSInteger length = [firmwareFileStream read:outputBufferData maxLength:readLength];
firmwareFileStreamPointer += length;
firmwareFlashPagePointer -= length;
int indexFrom = 0;
int indexTo = 0;
outputBuffer[indexTo++] = 'x';
uint8_t outputBufferChecksum = 0x00;
while(indexFrom < length) {
outputBufferChecksum ^= outputBufferData[indexFrom];
outputBuffer[indexTo++] = outputBufferData[indexFrom++];
}
while(indexTo < (packetDataSize + 1)) {
outputBufferChecksum ^= 0xFF;
outputBuffer[indexTo++] = 0xFF;
}
outputBuffer[indexTo++] = outputBufferChecksum;
firmwareWriteBuffer = [NSData dataWithBytes:outputBuffer length:indexTo];
NSUInteger firmwareWriteBufferLength = [firmwareWriteBuffer length];
Byte *firmwareWriteBufferLengthByteData = (Byte*)malloc(firmwareWriteBufferLength);
memcpy(firmwareWriteBufferLengthByteData, [firmwareWriteBuffer bytes], firmwareWriteBufferLength);
NSMutableString *firmwareWriteBufferString = [NSMutableString stringWithCapacity:0];
for(int i = 0; i < [firmwareWriteBuffer length]; i++) {
[firmwareWriteBufferString appendFormat:@"%02x ", firmwareWriteBufferLengthByteData[i]];
}
CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
NSLog(@"BLE SEND(%d) %@ %llu / %llu %.2f%% %fsec",firmwareWriteBufferRetry,firmwareWriteBufferString,firmwareFileStreamPointer,firmwareFileStreamSize,(float)firmwareFileStreamPointer / (float)firmwareFileStreamSize * 100, elapsedTime);
lblPercentComplete.text = [NSString stringWithFormat:@"%llu / %llu %.2f%% %.02f秒",firmwareFileStreamPointer,firmwareFileStreamSize,(float)firmwareFileStreamPointer / (float)firmwareFileStreamSize * 100, elapsedTime];
[self.protocol bleWriteRaw:firmwareWriteBuffer];
} else if (firmwareFileStreamPointer == firmwareFileStreamSize) {
switch(firmwareUpdateState) {
case UPLOAD_PAGE_10_CONTINUE:
firmwareUpdateState = UPLOAD_PAGE_10_END;
break;
case UPLOAD_PAGE_11_CONTINUE:
firmwareUpdateState = UPLOAD_PAGE_11_END;
break;
case UPLOAD_PAGE_12_CONTINUE:
firmwareUpdateState = UPLOAD_PAGE_12_END;
break;
case UPLOAD_PAGE_13_CONTINUE:
firmwareUpdateState = UPLOAD_PAGE_13_END;
break;
default:
break;
}
[self firmwareWriteTask];
} else {
NSLog(@"Should not get here, something bad bad happened!!!");
NSLog(@"firmwareFileStreamPointer should never be larger than firmwareFileStreamSize, ever!!!");
}
//NSData *nsData = [@"fw@" dataUsingEncoding:NSUTF8StringEncoding];
//[self.protocol putData:@"infoDeviceId" data:nil];
return true;
break;
}
case UPLOAD_PAGE_10_RETRY:
case UPLOAD_PAGE_11_RETRY:
case UPLOAD_PAGE_12_RETRY:
case UPLOAD_PAGE_13_RETRY:
{
NSUInteger firmwareWriteBufferLength = [firmwareWriteBuffer length];
Byte *firmwareWriteBufferLengthByteData = (Byte*)malloc(firmwareWriteBufferLength);
memcpy(firmwareWriteBufferLengthByteData, [firmwareWriteBuffer bytes], firmwareWriteBufferLength);
NSMutableString *firmwareWriteBufferString = [NSMutableString stringWithCapacity:0];
for(int i = 0; i < [firmwareWriteBuffer length]; i++) {
[firmwareWriteBufferString appendFormat:@"%02x ", firmwareWriteBufferLengthByteData[i]];
}
CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
NSLog(@"BLE RESEND(%d) %@ %llu / %llu %.2f%% %fsec",firmwareWriteBufferRetry,firmwareWriteBufferString,firmwareFileStreamPointer,firmwareFileStreamSize,(float)firmwareFileStreamPointer / (float)firmwareFileStreamSize * 100, elapsedTime);
[self.protocol bleWriteRaw:firmwareWriteBuffer];
//NSData *nsData = [@"fw@" dataUsingEncoding:NSUTF8StringEncoding];
//[self.protocol putData:@"infoDeviceId" data:nil];
return true;
break;
}
case UPLOAD_PAGE_10_END:
firmwareUpdateState = WRITE_PAGE_10;
[self firmwareWriteTask];
break;
case WRITE_PAGE_10:
[[self protocol]putData:@"firmwareFlashWrite" data:@"10"];
break;
case WRITE_PAGE_10_DONE:
if (firmwareFileStreamPointer != firmwareFileStreamSize) {
firmwareUpdateState = UPLOAD_PAGE_11_ERASE_TEMP;
} else {
firmwareUpdateState = UPLOAD_DONE;
}
[self firmwareWriteTask];
break;
case UPLOAD_PAGE_11_ERASE_TEMP:
[[self protocol]putData:@"firmwareBufferClear" data:nil];
break;
case UPLOAD_PAGE_11_END:
firmwareUpdateState = WRITE_PAGE_11;
[self firmwareWriteTask];
break;
case WRITE_PAGE_11:
[[self protocol]putData:@"firmwareFlashWrite" data:@"11"];
break;
case WRITE_PAGE_11_DONE:
if (firmwareFileStreamPointer != firmwareFileStreamSize) {
firmwareUpdateState = UPLOAD_PAGE_12_ERASE_TEMP;
} else {
firmwareUpdateState = UPLOAD_DONE;
}
[self firmwareWriteTask];
break;
case UPLOAD_PAGE_12_ERASE_TEMP:
[[self protocol]putData:@"firmwareBufferClear" data:nil];
break;
case UPLOAD_PAGE_12_END:
firmwareUpdateState = WRITE_PAGE_12;
[self firmwareWriteTask];
break;
case WRITE_PAGE_12:
[[self protocol]putData:@"firmwareFlashWrite" data:@"12"];
break;
case WRITE_PAGE_12_DONE:
if (firmwareFileStreamPointer != firmwareFileStreamSize) {
firmwareUpdateState = UPLOAD_PAGE_13_ERASE_TEMP;
} else {
firmwareUpdateState = UPLOAD_DONE;
}
[self firmwareWriteTask];
break;
case UPLOAD_PAGE_13_ERASE_TEMP:
[[self protocol]putData:@"firmwareBufferClear" data:nil];
break;
case UPLOAD_PAGE_13_END:
firmwareUpdateState = WRITE_PAGE_13;
[self firmwareWriteTask];
break;
case WRITE_PAGE_13:
[[self protocol]putData:@"firmwareFlashWrite" data:@"13"];
break;
case WRITE_PAGE_13_DONE:
firmwareUpdateState = UPLOAD_DONE;
[self firmwareWriteTask];
break;
case UPLOAD_DONE:
//firmwareUpdateState = EEPROM_WP_OFF;
//[self firmwareWriteTask];
{
CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
NSLog(@"Firmware upload done! %fsec", elapsedTime);
break;
}
case EEPROM_WP_OFF:
[[self protocol]putData:@"eepromWriteProtect" data:@"0"];
break;
case EEPROM_WP_OFF_DONE:
firmwareUpdateState = FIRMWARE_IMAGE_SELECT_1;
[self firmwareWriteTask];
break;
case FIRMWARE_IMAGE_SELECT_1:
[[self protocol]putData:@"firmwareImageSelect" data:@"1"];
break;
case FIRMWARE_IMAGE_SELECT_1_DONE:
firmwareUpdateState = RESET;
[self firmwareWriteTask];
break;
case RESET:
[[self protocol]putData:@"systemReset" data:nil];
break;
case RESET_DONE:
{
CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;
NSLog(@"Firmware upload done! %fsec", elapsedTime);
break;
}
}
return false;
}
- (void)protocolDidGetData:(NSString *)dataType data:(NSString *)dataData {
if([dataType isEqualToString:@"firmwareFlashErase"]) {
if([dataData isEqualToString: @"1"]) {
if(firmwareUpdateState == ERASE_PAGE_1) {
firmwareUpdateState = UPLOAD_PAGE_10_ERASE_TEMP;
[self firmwareWriteTask];
}
}
} else if([dataType isEqualToString:@"firmwareBufferClear"]) {
switch(firmwareUpdateState) {
case UPLOAD_PAGE_10_ERASE_TEMP:
firmwareUpdateState = UPLOAD_PAGE_10_BEGIN;
break;
case UPLOAD_PAGE_11_ERASE_TEMP:
firmwareUpdateState = UPLOAD_PAGE_11_BEGIN;
break;
case UPLOAD_PAGE_12_ERASE_TEMP:
firmwareUpdateState = UPLOAD_PAGE_12_BEGIN;
break;
case UPLOAD_PAGE_13_ERASE_TEMP:
firmwareUpdateState = UPLOAD_PAGE_13_BEGIN;
break;
default:
break;
}
[self firmwareWriteTask];
} else if([dataType isEqualToString:@"firmwareBufferWrite"]) {
if([dataData isEqualToString: @"OK"]) {
if(firmwareWriteBufferRetry != 0) {
firmwareWriteBufferRetry = 0;
switch(firmwareUpdateState) {
case UPLOAD_PAGE_10_RETRY:
firmwareUpdateState = UPLOAD_PAGE_10_CONTINUE;
break;
case UPLOAD_PAGE_11_RETRY:
firmwareUpdateState = UPLOAD_PAGE_11_CONTINUE;
break;
case UPLOAD_PAGE_12_RETRY:
firmwareUpdateState = UPLOAD_PAGE_12_CONTINUE;
break;
case UPLOAD_PAGE_13_RETRY:
firmwareUpdateState = UPLOAD_PAGE_13_CONTINUE;
break;
default:
break;
}
}
if(firmwareFlashPagePointer == 0) {
switch(firmwareUpdateState) {
case UPLOAD_PAGE_10_CONTINUE:
firmwareUpdateState = UPLOAD_PAGE_10_END;
break;
case UPLOAD_PAGE_11_CONTINUE:
firmwareUpdateState = UPLOAD_PAGE_11_END;
break;
case UPLOAD_PAGE_12_CONTINUE:
firmwareUpdateState = UPLOAD_PAGE_12_END;
break;
case UPLOAD_PAGE_13_CONTINUE:
firmwareUpdateState = UPLOAD_PAGE_13_END;
break;
default:
break;
}
}
[self firmwareWriteTask];
} else {
if(firmwareWriteBufferRetry < 10) {
firmwareWriteBufferRetry++;
switch(firmwareUpdateState) {
case UPLOAD_PAGE_10_CONTINUE:
firmwareUpdateState = UPLOAD_PAGE_10_RETRY;
break;
case UPLOAD_PAGE_11_CONTINUE:
firmwareUpdateState = UPLOAD_PAGE_11_RETRY;
break;
case UPLOAD_PAGE_12_CONTINUE:
firmwareUpdateState = UPLOAD_PAGE_12_RETRY;
break;
case UPLOAD_PAGE_13_CONTINUE:
firmwareUpdateState = UPLOAD_PAGE_13_RETRY;
break;
default:
break;
}
[self firmwareWriteTask];
} else {
NSLog(@"BLE RESEND(%d) RETRY EXCEED, GIVE UP",firmwareWriteBufferRetry);
}
}
} else if([dataType isEqualToString:@"firmwareFlashWrite"]) {
if([dataData isEqualToString:@"10"]) {
NSLog(@"firmwareFlashWrite 10");
firmwareUpdateState = WRITE_PAGE_10_DONE;
[self firmwareWriteTask];
} else if([dataData isEqualToString:@"11"]) {
NSLog(@"firmwareFlashWrite 11");
firmwareUpdateState = WRITE_PAGE_11_DONE;
[self firmwareWriteTask];
} else if([dataData isEqualToString:@"12"]) {
NSLog(@"firmwareFlashWrite 12");
firmwareUpdateState = WRITE_PAGE_12_DONE;
[self firmwareWriteTask];
} else if([dataData isEqualToString:@"13"]) {
NSLog(@"firmwareFlashWrite 13");
firmwareUpdateState = WRITE_PAGE_13_DONE;
[self firmwareWriteTask];
}
} else if([dataType isEqualToString:@"firmwareImageSelect"]) {
if([dataData isEqualToString:@"1"]) {
NSLog(@"firmwareImageSelect 1");
firmwareUpdateState = FIRMWARE_IMAGE_SELECT_1_DONE;
[self firmwareWriteTask];
}
} else if([dataType isEqualToString:@"eepromWriteProtect"]) {
if([dataData isEqualToString:@"0"]) {
NSLog(@"firmwareImageSelect 0");
firmwareUpdateState = EEPROM_WP_OFF_DONE;
[self firmwareWriteTask];
}
} else if([dataType isEqualToString:@"systemReset"]) {
NSLog(@"firmwareImageSelect 1");
firmwareUpdateState = RESET_DONE;
[self firmwareWriteTask];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [arrResult count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"mycell";
FirmwareWriteControllerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
NSInteger row = [indexPath row];
NSDictionary *dataRecord = [arrResult objectAtIndex:row];
// Configure the cell...
UIFont *newFont = [UIFont fontWithName:@"Arial" size:11.0];
cell.lblTitle.font = newFont;
cell.lblTitle.text = [dataRecord valueForKey:@"file"];
newFont = [UIFont fontWithName:@"Arial" size:11.0];
cell.lblSubtitle.font = newFont;
cell.lblSubtitle.text = [dataRecord valueForKey:@"uuid"];
return cell;
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="12120" systemVersion="16F73" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12088"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="FirmwareWriteController">
<connections>
<outlet property="lblPercentComplete" destination="gbe-O8-4MZ" id="tzg-Iq-QuD"/>
<outlet property="tblFirmware" destination="Bm4-3e-kcl" id="MoB-u5-JGI"/>
<outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<navigationBar contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="GD6-XB-ga1">
<rect key="frame" x="0.0" y="23" width="375" height="44"/>
<items>
<navigationItem title="ファームウェア書き込み" id="M6c-ur-fNv">
<barButtonItem key="leftBarButtonItem" title="戻る" id="vHb-pY-nI8">
<connections>
<action selector="cancelButtonClicked:" destination="-1" id="PP3-RL-PMI"/>
</connections>
</barButtonItem>
</navigationItem>
</items>
</navigationBar>
<tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="Bm4-3e-kcl">
<rect key="frame" x="0.0" y="114" width="375" height="553"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
</tableView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="gbe-O8-4MZ">
<rect key="frame" x="0.0" y="85" width="375" height="21"/>
<constraints>
<constraint firstAttribute="height" constant="21" id="EGb-VE-YbS"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="Bm4-3e-kcl" firstAttribute="trailing" secondItem="gbe-O8-4MZ" secondAttribute="trailing" id="Abo-tT-Thu"/>
<constraint firstItem="GD6-XB-ga1" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" id="FtV-kf-WI3"/>
<constraint firstItem="gbe-O8-4MZ" firstAttribute="top" secondItem="GD6-XB-ga1" secondAttribute="bottom" constant="18" id="GoQ-Q5-91K"/>
<constraint firstItem="Bm4-3e-kcl" firstAttribute="top" secondItem="gbe-O8-4MZ" secondAttribute="bottom" constant="8" symbolic="YES" id="Une-zo-zte"/>
<constraint firstItem="gbe-O8-4MZ" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" id="fxk-Ov-pU5"/>
<constraint firstItem="Bm4-3e-kcl" firstAttribute="leading" secondItem="gbe-O8-4MZ" secondAttribute="leading" id="gbQ-tt-xdK"/>
<constraint firstAttribute="trailing" secondItem="GD6-XB-ga1" secondAttribute="trailing" id="jWA-Pb-qcK"/>
<constraint firstAttribute="trailing" secondItem="gbe-O8-4MZ" secondAttribute="trailing" id="qg6-AW-Ney"/>
<constraint firstAttribute="bottom" secondItem="Bm4-3e-kcl" secondAttribute="bottom" id="u5Z-t5-eje"/>
<constraint firstItem="GD6-XB-ga1" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="23" id="zUz-9r-bi8"/>
</constraints>
<point key="canvasLocation" x="24.5" y="52.5"/>
</view>
</objects>
</document>
//
// FirmwareWriteControllerTableViewCell.h
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2017/06/07.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FirmwareWriteControllerTableViewCell : UITableViewCell
@property (strong, nonatomic) IBOutlet UILabel *lblTitle;
@property (strong, nonatomic) IBOutlet UILabel *lblSubtitle;
@end
//
// FirmwareWriteControllerTableViewCell.m
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2017/06/07.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import "FirmwareWriteControllerTableViewCell.h"
@implementation FirmwareWriteControllerTableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="12120" systemVersion="16F73" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12088"/>
<capability name="Constraints to layout margins" minToolsVersion="6.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<tableViewCell contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" id="KGk-i7-Jjw" customClass="FirmwareWriteControllerTableViewCell">
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="KGk-i7-Jjw" id="H2p-sc-9uM">
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="タイトル" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="hee-i7-oLg">
<rect key="frame" x="17" y="4" width="303" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="サブタイトル" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="XEF-Tk-t7H">
<rect key="frame" x="17" y="22" width="303" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="12"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstItem="XEF-Tk-t7H" firstAttribute="top" secondItem="H2p-sc-9uM" secondAttribute="topMargin" constant="14" id="4fz-2b-2iR"/>
<constraint firstAttribute="trailing" secondItem="hee-i7-oLg" secondAttribute="trailing" id="FPe-q7-Kt0"/>
<constraint firstItem="hee-i7-oLg" firstAttribute="leading" secondItem="H2p-sc-9uM" secondAttribute="leadingMargin" constant="9" id="LWf-z4-6OC"/>
<constraint firstItem="hee-i7-oLg" firstAttribute="top" secondItem="H2p-sc-9uM" secondAttribute="topMargin" constant="-4" id="aU2-zO-01S"/>
<constraint firstItem="hee-i7-oLg" firstAttribute="trailing" secondItem="XEF-Tk-t7H" secondAttribute="trailing" id="onp-HC-6zn"/>
<constraint firstItem="hee-i7-oLg" firstAttribute="leading" secondItem="XEF-Tk-t7H" secondAttribute="leading" id="wGx-O2-PWb"/>
<constraint firstAttribute="bottomMargin" secondItem="XEF-Tk-t7H" secondAttribute="bottom" constant="-7.5" id="yYM-VE-A2L"/>
</constraints>
</tableViewCellContentView>
<connections>
<outlet property="lblSubtitle" destination="XEF-Tk-t7H" id="6ub-Gh-yfi"/>
<outlet property="lblTitle" destination="hee-i7-oLg" id="Exz-fq-eqY"/>
</connections>
</tableViewCell>
</objects>
</document>
//
// InputMotorController.h
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2017/02/23.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "BleProtocol.h"
#import "BLE.h"
@interface InputMotorController : UIViewController <BLEProtocolDelegate>
@property (nonatomic, strong) NSString *jacketId;
@property (strong, nonatomic) BleProtocol *protocol;
@property (nonatomic,assign) id <BLEProtocolDelegate> lastProtocolDelegate;
@end
//
// InputMotorController.m
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2017/02/23.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import "InputMotorController.h"
@interface InputMotorController ()
@property (strong, nonatomic) IBOutlet UIButton *btn0;
@property (strong, nonatomic) IBOutlet UIButton *btn1;
@property (strong, nonatomic) IBOutlet UIButton *btn2;
@end
@implementation InputMotorController {
UIView *_mask;
NSTimer *_writeResponseTimer;
bool ignoreWriteResponse;
id lastButton;
NSInteger newState;
}
@synthesize protocol;
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
[_mask removeFromSuperview];
[self dismissViewControllerAnimated:YES completion:Nil];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
_lastProtocolDelegate = protocol.delegate;
protocol.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
protocol.delegate = _lastProtocolDelegate;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (void)showAlert {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ジャケットの設定"
message:@"設定が保存されました。"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)showAlert:(NSString*)title message:(NSString*)message{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)showMask {
_mask = [[UIView alloc] initWithFrame:[self.view frame]];
[_mask setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.25]];
[self.view addSubview:_mask];
}
-(void)writeResponseTimeout:(NSTimer *)timer {
ignoreWriteResponse = true;
[self showAlert:@"ジャケットの設定" message:@"設定が保存されない。"];
}
- (void)protocolDidGetData:(NSString *)dataType data:(NSString *)dataData {
if([dataType isEqualToString:@"writeMotor"]){
if(ignoreWriteResponse) return;
[_writeResponseTimer invalidate];
if([dataData isEqual:@"OK"]) {
[self showAlert:@"ジャケットの設定" message:@"設定が保存されました。"];
} else {
[self showAlert:@"ジャケットの設定" message:@"設定が保存されない。"];
}
}
}
- (IBAction)btn0:(id)sender {
if(lastButton) {
[lastButton setBackgroundColor:[UIColor clearColor]];
}
lastButton = sender;
newState = 0;
[sender setBackgroundColor:[UIColor yellowColor]];
}
- (IBAction)btn1:(id)sender {
if(lastButton) {
[lastButton setBackgroundColor:[UIColor clearColor]];
}
lastButton = sender;
newState = 1;
[sender setBackgroundColor:[UIColor yellowColor]];
}
- (IBAction)btn2:(id)sender {
if(lastButton) {
[lastButton setBackgroundColor:[UIColor clearColor]];
}
lastButton = sender;
newState = 2;
[sender setBackgroundColor:[UIColor yellowColor]];
}
- (IBAction)cancelButtonClicked:(id)sender {
[self dismissViewControllerAnimated:YES completion:Nil];
}
- (IBAction)saveButtonClicked:(id)sender {
ignoreWriteResponse = false;
[self showMask];
[protocol putData:@"writeMotor" data:[NSString stringWithFormat:@"%ld",newState]];
_writeResponseTimer = [NSTimer scheduledTimerWithTimeInterval: 5.0 target: self selector:@selector(writeResponseTimeout:) userInfo: nil repeats:NO];
}
@end
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="InputMotorController">
<connections>
<outlet property="btn0" destination="y6L-Z8-PBp" id="0If-yX-pUs"/>
<outlet property="btn1" destination="N8B-HG-KJu" id="Qjf-65-PYn"/>
<outlet property="btn2" destination="YiN-Ek-vti" id="Fng-yV-kXC"/>
<outlet property="view" destination="9aV-RW-OZ8" id="LHe-HA-LNf"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view contentMode="scaleToFill" id="9aV-RW-OZ8">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="y6L-Z8-PBp">
<rect key="frame" x="172" y="97" width="30" height="30"/>
<state key="normal" title="OFF"/>
<connections>
<action selector="btn0:" destination="-2" eventType="touchUpInside" id="ASw-mk-2I6"/>
<action selector="btn0:" destination="-1" eventType="touchUpInside" id="eTs-nj-jCz"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="N8B-HG-KJu">
<rect key="frame" x="89" y="157" width="197" height="30"/>
<state key="normal" title="ON 0 (iOSホームボタン押し)"/>
<connections>
<action selector="btn1:" destination="-2" eventType="touchUpInside" id="VWj-L6-FAy"/>
<action selector="btn1:" destination="-1" eventType="touchUpInside" id="i5s-rG-fdC"/>
</connections>
</button>
<navigationBar contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="8X3-1K-oyZ">
<rect key="frame" x="0.0" y="23" width="375" height="44"/>
<items>
<navigationItem title="モーターの設定" id="JpB-f0-A8S">
<barButtonItem key="leftBarButtonItem" title="戻る" id="QfV-3b-uNb">
<connections>
<action selector="cancelButtonClicked:" destination="-1" id="kSA-tc-wgg"/>
</connections>
</barButtonItem>
<barButtonItem key="rightBarButtonItem" title="保存" id="Jvg-is-ZAy">
<connections>
<action selector="saveButtonClicked:" destination="-1" id="xkU-dg-36I"/>
</connections>
</barButtonItem>
</navigationItem>
</items>
</navigationBar>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="YiN-Ek-vti">
<rect key="frame" x="61" y="217" width="253" height="30"/>
<state key="normal" title="ON 1(ANDRIODホームボタン押し)"/>
<connections>
<action selector="btn2:" destination="-1" eventType="touchUpInside" id="avV-Oc-oJQ"/>
<action selector="btn2:" destination="-2" eventType="touchUpInside" id="yzK-gg-Icl"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="y6L-Z8-PBp" firstAttribute="top" secondItem="8X3-1K-oyZ" secondAttribute="bottom" constant="30" id="1IP-9d-ZtC"/>
<constraint firstItem="N8B-HG-KJu" firstAttribute="top" secondItem="y6L-Z8-PBp" secondAttribute="bottom" constant="30" id="ExD-uU-gJa"/>
<constraint firstItem="8X3-1K-oyZ" firstAttribute="centerX" secondItem="y6L-Z8-PBp" secondAttribute="centerX" id="JPi-Xc-I0P"/>
<constraint firstItem="YiN-Ek-vti" firstAttribute="top" secondItem="N8B-HG-KJu" secondAttribute="bottom" constant="30" id="O9g-kB-Qwr"/>
<constraint firstItem="y6L-Z8-PBp" firstAttribute="top" secondItem="8X3-1K-oyZ" secondAttribute="bottom" constant="30" id="ZmM-NH-pzR"/>
<constraint firstItem="N8B-HG-KJu" firstAttribute="centerX" secondItem="9aV-RW-OZ8" secondAttribute="centerX" id="apJ-QU-yP3"/>
<constraint firstItem="8X3-1K-oyZ" firstAttribute="top" secondItem="9aV-RW-OZ8" secondAttribute="top" constant="23" id="hqq-Uz-88D"/>
<constraint firstItem="YiN-Ek-vti" firstAttribute="centerX" secondItem="9aV-RW-OZ8" secondAttribute="centerX" id="kg8-xM-aVZ"/>
<constraint firstAttribute="trailing" secondItem="8X3-1K-oyZ" secondAttribute="trailing" id="lb2-Nl-Lmt"/>
<constraint firstItem="8X3-1K-oyZ" firstAttribute="leading" secondItem="9aV-RW-OZ8" secondAttribute="leading" id="xcc-yg-Zzi"/>
<constraint firstItem="y6L-Z8-PBp" firstAttribute="centerX" secondItem="9aV-RW-OZ8" secondAttribute="centerX" id="z3G-w1-vpt"/>
</constraints>
<point key="canvasLocation" x="-67" y="-73"/>
</view>
</objects>
</document>
//
// InputSoundController.h
// jacket_test_ios
//
// Created by ドラッサル 亜嵐 on 2017/10/06.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "BleProtocol.h"
#import "BLE.h"
@interface InputSoundController : UIViewController <BLEProtocolDelegate>
@property (nonatomic, strong) NSString *jacketId;
@property (strong, nonatomic) BleProtocol *protocol;
@property (nonatomic,assign) id <BLEProtocolDelegate> lastProtocolDelegate;
@end
//
// InputSoundController.m
// jacket_test_ios
//
// Created by ドラッサル 亜嵐 on 2017/10/06.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import "InputSoundController.h"
@interface InputSoundController ()
@property (strong, nonatomic) IBOutlet UIButton *btn0;
@property (strong, nonatomic) IBOutlet UIButton *btn1;
@end
@implementation InputSoundController {
UIView *_mask;
NSTimer *_writeResponseTimer;
bool ignoreWriteResponse;
id lastButton;
NSInteger newState;
}
@synthesize protocol;
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
[_mask removeFromSuperview];
[self dismissViewControllerAnimated:YES completion:Nil];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
_lastProtocolDelegate = protocol.delegate;
protocol.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
protocol.delegate = _lastProtocolDelegate;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (void)showAlert {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ジャケットの設定"
message:@"設定が保存されました。"
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)showAlert:(NSString*)title message:(NSString*)message{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)showMask {
_mask = [[UIView alloc] initWithFrame:[self.view frame]];
[_mask setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.25]];
[self.view addSubview:_mask];
}
-(void)writeResponseTimeout:(NSTimer *)timer {
ignoreWriteResponse = true;
[self showAlert:@"ジャケットの設定" message:@"設定が保存されない。"];
}
- (void)protocolDidGetData:(NSString *)dataType data:(NSString *)dataData {
if([dataType isEqualToString:@"writeSound"]){
if(ignoreWriteResponse) return;
[_writeResponseTimer invalidate];
if([dataData isEqual:@"OK"]) {
[self showAlert:@"ジャケットの設定" message:@"設定が保存されました。"];
} else {
[self showAlert:@"ジャケットの設定" message:@"設定が保存されない。"];
}
}
}
- (IBAction)btn0:(id)sender {
if(lastButton) {
[lastButton setBackgroundColor:[UIColor clearColor]];
}
lastButton = sender;
newState = 0;
[sender setBackgroundColor:[UIColor yellowColor]];
}
- (IBAction)btn1:(id)sender {
if(lastButton) {
[lastButton setBackgroundColor:[UIColor clearColor]];
}
lastButton = sender;
newState = 1;
[sender setBackgroundColor:[UIColor yellowColor]];
}
- (IBAction)cancelButtonClicked:(id)sender {
[self dismissViewControllerAnimated:YES completion:Nil];
}
- (IBAction)saveButtonClicked:(id)sender {
ignoreWriteResponse = false;
[self showMask];
[protocol putData:@"writeSound" data:[NSString stringWithFormat:@"%ld",newState]];
_writeResponseTimer = [NSTimer scheduledTimerWithTimeInterval: 5.0 target: self selector:@selector(writeResponseTimeout:) userInfo: nil repeats:NO];
}
@end
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="13196" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13173"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="InputSoundController">
<connections>
<outlet property="btn0" destination="PpR-jP-zBp" id="3vy-Dd-cfz"/>
<outlet property="btn1" destination="AoY-L8-av3" id="XJd-q4-Hsz"/>
<outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<navigationBar contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="MGO-KK-hkK">
<rect key="frame" x="0.0" y="23" width="375" height="44"/>
<items>
<navigationItem title="サウンドの設定" id="3l5-OJ-hVk">
<barButtonItem key="leftBarButtonItem" title="戻る" id="aaD-A8-qxu">
<connections>
<action selector="cancelButtonClicked:" destination="-1" id="92j-lv-7mZ"/>
</connections>
</barButtonItem>
<barButtonItem key="rightBarButtonItem" title="保存" id="tfS-NB-bAa">
<connections>
<action selector="saveButtonClicked:" destination="-1" id="Ct8-Yt-cqf"/>
</connections>
</barButtonItem>
</navigationItem>
</items>
</navigationBar>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="PpR-jP-zBp">
<rect key="frame" x="140" y="121" width="94" height="30"/>
<state key="normal" title="サウンド OFF"/>
<connections>
<action selector="btn0:" destination="-1" eventType="touchUpInside" id="D2i-qV-r6l"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="AoY-L8-av3">
<rect key="frame" x="143" y="184" width="88" height="30"/>
<state key="normal" title="サウンド ON"/>
<connections>
<action selector="btn1:" destination="-1" eventType="touchUpInside" id="YsA-cp-CR4"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="PpR-jP-zBp" firstAttribute="top" secondItem="MGO-KK-hkK" secondAttribute="bottom" constant="54" id="4bz-HU-IHi"/>
<constraint firstItem="AoY-L8-av3" firstAttribute="top" secondItem="PpR-jP-zBp" secondAttribute="bottom" constant="33" id="BWX-2h-now"/>
<constraint firstItem="MGO-KK-hkK" firstAttribute="centerX" secondItem="PpR-jP-zBp" secondAttribute="centerX" id="HE0-AV-Sn0"/>
<constraint firstItem="MGO-KK-hkK" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" id="JBI-H3-7oh"/>
<constraint firstItem="PpR-jP-zBp" firstAttribute="centerX" secondItem="AoY-L8-av3" secondAttribute="centerX" id="pYf-oQ-Q5a"/>
<constraint firstAttribute="trailing" secondItem="MGO-KK-hkK" secondAttribute="trailing" id="rjh-dO-gU9"/>
<constraint firstItem="MGO-KK-hkK" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="23" id="vcv-dy-VMf"/>
</constraints>
</view>
<barButtonItem title="Item" id="kIx-dO-d7Q"/>
</objects>
</document>
//
// Operation.h
// tuber
//
// Created by ドラッサル 亜嵐 on 2016/06/09.
// Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "AFNetworking.h"
@interface Operation : NSObject
@property (nonatomic, strong) AFHTTPSessionManager *manager;
@property (nonatomic, strong) AFHTTPSessionManager *managerCustom;
@property (nonatomic, strong) AFHTTPSessionManager *managerImage;
@property (nonatomic, strong) AFHTTPSessionManager *managerRaw;
@property (nonatomic, strong) AFHTTPSessionManager *managerStreamToFile;
@property (nonatomic, strong) NSString *pcbDeviceId;
@property (nonatomic, strong) NSString *pcbDeviceType;
@property (nonatomic, strong) NSString *pcbDeviceModel;
@property (nonatomic, strong) NSString *pcbDeviceOs;
- (void)getFirmwareList:(NSString*)deviceId
deviceType:(NSString*)deviceType
deviceModel:(NSString*)deviceModel
deviceOs:(NSString*)deviceOs
appVersion:(NSString*)appVersion
success:(void(^)(id JSON))successHandler
failure:(void(^)(NSError *error, id JSON))failureHandler;
- (void)getImage:(NSString*)urlString success:(void(^)(id JSON))successHandler failure:(void(^)(NSError *error, id JSON))failureHandler;
- (void)getRaw:(NSString*)urlString
success:(void(^)(id JSON))successHandler
failure:(void(^)(NSError *error, id JSON))failureHandler;
- (UIImage*)getImageFromFile:(NSString*)filename;
- (void)streamToFile:(NSString*)urlString
saveToPath:(NSString*)saveToPath
progressBlock:(void(^)(double fractionCompleted))progressBlock
success:(void(^)(NSString *savedTo))successHandler
failure:(void(^)(NSError *error))failureHandler;
+ (instancetype)sharedOperation;
@end
//
// Operation.m
// tuber
//
// Created by ドラッサル 亜嵐 on 2016/06/09.
// Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//
#import "Operation.h"
#import "AFNetworking.h"
@interface Operation () {
NSLock* _lock;
NSArray *_enableCountryNames;
NSArray *_enableCountryCodes;
}
@end
@implementation Operation
- (void)getFirmwareList:(NSString*)deviceId
deviceType:(NSString*)deviceType
deviceModel:(NSString*)deviceModel
deviceOs:(NSString*)deviceOs
appVersion:(NSString*)appVersion
success:(void(^)(id JSON))successHandler
failure:(void(^)(NSError *error, id JSON))failureHandler {
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:deviceId forKey:@"deviceid"];
[params setObject:deviceType forKey:@"devicetype"];
[params setObject:deviceModel forKey:@"devicemodel"];
[params setObject:deviceOs forKey:@"deviceos"];
[params setObject:appVersion forKey:@"appversion"];
params = [self buildParams:params needAuth:NO];
[self startOperationWithParams:params
reqApi:@"firmware_list.php"
method:@"GET"
success:^(id JSON) {
if (successHandler) {
successHandler(JSON);
}
}
failure:^(NSError *error, id JSON) {
//NSLog(@"ERROR %@", error);
if (failureHandler) {
failureHandler(error, JSON);
}
}];
}
- (void)getImage:(NSString*)urlString
success:(void(^)(id JSON))successHandler
failure:(void(^)(NSError *error, id JSON))failureHandler {
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params = [self buildParams:params needAuth:NO];
[self startImageOperationWithParams:params
path:urlString
method:@"GET"
success:^(id JSON) {
if (successHandler) {
successHandler(JSON);
}
}
failure:^(NSError *error, id JSON) {
//NSLog(@"ERROR %@", error);
if (failureHandler) {
failureHandler(error, JSON);
}
}];
}
- (void)getRaw:(NSString*)urlString
success:(void(^)(id JSON))successHandler
failure:(void(^)(NSError *error, id JSON))failureHandler {
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params = [self buildParams:params needAuth:NO];
[self startRawOperationWithParams:params
path:urlString
method:@"GET"
success:^(id JSON) {
if (successHandler) {
successHandler(JSON);
}
}
failure:^(NSError *error, id JSON) {
//NSLog(@"ERROR %@", error);
if (failureHandler) {
failureHandler(error, JSON);
}
}];
}
- (void)streamToFile:(NSString*)urlString
saveToPath:(NSString*)saveToPath
progressBlock:(void(^)(double fractionCompleted))progressBlock
success:(void(^)(NSString *savedTo))successHandler
failure:(void(^)(NSError *error))failureHandler {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *saveToPathFull = [documentsDirectory stringByAppendingPathComponent:saveToPath];
BOOL ex = [[NSFileManager defaultManager] fileExistsAtPath:saveToPathFull];
if(ex) {
NSLog(@"file exists: %@", saveToPathFull);
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL success = [fileManager removeItemAtPath:saveToPathFull error:&error];
if(success) {
NSLog(@"削除した");
} else {
NSLog(@"削除を失敗した");
}
} else {
NSLog(@"file does not exist: %@", saveToPathFull);
}
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request
progress:^(NSProgress * _Nonnull downloadProgress) {
//NSLog(@"Progress: %f", downloadProgress.fractionCompleted);
dispatch_async(dispatch_get_main_queue(), ^{
progressBlock(downloadProgress.fractionCompleted);
});
}
destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *saveToPathFull = [documentsDirectory stringByAppendingPathComponent:saveToPath];
NSString *saveToFolder = [saveToPathFull stringByDeletingLastPathComponent];
if (![[NSFileManager defaultManager] fileExistsAtPath:saveToFolder])
{
[[NSFileManager defaultManager] createDirectoryAtPath:saveToFolder withIntermediateDirectories:NO attributes:nil error:&error];
}
NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
//return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
return [documentsDirectoryURL URLByAppendingPathComponent:saveToPath];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
if(!error) {
//NSLog(@"File downloaded to: %@", filePath);
successHandler([NSString stringWithFormat:@"%@",filePath]);
} else {
failureHandler(error);
}
}];
[downloadTask resume];
}
- (UIImage*)getImageFromFile:(NSString*)filename {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: @"/save/%@",filename]];
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}
# pragma mark - Singleton pattern
static Operation *_sharedOperation;
- (id)init {
self = [super init];
if (self) {
// 初期処理
_lock = [[NSLock alloc] init];
}
return self;
}
+ (instancetype)sharedOperation {
@synchronized(self) {
if (_sharedOperation == nil) {
(void) [[self alloc] init]; // ここでは代入していない
}
}
return _sharedOperation;
}
+ (id)allocWithZone:(NSZone *)zone {
@synchronized(self) {
if (_sharedOperation == nil) {
_sharedOperation = [super allocWithZone:zone];
return _sharedOperation; // 最初の割り当てで代入し、返す
}
}
return nil;
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
#pragma mark - Private Methods
- (void)startOperationWithParams:(NSDictionary *)aParams
reqApi:(NSString *)reqApi
method:(NSString *)method
success:(void(^)(id JSON))successHandler
failure:(void(^)(NSError *error, id JSON))failureHandler {
NSString *reqApiFull = [NSString stringWithFormat:URL_PATH_API, reqApi];
NSString *reqUrlFull = [NSString stringWithFormat:@"%@%@", URL_BASE,reqApiFull];
[self startOperationWithParams:aParams reqUrlFull:reqUrlFull method:method success:successHandler failure:failureHandler];
}
- (void)startOperationWithParams:(NSDictionary *)aParams
reqUrlFull:(NSString *)reqUrlFull
method:(NSString *)method
success:(void(^)(id JSON))successHandler
failure:(void(^)(NSError *error, id JSON))failureHandler {
// form-urlencoded request
NSURL *URL = [NSURL URLWithString:reqUrlFull];
// set self.manager only if it hasn't been created yet
if(!self.managerCustom)
{
self.managerCustom = [AFHTTPSessionManager manager]; // 71%
//self.manager.requestSerializer = [AFJSONRequestSerializer serializer];
self.managerCustom.responseSerializer = [AFHTTPResponseSerializer serializer]; // 9.7%
self.managerCustom.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"application/x-www-form-urlencoded", nil];
}
/*
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
*/
NSMutableDictionary *params = [self buildParams:aParams needAuth:NO];
/*
NSMutableURLRequest *request = [httpClient requestWithMethod:method
path:path
parameters:params];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
*/
if([method isEqualToString:@"GET"]) {
[self.managerCustom GET:URL.absoluteString parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
if([responseObject isKindOfClass:[NSDictionary class]]) {
if(successHandler) {
successHandler(responseObject);
}
}
else {
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
NSLog(@"[Operation] => resultObject: %@", response);
if(!response) {
NSMutableDictionary *queryStringDictionary = [[NSMutableDictionary alloc] init];
NSString * responseString = [[NSString alloc] initWithBytes:(char *)[responseObject bytes] length:[responseObject length] encoding:NSUTF8StringEncoding];
NSArray *urlComponents = [responseString componentsSeparatedByString:@"&"];
for (NSString *keyValuePair in urlComponents)
{
NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
NSString *key = [[pairComponents firstObject] stringByRemovingPercentEncoding];
NSString *value = [[pairComponents lastObject] stringByRemovingPercentEncoding];
value = [value stringByReplacingOccurrencesOfString:@"+" withString:@" "];
value = [value stringByRemovingPercentEncoding];
[queryStringDictionary setObject:value forKey:key];
}
response = queryStringDictionary;
}
if(successHandler) {
successHandler(response);
}
}
} failure:^(NSURLSessionTask *operation, NSError *error) {
//NSLog(@"[Operation] => resultObject: %@", responseObject);
NSLog(@"[Operation] => error: %@", error);
if (failureHandler) {
//failureHandler(error, responseObject);
failureHandler(error, nil);
}
}];
} else if([method isEqualToString:@"POST"]) {
[self.managerCustom POST:URL.absoluteString parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
if([responseObject isKindOfClass:[NSDictionary class]]) {
if(successHandler) {
successHandler(responseObject);
}
}
else {
NSLog(@"[Operation] => resultObject: %@", responseObject);
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
if(successHandler) {
successHandler(response);
}
}
} failure:^(NSURLSessionTask *operation, NSError *error) {
//NSLog(@"[Operation] => resultObject: %@", responseObject);
NSLog(@"[Operation] => error: %@", error);
if (failureHandler) {
//failureHandler(error, responseObject);
failureHandler(error, nil);
}
}];
}
//NSLog(@"[Operation] => startResuest: %@", [[request URL] absoluteString]);
NSLog(@"[Operation] => params: %@", params);
}
- (void)startImageOperationWithParams:(NSDictionary *)aParams
path:(NSString *)pathString
method:(NSString *)method
success:(void(^)(id JSON))successHandler
failure:(void(^)(NSError *error, id JSON))failureHandler {
[self startImageOperationWithParams:aParams reqPath:@"%@" path:pathString method:method success:successHandler failure:failureHandler];
}
- (void)startImageOperationWithParams:(NSDictionary *)aParams
reqPath:(NSString *)reqPathStr
path:(NSString *)pathString
method:(NSString *)method
success:(void(^)(id JSON))successHandler
failure:(void(^)(NSError *error, id JSON))failureHandler {
// form-urlencoded request
NSString *path = [NSString stringWithFormat:reqPathStr, pathString];
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",path]];
// set self.manager only if it hasn't been created yet
if(!self.managerImage)
{
self.managerImage = [AFHTTPSessionManager manager]; // 71%
//self.managerImage.requestSerializer = [AFJSONRequestSerializer serializer];
self.managerImage.responseSerializer = [AFImageResponseSerializer serializer]; // 9.7%
}
/*
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
*/
NSMutableDictionary *params = [self buildParams:aParams needAuth:NO];
/*
NSMutableURLRequest *request = [httpClient requestWithMethod:method
path:path
parameters:params];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
*/
if([method isEqualToString:@"GET"]) {
[self.managerImage GET:URL.absoluteString parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"[Operation] => resultObject: %@", responseObject);
if(successHandler) {
successHandler(responseObject);
}
} failure:^(NSURLSessionTask *operation, NSError *error) {
//NSLog(@"[Operation] => resultObject: %@", responseObject);
NSLog(@"[Operation] => error: %@", error);
if (failureHandler) {
//failureHandler(error, responseObject);
failureHandler(error, nil);
}
}];
} else if([method isEqualToString:@"POST"]) {
[self.managerImage POST:URL.absoluteString parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(@"[Operation] => resultObject: %@", responseObject);
if(successHandler) {
successHandler(responseObject);
}
} failure:^(NSURLSessionTask *operation, NSError *error) {
//NSLog(@"[Operation] => resultObject: %@", responseObject);
NSLog(@"[Operation] => error: %@", error);
if (failureHandler) {
//failureHandler(error, responseObject);
failureHandler(error, nil);
}
}];
}
//NSLog(@"[Operation] => startResuest: %@", [[request URL] absoluteString]);
NSLog(@"[Operation] => params: %@", params);
}
- (void)startRawOperationWithParams:(NSDictionary *)aParams
path:(NSString *)pathString
method:(NSString *)method
success:(void(^)(id JSON))successHandler
failure:(void(^)(NSError *error, id JSON))failureHandler {
[self startRawOperationWithParams:aParams reqPath:@"%@" path:pathString method:method success:successHandler failure:failureHandler];
}
- (void)startRawOperationWithParams:(NSDictionary *)aParams
reqPath:(NSString *)reqPathStr
path:(NSString *)pathString
method:(NSString *)method
success:(void(^)(id JSON))successHandler
failure:(void(^)(NSError *error, id JSON))failureHandler {
// form-urlencoded request
NSString *path = [NSString stringWithFormat:reqPathStr, pathString];
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",path]];
// set self.manager only if it hasn't been created yet
if(!self.managerRaw)
{
self.managerRaw = [AFHTTPSessionManager manager]; // 71%
//self.managerRaw.responseSerializer = [AFJSONRequestSerializer serializer];
//self.managerRaw.responseSerializer = [AFImageResponseSerializer serializer]; // 9.7%
self.managerRaw.responseSerializer = [AFHTTPResponseSerializer serializer]; // 9.7%
}
/*
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
*/
NSMutableDictionary *params = [self buildParams:aParams needAuth:NO];
/*
NSMutableURLRequest *request = [httpClient requestWithMethod:method
path:path
parameters:params];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
*/
if([method isEqualToString:@"GET"]) {
[self.managerRaw GET:URL.absoluteString parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
//NSLog(@"[Operation] => resultObject: %@", responseObject);
if(successHandler) {
successHandler(responseObject);
}
} failure:^(NSURLSessionTask *operation, NSError *error) {
//NSLog(@"[Operation] => resultObject: %@", responseObject);
NSLog(@"[Operation] => error: %@", error);
if (failureHandler) {
//failureHandler(error, responseObject);
failureHandler(error, nil);
}
}];
} else if([method isEqualToString:@"POST"]) {
[self.managerRaw POST:URL.absoluteString parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
//NSLog(@"[Operation] => resultObject: %@", responseObject);
if(successHandler) {
successHandler(responseObject);
}
} failure:^(NSURLSessionTask *operation, NSError *error) {
//NSLog(@"[Operation] => resultObject: %@", responseObject);
NSLog(@"[Operation] => error: %@", error);
if (failureHandler) {
//failureHandler(error, responseObject);
failureHandler(error, nil);
}
}];
}
//NSLog(@"[Operation] => startResuest: %@", [[request URL] absoluteString]);
NSLog(@"[Operation] => params: %@", params);
}
/*
- (void)startOperationWithParams:(NSDictionary *)aParams
reqPath:(NSString *)reqPathStr
path:(NSString *)pathString
method:(NSString *)method
success:(void(^)(id JSON))successHandler
failure:(void(^)(NSError *error, id JSON))failureHandler {
// form-urlencoded request
NSString *path = [NSString stringWithFormat:reqPathStr, pathString];
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",BASE_URL,path]];
NSMutableDictionary *params = [self buildParams:aParams needAuth:NO];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URL.absoluteString parameters:nil error:nil];
req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
[req setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:params forKey:@"Some Key Value"];
[archiver finishEncoding];
// Here, data holds the serialized version of your dictionary
[req setHTTPBody:data];
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
if([responseObject isKindOfClass:[NSDictionary class]]) {
if(successHandler) {
successHandler(responseObject);
}
}
else {
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
NSLog(@"[Operation] => resultObject: %@", response);
if(successHandler) {
successHandler(response);
}
}
} else {
//NSLog(@"[Operation] => resultObject: %@", responseObject);
NSLog(@"[Operation] => error: %@", error);
if (failureHandler) {
//failureHandler(error, responseObject);
failureHandler(error, nil);
}
}
}] resume];
//NSLog(@"[Operation] => startResuest: %@", [[request URL] absoluteString]);
NSLog(@"[Operation] => params: %@", params);
}
*/
# pragma mark - Network management methods
- (NSMutableDictionary *)buildParams:(NSDictionary *)params needAuth:(BOOL)needAuth {
// APIの基本パラメータを生成
NSMutableDictionary *result = [NSMutableDictionary dictionary];
if (params) {
[result setValuesForKeysWithDictionary:params];
}
if (needAuth) {
NSString *username = USER_USERID;
if (!username)
username = @"";
NSString *password = USER_PASSWORD;
if (!password)
password = @"";
[result setObject:username forKey:KEY_USER_USERID];
[result setObject:password forKey:KEY_USER_PASSWORD];
}
//[result setObject:@"ios" forKey:AGENT_KEY];
//[result setObject:@"vname" forKey:VNAME_KEY];
return result;
}
@end
//
// SettingsController.h
// jacketparentweb
//
// Created by Chris Johnston on 11/28/16.
// Copyright © 2016 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "BleProtocol.h"
#import "BLE.h"
typedef enum {
SETTINGS_CONTROLLER__EEPROM_READ_MODE,
SETTINGS_CONTROLLER__EEPROM_READ_MODE_DONE,
SETTINGS_CONTROLLER__EEPROM_READ_ID,
SETTINGS_CONTROLLER__EEPROM_READ_ID_DONE,
SETTINGS_CONTROLLER__EEPROM_READ_MODEL,
SETTINGS_CONTROLLER__EEPROM_READ_MODEL_DONE,
SETTINGS_CONTROLLER__EEPROM_READ_TYPE,
SETTINGS_CONTROLLER__EEPROM_READ_TYPE_DONE,
SETTINGS_CONTROLLER__EEPROM_READ_OS,
SETTINGS_CONTROLLER__EEPROM_READ_OS_DONE,
SETTINGS_CONTROLLER__EEPROM_READ_PIN,
SETTINGS_CONTROLLER__EEPROM_READ_PIN_DONE,
SETTINGS_CONTROLLER__DONE
} SettingsControllerCommandState;
@interface SettingsController : UIViewController <BLEProtocolDelegate> {
IBOutlet UILabel *lblDeviceMode;
IBOutlet UILabel *lblDeviceId;
IBOutlet UILabel *lblDeviceModel;
IBOutlet UILabel *lblDeviceType;
IBOutlet UILabel *lblDeviceOs;
IBOutlet UILabel *lblDevicePin;
SettingsControllerCommandState bleCommandState;
}
@property (nonatomic, strong) NSString *jacketId;
@property (strong, nonatomic) BLE *ble;
@property (strong, nonatomic) BleProtocol *protocol;
@property (nonatomic,assign) id <BLEProtocolDelegate> lastProtocolDelegate;
+ (void)show:(NSString*)jacketId navigationController:(UINavigationController*)navigationController;
@end
//
// SettingsController.m
// jacketparentweb
//
// Created by Chris Johnston on 11/28/16.
// Copyright © 2016 ドラッサル 亜嵐. All rights reserved.
//
#import "SettingsController.h"
#import "InputMotorController.h"
#import "InputSoundController.h"
#import "FirmwareDownloadController.h"
#import "FirmwareUpdateController.h"
#import "EepromController.h"
#import "BootSettingController.h"
@interface SettingsController ()
@property (strong, nonatomic) IBOutlet UIScrollView *scrollView;
@property (strong, nonatomic) IBOutlet UILabel *currentMotor;
@property (nonatomic) NSInteger itemCounter;
@property (nonatomic) NSTimer * tmr;
@end
@implementation SettingsController {
UIView *_mask;
NSTimer *_writeWalkResponseTimer;
NSTimer *_writeResetTimerResponseTimer;
bool ignoreWriteWalkResponse;
bool ignoreWriteResetUsetimeResponse;
NSArray<UILabel*>* timeRangeLabels;
NSMutableArray<NSString*>* timeRangeData;
NSArray<NSString*>* daysOfWeek;
}
@synthesize ble;
@synthesize protocol;
+ (void)show:(BleProtocol*)protocol navigationController:(UINavigationController*)navigationController {
SettingsController *viewObj=[[SettingsController alloc] initWithNibName:@"SettingsController" bundle:nil];
viewObj.protocol = protocol;
[navigationController pushViewController:viewObj animated:YES];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
_lastProtocolDelegate = protocol.delegate;
protocol.delegate = self;
bleCommandState = SETTINGS_CONTROLLER__EEPROM_READ_ID;
[self bleCommandTask];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[self.tmr invalidate];
protocol.delegate = _lastProtocolDelegate;
}
- (void)dealloc {
// Do cleanup
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)writeResetTimerResponseTimeout:(NSTimer *)timer {
ignoreWriteResetUsetimeResponse = true;
[self showAlert:@"ジャケットの設定" message:@"設定が保存されない。"];
}
- (NSString*)byteToDays:(NSString*)dowByte{
NSMutableString *result = [NSMutableString stringWithString:@""];
const char *chars = [dowByte UTF8String];
Byte byte = strtoul(chars, NULL, 16);
for(int i=0; i<7; i++){
if(byte & (1 << i)) {
[result appendString:[daysOfWeek objectAtIndex:i]];
}
}
return [NSString stringWithString:result];
}
- (void)showAlert:(NSString*)title message:(NSString*)message{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
[_mask removeFromSuperview];
}
- (void)showMask {
_mask = [[UIView alloc] initWithFrame:[self.view frame]];
[_mask setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.25]];
[self.view addSubview:_mask];
}
- (IBAction)firmwareDownloadClicked:(id)sender {
FirmwareDownloadController *viewObj=[[FirmwareDownloadController alloc] initWithNibName:@"FirmwareDownloadController" bundle:nil];
viewObj.protocol = self.protocol;
[self presentViewController:viewObj animated:YES completion: nil];
}
- (IBAction)firmwareUpdateClicked:(id)sender {
FirmwareUpdateController *viewObj=[[FirmwareUpdateController alloc] initWithNibName:@"FirmwareUpdateController" bundle:nil];
viewObj.protocol = self.protocol;
[self presentViewController:viewObj animated:YES completion: nil];
}
- (IBAction)eepromUpdateClicked:(id)sender {
EepromController *viewObj=[[EepromController alloc] initWithNibName:@"EepromController" bundle:nil];
viewObj.protocol = self.protocol;
[self presentViewController:viewObj animated:YES completion: nil];
}
- (IBAction)bootUpdateClicked:(id)sender {
BootSettingController *viewObj=[[BootSettingController alloc] initWithNibName:@"BootSettingController" bundle:nil];
viewObj.protocol = self.protocol;
[self presentViewController:viewObj animated:YES completion: nil];
}
- (IBAction)InputMotorClicked:(id)sender {
InputMotorController *viewObj=[[InputMotorController alloc] initWithNibName:@"InputMotorController" bundle:nil];
viewObj.protocol = self.protocol;
[self presentViewController:viewObj animated:YES completion: nil];
}
- (IBAction)InputSoundClicked:(id)sender {
InputSoundController *viewObj=[[InputSoundController alloc] initWithNibName:@"InputSoundController" bundle:nil];
viewObj.protocol = self.protocol;
[self presentViewController:viewObj animated:YES completion: nil];
}
- (IBAction)resetClicked:(id)sender {
[[self protocol]putData:@"systemReset" data:nil];
}
- (IBAction)updateModeResetClicked:(id)sender {
[[self protocol]putData:@"eepromWriteProtect" data:@"0"];
}
- (BOOL)bleCommandTask {
switch(bleCommandState) {
case SETTINGS_CONTROLLER__EEPROM_READ_MODE:
[[self protocol]putData:@"infoDeviceId" data:nil];
break;
case SETTINGS_CONTROLLER__EEPROM_READ_ID:
[[self protocol]putData:@"infoDeviceId" data:nil];
break;
case SETTINGS_CONTROLLER__EEPROM_READ_MODEL:
[[self protocol]putData:@"infoDeviceModel" data:nil];
break;
case SETTINGS_CONTROLLER__EEPROM_READ_TYPE:
[[self protocol]putData:@"infoDeviceType" data:nil];
break;
case SETTINGS_CONTROLLER__EEPROM_READ_OS:
[[self protocol]putData:@"infoDeviceOs" data:nil];
break;
case SETTINGS_CONTROLLER__EEPROM_READ_PIN:
[[self protocol]putData:@"infoDevicePin" data:nil];
break;
case SETTINGS_CONTROLLER__EEPROM_READ_MODE_DONE:
bleCommandState = SETTINGS_CONTROLLER__EEPROM_READ_ID;
[self bleCommandTask];
break;
case SETTINGS_CONTROLLER__EEPROM_READ_ID_DONE:
bleCommandState = SETTINGS_CONTROLLER__EEPROM_READ_MODEL;
[self bleCommandTask];
break;
case SETTINGS_CONTROLLER__EEPROM_READ_MODEL_DONE:
bleCommandState = SETTINGS_CONTROLLER__EEPROM_READ_TYPE;
[self bleCommandTask];
break;
case SETTINGS_CONTROLLER__EEPROM_READ_TYPE_DONE:
bleCommandState = SETTINGS_CONTROLLER__EEPROM_READ_OS;
[self bleCommandTask];
break;
case SETTINGS_CONTROLLER__EEPROM_READ_OS_DONE:
bleCommandState = SETTINGS_CONTROLLER__EEPROM_READ_PIN;
[self bleCommandTask];
break;
case SETTINGS_CONTROLLER__EEPROM_READ_PIN_DONE:
bleCommandState = SETTINGS_CONTROLLER__DONE;
[self bleCommandTask];
break;
case SETTINGS_CONTROLLER__DONE:
{
NSLog(@"Ble command set done!");
break;
}
}
return false;
}
- (void)protocolDidGetData:(NSString *)dataType data:(NSString *)dataData {
NSString *dataTypeFixed;
if([dataType hasPrefix:@"read"]) {
dataTypeFixed = [NSString stringWithFormat:@"%@%@",[[dataType substringWithRange:NSMakeRange(4, 1)] lowercaseString], [dataType substringFromIndex:5]];
//NSLog(@"[SettingsController] read dataTypeFixed: %@", dataTypeFixed);
if([dataData isEqualToString:@""]) {
dataData = @"なし";
}
if([dataTypeFixed isEqualToString:@"motor"]) {
_currentMotor.text = dataData;
}
//NSLog(@"[SettingsController] read dataData: %@", dataData);
} else if([dataType hasPrefix:@"write"]) {
dataTypeFixed = [NSString stringWithFormat:@"%@%@",[[dataType substringWithRange:NSMakeRange(5, 1)] lowercaseString], [dataType substringFromIndex:6]];
//NSLog(@"[SettingsController] write dataTypeFixed: %@", dataTypeFixed);
//NSLog(@"[SettingsController] write dataData: %@", dataData);
if([dataTypeFixed isEqual:@"walking"]) {
if(ignoreWriteWalkResponse) return;
[_writeWalkResponseTimer invalidate];
if([dataData isEqual:@"OK"]) {
[self showAlert:@"ジャケットの設定" message:@"設定が保存されました。"];
} else {
[self showAlert:@"ジャケットの設定" message:@"設定が保存されない。"];
}
}
} else if([dataType isEqualToString:@"eepromWriteProtect"]) {
[[self protocol]putData:@"systemResetInBootloader" data:nil];
} else if([dataType isEqualToString:@"infoDeviceMode"]) {
NSLog(@"infoDeviceMode");
lblDeviceMode.text = dataData;
bleCommandState = SETTINGS_CONTROLLER__EEPROM_READ_MODE_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"infoDeviceId"]) {
NSLog(@"infoDeviceId");
lblDeviceId.text = dataData;
bleCommandState = SETTINGS_CONTROLLER__EEPROM_READ_ID_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"infoDeviceModel"]) {
NSLog(@"infoDeviceModel");
lblDeviceModel.text = dataData;
bleCommandState = SETTINGS_CONTROLLER__EEPROM_READ_MODEL_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"infoDeviceType"]) {
NSLog(@"infoDeviceType");
lblDeviceType.text = dataData;
bleCommandState = SETTINGS_CONTROLLER__EEPROM_READ_TYPE_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"infoDeviceOs"]) {
NSLog(@"infoDeviceOs");
lblDeviceOs.text = dataData;
if([dataData hasPrefix:@"B"]) {
lblDeviceMode.text = @"UPDATE";
} else {
lblDeviceMode.text = @"APPLICATION";
}
bleCommandState = SETTINGS_CONTROLLER__EEPROM_READ_OS_DONE;
[self bleCommandTask];
} else if([dataType isEqualToString:@"infoDevicePin"]) {
NSLog(@"infoDevicePin");
lblDevicePin.text = dataData;
bleCommandState = SETTINGS_CONTROLLER__EEPROM_READ_PIN_DONE;
[self bleCommandTask];
}
}
@end
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="13196" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES">
<device id="retina4_0" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13173"/>
<capability name="Alignment constraints to the first baseline" minToolsVersion="6.0"/>
<capability name="Constraints to layout margins" minToolsVersion="6.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="SettingsController">
<connections>
<outlet property="lblDeviceId" destination="R0e-ju-3rJ" id="Eb4-9O-Agt"/>
<outlet property="lblDeviceMode" destination="7Md-pz-rS9" id="0KH-nO-VgJ"/>
<outlet property="lblDeviceModel" destination="FQe-8d-toS" id="ebO-2N-5hW"/>
<outlet property="lblDeviceOs" destination="wTV-GF-cUt" id="KYf-7B-NrH"/>
<outlet property="lblDevicePin" destination="xoE-0o-rQI" id="l2r-ul-pci"/>
<outlet property="lblDeviceType" destination="edw-Vo-Bc5" id="GJa-h4-p8m"/>
<outlet property="scrollView" destination="Gq0-Ni-ZRy" id="WzG-xH-2dU"/>
<outlet property="view" destination="i5M-Pr-FkT" id="dA6-dK-EZ0"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT">
<rect key="frame" x="0.0" y="0.0" width="320" height="783"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<scrollView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" ambiguous="YES" showsHorizontalScrollIndicator="NO" showsVerticalScrollIndicator="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Gq0-Ni-ZRy">
<rect key="frame" x="0.0" y="0.0" width="320" height="783"/>
<subviews>
<view contentMode="scaleToFill" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="cfc-hT-fKj" customClass="DemoView" customModule="jacket_test_ios" customModuleProvider="target">
<rect key="frame" x="0.0" y="0.0" width="320" height="775"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
</view>
</subviews>
</scrollView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstAttribute="bottom" secondItem="Gq0-Ni-ZRy" secondAttribute="bottom" id="3Lo-bZ-bNw"/>
<constraint firstItem="Gq0-Ni-ZRy" firstAttribute="leading" secondItem="i5M-Pr-FkT" secondAttribute="leading" id="Ay0-Jm-RMi"/>
<constraint firstAttribute="trailing" secondItem="Gq0-Ni-ZRy" secondAttribute="trailing" id="vvl-Sz-2e2"/>
<constraint firstItem="Gq0-Ni-ZRy" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" id="y1K-nD-sXF"/>
</constraints>
<freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
<point key="canvasLocation" x="-112" y="2427.5"/>
</view>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="uMf-cM-5yr" userLabel="Content">
<rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
<subviews>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="eIE-UX-Coo" userLabel="BootUpdate">
<rect key="frame" x="0.0" y="0.0" width="320" height="180"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="基板の情報" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="B0g-wP-AkO">
<rect key="frame" x="0.0" y="0.0" width="320" height="34"/>
<color key="backgroundColor" cocoaTouchSystemColor="groupTableViewBackgroundColor"/>
<constraints>
<constraint firstAttribute="height" constant="34" id="JkZ-zf-mDP"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="ID" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Eh3-6e-3UV">
<rect key="frame" x="8" y="62" width="69" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="69" id="Mjr-RX-kkM"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="モード" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="fvS-r5-fcl">
<rect key="frame" x="8" y="38" width="69" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="69" id="XZQ-7I-ohk"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Z60-Ov-osn">
<rect key="frame" x="118" y="42" width="142" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="142" id="nBq-pg-NGj"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="MODEL" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="OfR-lz-RdI">
<rect key="frame" x="8" y="85" width="69" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="69" id="jNU-gH-Hmy"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="TYPE" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="ciF-HT-7im">
<rect key="frame" x="8" y="109" width="69" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="69" id="rI7-Bd-FLA"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="OS" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Ulk-TS-1YW">
<rect key="frame" x="8" y="130" width="69" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="69" id="uaF-7h-MDM"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="PIN" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="eW2-wE-Y8r" userLabel="Lbl Device Pin">
<rect key="frame" x="8" y="151" width="27" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="取得中" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="R0e-ju-3rJ">
<rect key="frame" x="75" y="66" width="236" height="17"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="取得中" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="FQe-8d-toS">
<rect key="frame" x="75" y="85" width="236" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="取得中" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="edw-Vo-Bc5">
<rect key="frame" x="75" y="108" width="236" height="21"/>
<constraints>
<constraint firstAttribute="height" constant="21" id="Zur-HE-k73"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="取得中" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="wTV-GF-cUt">
<rect key="frame" x="75" y="131" width="236" height="17"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="取得中" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="7Md-pz-rS9">
<rect key="frame" x="269" y="38" width="43" height="17"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="取得中" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="xoE-0o-rQI" userLabel="Lbl Device Pin">
<rect key="frame" x="268" y="151" width="43" height="17"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="edw-Vo-Bc5" firstAttribute="top" secondItem="FQe-8d-toS" secondAttribute="bottom" constant="2" id="0sm-wS-Cfx"/>
<constraint firstItem="eW2-wE-Y8r" firstAttribute="top" secondItem="Ulk-TS-1YW" secondAttribute="bottom" id="4Pl-XC-ENT"/>
<constraint firstAttribute="trailing" secondItem="B0g-wP-AkO" secondAttribute="trailing" id="5dD-IQ-w6L"/>
<constraint firstItem="R0e-ju-3rJ" firstAttribute="trailing" secondItem="FQe-8d-toS" secondAttribute="trailing" id="6T2-Rw-zVC"/>
<constraint firstItem="Z60-Ov-osn" firstAttribute="leading" secondItem="Eh3-6e-3UV" secondAttribute="trailing" constant="41" id="6t6-in-NnI"/>
<constraint firstItem="Z60-Ov-osn" firstAttribute="baseline" secondItem="Eh3-6e-3UV" secondAttribute="baseline" constant="-20" id="8XO-4P-5Gh"/>
<constraint firstItem="OfR-lz-RdI" firstAttribute="leading" secondItem="Ulk-TS-1YW" secondAttribute="leading" id="8z3-5W-41D"/>
<constraint firstAttribute="trailing" secondItem="xoE-0o-rQI" secondAttribute="trailing" constant="9" id="AFL-eS-ZnM"/>
<constraint firstItem="7Md-pz-rS9" firstAttribute="top" secondItem="B0g-wP-AkO" secondAttribute="bottom" constant="4" id="FkS-OY-9AO"/>
<constraint firstItem="R0e-ju-3rJ" firstAttribute="leading" secondItem="FQe-8d-toS" secondAttribute="leading" id="JGf-RB-Gkl"/>
<constraint firstItem="R0e-ju-3rJ" firstAttribute="leading" secondItem="eIE-UX-Coo" secondAttribute="leading" constant="75" id="LBg-Qb-exN"/>
<constraint firstItem="ciF-HT-7im" firstAttribute="top" secondItem="OfR-lz-RdI" secondAttribute="bottom" constant="3" id="OTz-Xb-8RD"/>
<constraint firstItem="Eh3-6e-3UV" firstAttribute="leading" secondItem="eIE-UX-Coo" secondAttribute="leading" constant="8" id="PPS-1m-wpu"/>
<constraint firstItem="R0e-ju-3rJ" firstAttribute="trailing" secondItem="eIE-UX-Coo" secondAttribute="trailingMargin" constant="-1" id="Q0C-E0-vsI"/>
<constraint firstItem="R0e-ju-3rJ" firstAttribute="leading" secondItem="edw-Vo-Bc5" secondAttribute="leading" id="TcD-PW-YNW"/>
<constraint firstAttribute="trailing" secondItem="R0e-ju-3rJ" secondAttribute="trailing" constant="9" id="U78-7L-mib"/>
<constraint firstItem="fvS-r5-fcl" firstAttribute="leading" secondItem="eIE-UX-Coo" secondAttribute="leading" constant="8" id="Usz-9a-iEF"/>
<constraint firstItem="wTV-GF-cUt" firstAttribute="top" secondItem="edw-Vo-Bc5" secondAttribute="bottom" constant="2" id="V2z-ol-bKf"/>
<constraint firstItem="eW2-wE-Y8r" firstAttribute="leading" secondItem="eIE-UX-Coo" secondAttribute="leading" constant="8" id="Vf6-Ek-S4h"/>
<constraint firstItem="xoE-0o-rQI" firstAttribute="top" secondItem="wTV-GF-cUt" secondAttribute="bottom" constant="3" id="bHE-HM-JA3"/>
<constraint firstItem="xoE-0o-rQI" firstAttribute="top" secondItem="wTV-GF-cUt" secondAttribute="bottom" constant="3" id="bzm-rp-NAz"/>
<constraint firstItem="OfR-lz-RdI" firstAttribute="leading" secondItem="Eh3-6e-3UV" secondAttribute="leading" id="c7l-L8-Jsi"/>
<constraint firstItem="fvS-r5-fcl" firstAttribute="top" secondItem="B0g-wP-AkO" secondAttribute="bottom" constant="4" id="dCu-tP-7RX"/>
<constraint firstItem="edw-Vo-Bc5" firstAttribute="baseline" secondItem="ciF-HT-7im" secondAttribute="baseline" id="emT-q3-zXA"/>
<constraint firstItem="Eh3-6e-3UV" firstAttribute="leading" secondItem="eIE-UX-Coo" secondAttribute="leading" constant="8" id="fen-9e-2Km"/>
<constraint firstItem="Z60-Ov-osn" firstAttribute="firstBaseline" secondItem="Eh3-6e-3UV" secondAttribute="baseline" constant="-20" id="gAS-O9-Yht"/>
<constraint firstItem="B0g-wP-AkO" firstAttribute="top" secondItem="eIE-UX-Coo" secondAttribute="top" id="hP1-Bd-CeX"/>
<constraint firstItem="Ulk-TS-1YW" firstAttribute="top" secondItem="ciF-HT-7im" secondAttribute="bottom" id="kSk-bE-Iln"/>
<constraint firstItem="R0e-ju-3rJ" firstAttribute="top" secondItem="Z60-Ov-osn" secondAttribute="bottom" constant="3" id="kZp-Iu-YU9"/>
<constraint firstItem="R0e-ju-3rJ" firstAttribute="trailing" secondItem="edw-Vo-Bc5" secondAttribute="trailing" id="me4-d1-SVv"/>
<constraint firstItem="Eh3-6e-3UV" firstAttribute="top" secondItem="fvS-r5-fcl" secondAttribute="bottom" constant="3" id="n7d-JU-q0a"/>
<constraint firstItem="B0g-wP-AkO" firstAttribute="leading" secondItem="eIE-UX-Coo" secondAttribute="leading" id="qDe-NH-yu6"/>
<constraint firstItem="wTV-GF-cUt" firstAttribute="leading" secondItem="edw-Vo-Bc5" secondAttribute="leading" id="r9h-pD-CBi"/>
<constraint firstItem="OfR-lz-RdI" firstAttribute="top" secondItem="Z60-Ov-osn" secondAttribute="bottom" constant="22" id="rhw-YN-J64"/>
<constraint firstItem="wTV-GF-cUt" firstAttribute="trailing" secondItem="edw-Vo-Bc5" secondAttribute="trailing" id="tEP-2z-MME"/>
<constraint firstItem="FQe-8d-toS" firstAttribute="top" secondItem="Z60-Ov-osn" secondAttribute="bottom" constant="22" id="vYd-SU-RCn"/>
<constraint firstItem="Z60-Ov-osn" firstAttribute="bottom" secondItem="R0e-ju-3rJ" secondAttribute="bottom" constant="-20" id="vpj-Rc-MBy"/>
<constraint firstAttribute="trailing" secondItem="7Md-pz-rS9" secondAttribute="trailing" constant="8" id="wn6-7R-Gny"/>
<constraint firstItem="OfR-lz-RdI" firstAttribute="leading" secondItem="ciF-HT-7im" secondAttribute="leading" id="yPd-vT-beo"/>
<constraint firstAttribute="height" constant="180" id="znJ-5h-UIP"/>
</constraints>
</view>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="EK1-iD-A0q" userLabel="BootUpdate">
<rect key="frame" x="0.0" y="180" width="320" height="75"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="起動設定" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="JUj-0Q-xHq">
<rect key="frame" x="0.0" y="0.0" width="320" height="34"/>
<color key="backgroundColor" cocoaTouchSystemColor="groupTableViewBackgroundColor"/>
<constraints>
<constraint firstAttribute="height" constant="34" id="Olc-OO-SXW"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="起動設定" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="FeW-R8-ZLg">
<rect key="frame" x="8" y="42" width="265" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="265" id="kDe-OM-fwD"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="Wet-HF-Lge">
<rect key="frame" x="281" y="37" width="31" height="30"/>
<state key="normal" title="変更"/>
<connections>
<action selector="bootUpdateClicked:" destination="-1" eventType="touchUpInside" id="0Jc-tk-ZAm"/>
</connections>
</button>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="BYM-dX-nl5">
<rect key="frame" x="118" y="42" width="142" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="142" id="pFH-bf-nRV"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstAttribute="height" constant="75" id="54h-aI-Z7C"/>
<constraint firstItem="Wet-HF-Lge" firstAttribute="top" secondItem="JUj-0Q-xHq" secondAttribute="bottom" constant="3" id="6JT-RP-DCy"/>
<constraint firstItem="BYM-dX-nl5" firstAttribute="baseline" secondItem="FeW-R8-ZLg" secondAttribute="baseline" id="JOg-UI-yVM"/>
<constraint firstItem="FeW-R8-ZLg" firstAttribute="leading" secondItem="EK1-iD-A0q" secondAttribute="leading" constant="8" id="UK3-X2-P5Y"/>
<constraint firstAttribute="trailing" secondItem="JUj-0Q-xHq" secondAttribute="trailing" id="Z64-1m-uea"/>
<constraint firstItem="JUj-0Q-xHq" firstAttribute="leading" secondItem="EK1-iD-A0q" secondAttribute="leading" id="cZj-EX-Gfm"/>
<constraint firstItem="BYM-dX-nl5" firstAttribute="firstBaseline" secondItem="FeW-R8-ZLg" secondAttribute="baseline" id="hU3-6d-dJQ"/>
<constraint firstAttribute="trailing" secondItem="Wet-HF-Lge" secondAttribute="trailing" constant="8" id="qbG-VA-kWF"/>
<constraint firstItem="FeW-R8-ZLg" firstAttribute="top" secondItem="JUj-0Q-xHq" secondAttribute="bottom" constant="8" id="vWo-l9-9jD"/>
<constraint firstItem="Wet-HF-Lge" firstAttribute="leading" secondItem="BYM-dX-nl5" secondAttribute="trailing" constant="21" id="yDV-sa-sEI"/>
<constraint firstItem="JUj-0Q-xHq" firstAttribute="top" secondItem="EK1-iD-A0q" secondAttribute="top" id="yWX-7x-O3R"/>
</constraints>
</view>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="bZ6-5Z-llY" userLabel="Reset">
<rect key="frame" x="0.0" y="255" width="320" height="75"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="再起動" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="aoh-8d-4Hm">
<rect key="frame" x="0.0" y="0.0" width="320" height="34"/>
<color key="backgroundColor" cocoaTouchSystemColor="groupTableViewBackgroundColor"/>
<constraints>
<constraint firstAttribute="height" constant="34" id="5LF-W6-3RE"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="再起動" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="KP3-TN-BE4">
<rect key="frame" x="8" y="42" width="265" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="265" id="BaW-il-ETI"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="a9m-cI-xwT">
<rect key="frame" x="266" y="37" width="46" height="30"/>
<state key="normal" title="再起動"/>
<connections>
<action selector="resetClicked:" destination="-1" eventType="touchUpInside" id="219-ka-ROT"/>
</connections>
</button>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="EV7-GY-Xat">
<rect key="frame" x="103" y="42" width="142" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="142" id="NlF-QB-ifc"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="aoh-8d-4Hm" firstAttribute="leading" secondItem="bZ6-5Z-llY" secondAttribute="leading" id="3i4-jh-uBp"/>
<constraint firstAttribute="trailing" secondItem="aoh-8d-4Hm" secondAttribute="trailing" id="5kX-wX-BtU"/>
<constraint firstItem="a9m-cI-xwT" firstAttribute="top" secondItem="aoh-8d-4Hm" secondAttribute="bottom" constant="3" id="8Dt-UA-FxO"/>
<constraint firstItem="KP3-TN-BE4" firstAttribute="top" secondItem="aoh-8d-4Hm" secondAttribute="bottom" constant="8" id="AoI-Mp-wE1"/>
<constraint firstItem="EV7-GY-Xat" firstAttribute="baseline" secondItem="KP3-TN-BE4" secondAttribute="baseline" id="Qdx-Ec-9MF"/>
<constraint firstAttribute="height" constant="75" id="UZ8-qw-cam"/>
<constraint firstItem="EV7-GY-Xat" firstAttribute="firstBaseline" secondItem="KP3-TN-BE4" secondAttribute="baseline" id="WRh-Xu-687"/>
<constraint firstItem="aoh-8d-4Hm" firstAttribute="top" secondItem="bZ6-5Z-llY" secondAttribute="top" id="WcY-bv-6L2"/>
<constraint firstItem="KP3-TN-BE4" firstAttribute="leading" secondItem="bZ6-5Z-llY" secondAttribute="leading" constant="8" id="jcx-be-l7d"/>
<constraint firstItem="a9m-cI-xwT" firstAttribute="leading" secondItem="EV7-GY-Xat" secondAttribute="trailing" constant="21" id="ku9-58-nU2"/>
<constraint firstAttribute="trailing" secondItem="a9m-cI-xwT" secondAttribute="trailing" constant="8" id="sjl-Hd-7Op"/>
</constraints>
</view>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="m7Q-v9-hms" userLabel="BootloaderReset">
<rect key="frame" x="0.0" y="330" width="320" height="75"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="更新モード設定して再起動" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="RE2-pA-egH">
<rect key="frame" x="0.0" y="0.0" width="320" height="34"/>
<color key="backgroundColor" cocoaTouchSystemColor="groupTableViewBackgroundColor"/>
<constraints>
<constraint firstAttribute="height" constant="34" id="mA3-g9-KLy"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="更新モード設定して再起動" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="aRd-mf-2Ol">
<rect key="frame" x="8" y="42" width="265" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="265" id="Ftu-cf-gZ7"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="ygi-T6-jss">
<rect key="frame" x="266" y="37" width="46" height="30"/>
<state key="normal" title="再起動"/>
<connections>
<action selector="updateModeResetClicked:" destination="-1" eventType="touchUpInside" id="uW0-3Q-4q1"/>
</connections>
</button>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Jok-le-R5B">
<rect key="frame" x="103" y="42" width="142" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="142" id="dH4-At-cGO"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="RE2-pA-egH" firstAttribute="top" secondItem="m7Q-v9-hms" secondAttribute="top" id="2G8-F2-d5j"/>
<constraint firstItem="aRd-mf-2Ol" firstAttribute="top" secondItem="RE2-pA-egH" secondAttribute="bottom" constant="8" id="95a-gB-O3O"/>
<constraint firstAttribute="height" constant="75" id="FhP-RM-laU"/>
<constraint firstItem="Jok-le-R5B" firstAttribute="firstBaseline" secondItem="aRd-mf-2Ol" secondAttribute="baseline" id="P1g-2x-2FY"/>
<constraint firstItem="Jok-le-R5B" firstAttribute="baseline" secondItem="aRd-mf-2Ol" secondAttribute="baseline" id="PjK-gb-5Ue"/>
<constraint firstAttribute="trailing" secondItem="ygi-T6-jss" secondAttribute="trailing" constant="8" id="QHZ-9k-ogr"/>
<constraint firstItem="ygi-T6-jss" firstAttribute="top" secondItem="RE2-pA-egH" secondAttribute="bottom" constant="3" id="eN5-Ub-frP"/>
<constraint firstItem="ygi-T6-jss" firstAttribute="leading" secondItem="Jok-le-R5B" secondAttribute="trailing" constant="21" id="iqJ-SU-eC2"/>
<constraint firstItem="RE2-pA-egH" firstAttribute="leading" secondItem="m7Q-v9-hms" secondAttribute="leading" id="qrF-eN-6u1"/>
<constraint firstAttribute="trailing" secondItem="RE2-pA-egH" secondAttribute="trailing" id="vPV-i2-D7j"/>
<constraint firstItem="aRd-mf-2Ol" firstAttribute="leading" secondItem="m7Q-v9-hms" secondAttribute="leading" constant="8" id="zad-OF-EaU"/>
</constraints>
</view>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="a3E-ut-IxQ" userLabel="FirmwareDownload">
<rect key="frame" x="0.0" y="405" width="320" height="75"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="ファームウェア取得" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="1ra-xe-iFB">
<rect key="frame" x="0.0" y="1" width="320" height="34"/>
<color key="backgroundColor" cocoaTouchSystemColor="groupTableViewBackgroundColor"/>
<constraints>
<constraint firstAttribute="height" constant="34" id="I4p-Q6-vPi"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="ファームウェア取得" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="vuJ-ex-WUe">
<rect key="frame" x="8" y="43" width="265" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="265" id="imp-EA-ELf"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="JZU-KM-0dc">
<rect key="frame" x="118" y="43" width="142" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="142" id="s0p-Sy-t7Z"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="right" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="rpM-I0-KKH">
<rect key="frame" x="281" y="38" width="31" height="30"/>
<state key="normal" title="取得"/>
<connections>
<action selector="firmwareDownloadClicked:" destination="-1" eventType="touchUpInside" id="IqB-mb-0Bj"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstAttribute="bottom" secondItem="rpM-I0-KKH" secondAttribute="bottom" constant="7" id="5Um-38-42k"/>
<constraint firstAttribute="trailing" secondItem="1ra-xe-iFB" secondAttribute="trailing" id="Dbo-LH-DFT"/>
<constraint firstAttribute="trailing" secondItem="rpM-I0-KKH" secondAttribute="trailing" constant="8" id="EAU-GK-PqN"/>
<constraint firstItem="1ra-xe-iFB" firstAttribute="leading" secondItem="a3E-ut-IxQ" secondAttribute="leading" id="Ogz-A5-raj"/>
<constraint firstItem="rpM-I0-KKH" firstAttribute="leading" secondItem="JZU-KM-0dc" secondAttribute="trailing" constant="21" id="eUG-X4-h3I"/>
<constraint firstItem="vuJ-ex-WUe" firstAttribute="top" secondItem="1ra-xe-iFB" secondAttribute="bottom" constant="8" id="kob-Hh-Y5b"/>
<constraint firstAttribute="height" constant="75" id="ksV-8F-g36"/>
<constraint firstItem="JZU-KM-0dc" firstAttribute="firstBaseline" secondItem="vuJ-ex-WUe" secondAttribute="baseline" id="ouR-4p-6Vu"/>
<constraint firstItem="rpM-I0-KKH" firstAttribute="centerY" secondItem="JZU-KM-0dc" secondAttribute="centerY" id="r5u-TZ-Re7"/>
<constraint firstItem="JZU-KM-0dc" firstAttribute="baseline" secondItem="vuJ-ex-WUe" secondAttribute="baseline" id="wtJ-jE-Ha8"/>
<constraint firstItem="vuJ-ex-WUe" firstAttribute="leading" secondItem="a3E-ut-IxQ" secondAttribute="leading" constant="8" id="ynI-Eo-7Y0"/>
</constraints>
</view>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="LIJ-gW-1dP" userLabel="FirmwareUpdate">
<rect key="frame" x="0.0" y="480" width="320" height="75"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="ファームウェア書込" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="p1j-9l-PQF">
<rect key="frame" x="0.0" y="1" width="320" height="34"/>
<color key="backgroundColor" cocoaTouchSystemColor="groupTableViewBackgroundColor"/>
<constraints>
<constraint firstAttribute="height" constant="34" id="Z05-yb-XYI"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="ファームウェア書込" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Mhd-pD-81B">
<rect key="frame" x="8" y="43" width="265" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="265" id="MQV-xs-vFB"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Vcs-sE-ZYp">
<rect key="frame" x="118" y="43" width="142" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="142" id="cgn-De-giJ"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="right" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="XEG-Eo-a4N">
<rect key="frame" x="281" y="38" width="31" height="30"/>
<state key="normal" title="書込"/>
<connections>
<action selector="firmwareUpdateClicked:" destination="-1" eventType="touchUpInside" id="S36-5x-G2y"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstAttribute="trailing" secondItem="XEG-Eo-a4N" secondAttribute="trailing" constant="8" id="63U-E0-9Bo"/>
<constraint firstItem="p1j-9l-PQF" firstAttribute="leading" secondItem="LIJ-gW-1dP" secondAttribute="leading" id="Lrb-Nr-YLq"/>
<constraint firstItem="Vcs-sE-ZYp" firstAttribute="firstBaseline" secondItem="Mhd-pD-81B" secondAttribute="baseline" id="UgP-c3-uDZ"/>
<constraint firstAttribute="bottom" secondItem="XEG-Eo-a4N" secondAttribute="bottom" constant="7" id="aBm-fB-qcP"/>
<constraint firstItem="Vcs-sE-ZYp" firstAttribute="baseline" secondItem="Mhd-pD-81B" secondAttribute="baseline" id="hPd-Ov-62R"/>
<constraint firstAttribute="height" constant="75" id="ian-h3-SoG"/>
<constraint firstItem="Mhd-pD-81B" firstAttribute="top" secondItem="p1j-9l-PQF" secondAttribute="bottom" constant="8" id="m4l-jb-sFs"/>
<constraint firstAttribute="trailing" secondItem="p1j-9l-PQF" secondAttribute="trailing" id="noU-qy-By3"/>
<constraint firstItem="XEG-Eo-a4N" firstAttribute="centerY" secondItem="Vcs-sE-ZYp" secondAttribute="centerY" id="pkS-Gh-Vye"/>
<constraint firstItem="Mhd-pD-81B" firstAttribute="leading" secondItem="LIJ-gW-1dP" secondAttribute="leading" constant="8" id="slX-9B-9u2"/>
<constraint firstItem="XEG-Eo-a4N" firstAttribute="leading" secondItem="Vcs-sE-ZYp" secondAttribute="trailing" constant="21" id="vlB-7y-R0M"/>
</constraints>
</view>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="bks-QW-Uu4" userLabel="EepromWrite">
<rect key="frame" x="0.0" y="555" width="320" height="75"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="EEPROMデータ更新" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="nwH-ab-Yjr">
<rect key="frame" x="0.0" y="1" width="320" height="34"/>
<color key="backgroundColor" cocoaTouchSystemColor="groupTableViewBackgroundColor"/>
<constraints>
<constraint firstAttribute="height" constant="34" id="Hx7-sv-mUy"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="EEPROMデータ更新" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="mMc-Wd-fEe">
<rect key="frame" x="8" y="43" width="265" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="265" id="bb4-jC-ce7"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="MD4-kn-fyo">
<rect key="frame" x="118" y="43" width="142" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="142" id="cgl-hU-Eov"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="right" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="dHq-3b-ofO">
<rect key="frame" x="281" y="38" width="31" height="30"/>
<state key="normal" title="変更"/>
<connections>
<action selector="eepromUpdateClicked:" destination="-1" eventType="touchUpInside" id="Q7x-Qp-WoP"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="dHq-3b-ofO" firstAttribute="centerY" secondItem="MD4-kn-fyo" secondAttribute="centerY" id="0Pf-Nj-gpn"/>
<constraint firstItem="nwH-ab-Yjr" firstAttribute="leading" secondItem="bks-QW-Uu4" secondAttribute="leading" id="I1v-Oc-1Lq"/>
<constraint firstAttribute="height" constant="75" id="Ief-OF-WTE"/>
<constraint firstAttribute="trailing" secondItem="nwH-ab-Yjr" secondAttribute="trailing" id="VTS-lT-vAy"/>
<constraint firstItem="dHq-3b-ofO" firstAttribute="leading" secondItem="MD4-kn-fyo" secondAttribute="trailing" constant="21" id="auM-hU-6D6"/>
<constraint firstAttribute="trailing" secondItem="dHq-3b-ofO" secondAttribute="trailing" constant="8" id="fIk-98-4vr"/>
<constraint firstItem="MD4-kn-fyo" firstAttribute="baseline" secondItem="mMc-Wd-fEe" secondAttribute="baseline" id="mhH-ON-yLC"/>
<constraint firstItem="mMc-Wd-fEe" firstAttribute="leading" secondItem="bks-QW-Uu4" secondAttribute="leading" constant="8" id="nZg-Es-OKc"/>
<constraint firstItem="MD4-kn-fyo" firstAttribute="firstBaseline" secondItem="mMc-Wd-fEe" secondAttribute="baseline" id="phN-VD-Dkl"/>
<constraint firstItem="mMc-Wd-fEe" firstAttribute="top" secondItem="nwH-ab-Yjr" secondAttribute="bottom" constant="8" id="x1L-Xq-4Vh"/>
<constraint firstAttribute="bottom" secondItem="dHq-3b-ofO" secondAttribute="bottom" constant="7" id="zvO-EU-8nY"/>
</constraints>
</view>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="zdW-Jd-NbE" userLabel="Motor">
<rect key="frame" x="0.0" y="630" width="320" height="75"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="モーター" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="j2Q-yU-L06">
<rect key="frame" x="0.0" y="1" width="320" height="34"/>
<color key="backgroundColor" cocoaTouchSystemColor="groupTableViewBackgroundColor"/>
<constraints>
<constraint firstAttribute="height" constant="34" id="gcr-hn-ziN"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="モーター" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="hCE-9A-2PM">
<rect key="frame" x="8" y="43" width="265" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="265" id="HuV-m2-3Xu"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="YT7-Nh-qYQ">
<rect key="frame" x="118" y="43" width="142" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="142" id="dOe-fy-Ux7"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="right" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="4SC-vA-ehC">
<rect key="frame" x="281" y="38" width="31" height="30"/>
<state key="normal" title="変更"/>
<connections>
<action selector="InputMotorClicked:" destination="-1" eventType="touchUpInside" id="wh2-Uv-UY0"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstAttribute="bottom" secondItem="4SC-vA-ehC" secondAttribute="bottom" constant="7" id="04P-RN-D5m"/>
<constraint firstItem="j2Q-yU-L06" firstAttribute="leading" secondItem="zdW-Jd-NbE" secondAttribute="leading" id="3Xv-QV-hgG"/>
<constraint firstItem="hCE-9A-2PM" firstAttribute="top" secondItem="j2Q-yU-L06" secondAttribute="bottom" constant="8" id="BDI-DS-WrK"/>
<constraint firstItem="YT7-Nh-qYQ" firstAttribute="baseline" secondItem="hCE-9A-2PM" secondAttribute="baseline" id="Bcx-oL-NGv"/>
<constraint firstAttribute="height" constant="75" id="LDC-QK-fUB"/>
<constraint firstItem="4SC-vA-ehC" firstAttribute="leading" secondItem="YT7-Nh-qYQ" secondAttribute="trailing" constant="21" id="RI3-rD-2OQ"/>
<constraint firstAttribute="trailing" secondItem="j2Q-yU-L06" secondAttribute="trailing" id="UwX-WW-zYM"/>
<constraint firstItem="YT7-Nh-qYQ" firstAttribute="firstBaseline" secondItem="hCE-9A-2PM" secondAttribute="baseline" id="hrG-SH-9Fw"/>
<constraint firstItem="4SC-vA-ehC" firstAttribute="centerY" secondItem="YT7-Nh-qYQ" secondAttribute="centerY" id="joW-nu-MMi"/>
<constraint firstAttribute="trailing" secondItem="4SC-vA-ehC" secondAttribute="trailing" constant="8" id="ndm-P5-t61"/>
<constraint firstItem="hCE-9A-2PM" firstAttribute="leading" secondItem="zdW-Jd-NbE" secondAttribute="leading" constant="8" id="x5o-BG-MEI"/>
</constraints>
</view>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="qtP-5j-EqG" userLabel="Sound">
<rect key="frame" x="0.0" y="705" width="320" height="75"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="サウンド" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Hb0-mJ-MpB">
<rect key="frame" x="0.0" y="1" width="320" height="34"/>
<color key="backgroundColor" cocoaTouchSystemColor="groupTableViewBackgroundColor"/>
<constraints>
<constraint firstAttribute="height" constant="34" id="KyR-of-NVe"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="サウンド" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="i7x-yH-7jw">
<rect key="frame" x="8" y="43" width="265" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="265" id="P85-8S-pXh"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Wb2-fb-a4B">
<rect key="frame" x="118" y="43" width="142" height="21"/>
<constraints>
<constraint firstAttribute="width" constant="142" id="A2X-Wy-a6P"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="right" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="bg3-Bd-fvo">
<rect key="frame" x="281" y="38" width="31" height="30"/>
<state key="normal" title="変更"/>
<connections>
<action selector="InputSoundClicked:" destination="-1" eventType="touchUpInside" id="vBM-jo-UKX"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="Wb2-fb-a4B" firstAttribute="firstBaseline" secondItem="i7x-yH-7jw" secondAttribute="baseline" id="1oo-ae-rhS"/>
<constraint firstAttribute="trailing" secondItem="bg3-Bd-fvo" secondAttribute="trailing" constant="8" id="6gw-Qe-zoC"/>
<constraint firstAttribute="height" constant="75" id="Aan-7k-u8h"/>
<constraint firstItem="Wb2-fb-a4B" firstAttribute="baseline" secondItem="i7x-yH-7jw" secondAttribute="baseline" id="Ibi-oo-0uU"/>
<constraint firstItem="bg3-Bd-fvo" firstAttribute="leading" secondItem="Wb2-fb-a4B" secondAttribute="trailing" constant="21" id="K1B-xx-asU"/>
<constraint firstItem="i7x-yH-7jw" firstAttribute="leading" secondItem="qtP-5j-EqG" secondAttribute="leading" constant="8" id="PiM-bp-DHF"/>
<constraint firstItem="Hb0-mJ-MpB" firstAttribute="leading" secondItem="qtP-5j-EqG" secondAttribute="leading" id="SYt-Tq-FaX"/>
<constraint firstAttribute="bottom" secondItem="bg3-Bd-fvo" secondAttribute="bottom" constant="7" id="bRJ-MP-vpO"/>
<constraint firstAttribute="trailing" secondItem="Hb0-mJ-MpB" secondAttribute="trailing" id="egv-cE-MA8"/>
<constraint firstItem="bg3-Bd-fvo" firstAttribute="centerY" secondItem="Wb2-fb-a4B" secondAttribute="centerY" id="s4y-EG-GLo"/>
<constraint firstItem="i7x-yH-7jw" firstAttribute="top" secondItem="Hb0-mJ-MpB" secondAttribute="bottom" constant="8" id="z90-rN-nsu"/>
</constraints>
</view>
</subviews>
<constraints>
<constraint firstItem="m7Q-v9-hms" firstAttribute="leading" secondItem="bZ6-5Z-llY" secondAttribute="leading" id="0C5-GP-1r9"/>
<constraint firstItem="zdW-Jd-NbE" firstAttribute="top" secondItem="bks-QW-Uu4" secondAttribute="bottom" id="0Sw-Gw-loS"/>
<constraint firstItem="EK1-iD-A0q" firstAttribute="top" secondItem="eIE-UX-Coo" secondAttribute="bottom" id="5IN-lS-ik5"/>
<constraint firstAttribute="trailing" secondItem="LIJ-gW-1dP" secondAttribute="trailing" id="60O-2b-ZdC"/>
<constraint firstItem="bZ6-5Z-llY" firstAttribute="trailing" secondItem="EK1-iD-A0q" secondAttribute="trailing" id="7HO-B6-6Or"/>
<constraint firstAttribute="height" constant="780" id="8c9-cl-D0b"/>
<constraint firstItem="a3E-ut-IxQ" firstAttribute="top" secondItem="m7Q-v9-hms" secondAttribute="bottom" id="9om-H3-469"/>
<constraint firstItem="qtP-5j-EqG" firstAttribute="leading" secondItem="zdW-Jd-NbE" secondAttribute="leading" id="Bf4-Yj-asS"/>
<constraint firstItem="zdW-Jd-NbE" firstAttribute="leading" secondItem="bks-QW-Uu4" secondAttribute="leading" id="ExU-yM-9Vb"/>
<constraint firstItem="qtP-5j-EqG" firstAttribute="trailing" secondItem="zdW-Jd-NbE" secondAttribute="trailing" id="FzY-aC-VYM"/>
<constraint firstItem="bZ6-5Z-llY" firstAttribute="top" secondItem="EK1-iD-A0q" secondAttribute="bottom" id="G3H-PW-uTb"/>
<constraint firstItem="bks-QW-Uu4" firstAttribute="trailing" secondItem="LIJ-gW-1dP" secondAttribute="trailing" id="G4e-9d-qvR"/>
<constraint firstItem="EK1-iD-A0q" firstAttribute="leading" secondItem="LIJ-gW-1dP" secondAttribute="leading" id="H7u-NR-BJO"/>
<constraint firstItem="LIJ-gW-1dP" firstAttribute="top" secondItem="a3E-ut-IxQ" secondAttribute="bottom" id="HNY-y6-piQ"/>
<constraint firstItem="eIE-UX-Coo" firstAttribute="trailing" secondItem="EK1-iD-A0q" secondAttribute="trailing" id="Ic5-mD-bYI"/>
<constraint firstItem="zdW-Jd-NbE" firstAttribute="trailing" secondItem="bks-QW-Uu4" secondAttribute="trailing" id="J3z-oH-cvq"/>
<constraint firstItem="bks-QW-Uu4" firstAttribute="leading" secondItem="LIJ-gW-1dP" secondAttribute="leading" id="MId-bN-m0y"/>
<constraint firstItem="eIE-UX-Coo" firstAttribute="top" secondItem="uMf-cM-5yr" secondAttribute="top" id="Wh6-3J-zbe"/>
<constraint firstItem="LIJ-gW-1dP" firstAttribute="leading" secondItem="uMf-cM-5yr" secondAttribute="leading" id="b4y-4b-BWL"/>
<constraint firstItem="qtP-5j-EqG" firstAttribute="top" secondItem="zdW-Jd-NbE" secondAttribute="bottom" id="fyK-F2-Jtx"/>
<constraint firstItem="a3E-ut-IxQ" firstAttribute="trailing" secondItem="bZ6-5Z-llY" secondAttribute="trailing" id="gou-vb-Vap"/>
<constraint firstItem="EK1-iD-A0q" firstAttribute="trailing" secondItem="LIJ-gW-1dP" secondAttribute="trailing" id="hf9-VU-4Zs"/>
<constraint firstItem="m7Q-v9-hms" firstAttribute="top" secondItem="bZ6-5Z-llY" secondAttribute="bottom" id="n5l-FV-o0j"/>
<constraint firstItem="a3E-ut-IxQ" firstAttribute="leading" secondItem="bZ6-5Z-llY" secondAttribute="leading" id="qbu-mP-GU7"/>
<constraint firstItem="bZ6-5Z-llY" firstAttribute="leading" secondItem="EK1-iD-A0q" secondAttribute="leading" id="vX5-pX-GB4"/>
<constraint firstItem="eIE-UX-Coo" firstAttribute="leading" secondItem="EK1-iD-A0q" secondAttribute="leading" id="w9S-vr-m4X"/>
<constraint firstItem="m7Q-v9-hms" firstAttribute="trailing" secondItem="bZ6-5Z-llY" secondAttribute="trailing" id="wyc-lV-7Wh"/>
<constraint firstItem="bks-QW-Uu4" firstAttribute="top" secondItem="LIJ-gW-1dP" secondAttribute="bottom" id="xir-Bz-6Ku"/>
</constraints>
<point key="canvasLocation" x="-470" y="2748"/>
</view>
</objects>
</document>
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
4466131E1E134FC000A56C82 /* SettingsController.m in Sources */ = {isa = PBXBuildFile; fileRef = 446613181E134FC000A56C82 /* SettingsController.m */; };
4466131F1E134FC000A56C82 /* SettingsController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 446613191E134FC000A56C82 /* SettingsController.xib */; };
CB34DA271E5E9C2200EBA2E4 /* InputMotorController.xib in Resources */ = {isa = PBXBuildFile; fileRef = CB34DA261E5E9C2200EBA2E4 /* InputMotorController.xib */; };
CB34DA2A1E5E9C4B00EBA2E4 /* InputMotorController.m in Sources */ = {isa = PBXBuildFile; fileRef = CB34DA291E5E9C4B00EBA2E4 /* InputMotorController.m */; };
CB53F4571F871AF300970458 /* InputSoundController.m in Sources */ = {isa = PBXBuildFile; fileRef = CB53F4551F871AF300970458 /* InputSoundController.m */; };
CB53F4581F871AF300970458 /* InputSoundController.xib in Resources */ = {isa = PBXBuildFile; fileRef = CB53F4561F871AF300970458 /* InputSoundController.xib */; };
CBE0DBC71F25804D00E765A4 /* EepromController.m in Sources */ = {isa = PBXBuildFile; fileRef = CBE0DBC51F25804D00E765A4 /* EepromController.m */; };
CBE0DBC81F25804D00E765A4 /* EepromController.xib in Resources */ = {isa = PBXBuildFile; fileRef = CBE0DBC61F25804D00E765A4 /* EepromController.xib */; };
CBE0DBCC1F258A4000E765A4 /* EepromTemplateController.m in Sources */ = {isa = PBXBuildFile; fileRef = CBE0DBCA1F258A4000E765A4 /* EepromTemplateController.m */; };
CBE0DBCD1F258A4000E765A4 /* EepromTemplateController.xib in Resources */ = {isa = PBXBuildFile; fileRef = CBE0DBCB1F258A4000E765A4 /* EepromTemplateController.xib */; };
CBE0DBD11F258A7400E765A4 /* EepromTemplateTableViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = CBE0DBCF1F258A7400E765A4 /* EepromTemplateTableViewCell.m */; };
CBE0DBD21F258A7400E765A4 /* EepromTemplateTableViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = CBE0DBD01F258A7400E765A4 /* EepromTemplateTableViewCell.xib */; };
CBE0DBD61F25DDE600E765A4 /* BootSettingController.m in Sources */ = {isa = PBXBuildFile; fileRef = CBE0DBD41F25DDE600E765A4 /* BootSettingController.m */; };
CBE0DBD71F25DDE600E765A4 /* BootSettingController.xib in Resources */ = {isa = PBXBuildFile; fileRef = CBE0DBD51F25DDE600E765A4 /* BootSettingController.xib */; };
CBE48CC51CD07F0A0089DAF2 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = CBE48CC41CD07F0A0089DAF2 /* main.m */; };
CBE48CC81CD07F0A0089DAF2 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = CBE48CC71CD07F0A0089DAF2 /* AppDelegate.m */; };
CBE48CCB1CD07F0A0089DAF2 /* BleSearchViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = CBE48CCA1CD07F0A0089DAF2 /* BleSearchViewController.m */; };
CBE48CCE1CD07F0A0089DAF2 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = CBE48CCC1CD07F0A0089DAF2 /* Main.storyboard */; };
CBE48CD01CD07F0A0089DAF2 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = CBE48CCF1CD07F0A0089DAF2 /* Assets.xcassets */; };
CBE48CD31CD07F0A0089DAF2 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = CBE48CD11CD07F0A0089DAF2 /* LaunchScreen.storyboard */; };
CBE48CDB1CD080120089DAF2 /* CoreBluetooth.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CBE48CDA1CD080120089DAF2 /* CoreBluetooth.framework */; };
CBE48CE11CD084740089DAF2 /* BLE.m in Sources */ = {isa = PBXBuildFile; fileRef = CBE48CDF1CD084740089DAF2 /* BLE.m */; };
CBE48CF81CD0B3C30089DAF2 /* BleProtocol.m in Sources */ = {isa = PBXBuildFile; fileRef = CBE48CF71CD0B3C30089DAF2 /* BleProtocol.m */; };
CBE48D001CD0B6AA0089DAF2 /* BleControl.m in Sources */ = {isa = PBXBuildFile; fileRef = CBE48CFF1CD0B6AA0089DAF2 /* BleControl.m */; };
CBE6440B1F30614800664E68 /* BleSearchResultTableViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = CBE644081F30614800664E68 /* BleSearchResultTableViewCell.m */; };
CBE6440C1F30614800664E68 /* BleSearchResultTableViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = CBE6440A1F30614800664E68 /* BleSearchResultTableViewController.m */; };
CBF4AEF41EE54D910029CE7D /* FirmwareUpdateController.xib in Resources */ = {isa = PBXBuildFile; fileRef = CBF4AEF31EE54D910029CE7D /* FirmwareUpdateController.xib */; };
CBF4AEF71EE54DE10029CE7D /* FirmwareUpdateController.m in Sources */ = {isa = PBXBuildFile; fileRef = CBF4AEF61EE54DE10029CE7D /* FirmwareUpdateController.m */; };
CBF4AF071EE55B620029CE7D /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = CBF4AEFB1EE55B620029CE7D /* AFHTTPSessionManager.m */; };
CBF4AF081EE55B620029CE7D /* AFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = CBF4AEFE1EE55B620029CE7D /* AFNetworkReachabilityManager.m */; };
CBF4AF091EE55B620029CE7D /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = CBF4AF001EE55B620029CE7D /* AFSecurityPolicy.m */; };
CBF4AF0A1EE55B620029CE7D /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = CBF4AF021EE55B620029CE7D /* AFURLRequestSerialization.m */; };
CBF4AF0B1EE55B620029CE7D /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = CBF4AF041EE55B620029CE7D /* AFURLResponseSerialization.m */; };
CBF4AF0C1EE55B620029CE7D /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = CBF4AF061EE55B620029CE7D /* AFURLSessionManager.m */; };
CBF4AF101EE637830029CE7D /* Operation.m in Sources */ = {isa = PBXBuildFile; fileRef = CBF4AF0F1EE637830029CE7D /* Operation.m */; };
CBF4AF161EE667B70029CE7D /* FirmwareDownloadController.m in Sources */ = {isa = PBXBuildFile; fileRef = CBF4AF141EE667B70029CE7D /* FirmwareDownloadController.m */; };
CBF4AF171EE667B70029CE7D /* FirmwareDownloadController.xib in Resources */ = {isa = PBXBuildFile; fileRef = CBF4AF151EE667B70029CE7D /* FirmwareDownloadController.xib */; };
CBF4AF1B1EE667CA0029CE7D /* FirmwareWriteController.m in Sources */ = {isa = PBXBuildFile; fileRef = CBF4AF191EE667CA0029CE7D /* FirmwareWriteController.m */; };
CBF4AF1C1EE667CA0029CE7D /* FirmwareWriteController.xib in Resources */ = {isa = PBXBuildFile; fileRef = CBF4AF1A1EE667CA0029CE7D /* FirmwareWriteController.xib */; };
CBF4AF251EE670650029CE7D /* FirmwareDownloadControllerTableViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = CBF4AF231EE670650029CE7D /* FirmwareDownloadControllerTableViewCell.m */; };
CBF4AF261EE670650029CE7D /* FirmwareDownloadControllerTableViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = CBF4AF241EE670650029CE7D /* FirmwareDownloadControllerTableViewCell.xib */; };
CBF4AF2B1EE6AD660029CE7D /* libsqlite3.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = CBF4AF2A1EE6AD660029CE7D /* libsqlite3.dylib */; };
CBF4AF391EE6F1F80029CE7D /* DBManager.m in Sources */ = {isa = PBXBuildFile; fileRef = CBF4AF381EE6F1F80029CE7D /* DBManager.m */; };
CBF4AF3D1EE7C8F00029CE7D /* FirmwareWriteControllerTableViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = CBF4AF3B1EE7C8F00029CE7D /* FirmwareWriteControllerTableViewCell.m */; };
CBF4AF3E1EE7C8F00029CE7D /* FirmwareWriteControllerTableViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = CBF4AF3C1EE7C8F00029CE7D /* FirmwareWriteControllerTableViewCell.xib */; };
CBF4AF411EE7EE290029CE7D /* NSData+NSString.m in Sources */ = {isa = PBXBuildFile; fileRef = CBF4AF401EE7EE290029CE7D /* NSData+NSString.m */; };
CE3077271F8E289100EB87FF /* DemoView.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE3077261F8E289100EB87FF /* DemoView.swift */; };
CE30772A1F8E2BD700EB87FF /* SenserData.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE3077291F8E2BD700EB87FF /* SenserData.swift */; };
CE30772D1F8E36BD00EB87FF /* UserNofitication.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE30772C1F8E36BD00EB87FF /* UserNofitication.swift */; };
CE30772F1F8E36E500EB87FF /* UNResponseManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE30772E1F8E36E500EB87FF /* UNResponseManager.swift */; };
CE3077311F8E37DA00EB87FF /* Caller.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE3077301F8E37DA00EB87FF /* Caller.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
446613171E134FC000A56C82 /* SettingsController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SettingsController.h; sourceTree = "<group>"; };
446613181E134FC000A56C82 /* SettingsController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SettingsController.m; sourceTree = "<group>"; };
446613191E134FC000A56C82 /* SettingsController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = SettingsController.xib; sourceTree = "<group>"; };
CB34DA261E5E9C2200EBA2E4 /* InputMotorController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = InputMotorController.xib; sourceTree = "<group>"; };
CB34DA281E5E9C4B00EBA2E4 /* InputMotorController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InputMotorController.h; sourceTree = "<group>"; };
CB34DA291E5E9C4B00EBA2E4 /* InputMotorController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = InputMotorController.m; sourceTree = "<group>"; };
CB53F4541F871AF300970458 /* InputSoundController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = InputSoundController.h; sourceTree = "<group>"; };
CB53F4551F871AF300970458 /* InputSoundController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = InputSoundController.m; sourceTree = "<group>"; };
CB53F4561F871AF300970458 /* InputSoundController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = InputSoundController.xib; sourceTree = "<group>"; };
CBE0DBC41F25804D00E765A4 /* EepromController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EepromController.h; sourceTree = "<group>"; };
CBE0DBC51F25804D00E765A4 /* EepromController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = EepromController.m; sourceTree = "<group>"; };
CBE0DBC61F25804D00E765A4 /* EepromController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = EepromController.xib; sourceTree = "<group>"; };
CBE0DBC91F258A4000E765A4 /* EepromTemplateController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EepromTemplateController.h; sourceTree = "<group>"; };
CBE0DBCA1F258A4000E765A4 /* EepromTemplateController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = EepromTemplateController.m; sourceTree = "<group>"; };
CBE0DBCB1F258A4000E765A4 /* EepromTemplateController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = EepromTemplateController.xib; sourceTree = "<group>"; };
CBE0DBCE1F258A7400E765A4 /* EepromTemplateTableViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EepromTemplateTableViewCell.h; sourceTree = "<group>"; };
CBE0DBCF1F258A7400E765A4 /* EepromTemplateTableViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = EepromTemplateTableViewCell.m; sourceTree = "<group>"; };
CBE0DBD01F258A7400E765A4 /* EepromTemplateTableViewCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = EepromTemplateTableViewCell.xib; sourceTree = "<group>"; };
CBE0DBD31F25DDE600E765A4 /* BootSettingController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BootSettingController.h; sourceTree = "<group>"; };
CBE0DBD41F25DDE600E765A4 /* BootSettingController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BootSettingController.m; sourceTree = "<group>"; };
CBE0DBD51F25DDE600E765A4 /* BootSettingController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = BootSettingController.xib; sourceTree = "<group>"; };
CBE48CC01CD07F0A0089DAF2 /* jacket_test_ios.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = jacket_test_ios.app; sourceTree = BUILT_PRODUCTS_DIR; };
CBE48CC41CD07F0A0089DAF2 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
CBE48CC61CD07F0A0089DAF2 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };
CBE48CC71CD07F0A0089DAF2 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = "<group>"; };
CBE48CC91CD07F0A0089DAF2 /* BleSearchViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = BleSearchViewController.h; sourceTree = "<group>"; };
CBE48CCA1CD07F0A0089DAF2 /* BleSearchViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = BleSearchViewController.m; sourceTree = "<group>"; };
CBE48CCD1CD07F0A0089DAF2 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
CBE48CCF1CD07F0A0089DAF2 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
CBE48CD21CD07F0A0089DAF2 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
CBE48CD41CD07F0A0089DAF2 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
CBE48CDA1CD080120089DAF2 /* CoreBluetooth.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreBluetooth.framework; path = System/Library/Frameworks/CoreBluetooth.framework; sourceTree = SDKROOT; };
CBE48CDE1CD084740089DAF2 /* BLE.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BLE.h; sourceTree = "<group>"; };
CBE48CDF1CD084740089DAF2 /* BLE.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BLE.m; sourceTree = "<group>"; };
CBE48CE01CD084740089DAF2 /* BLEDefines.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BLEDefines.h; sourceTree = "<group>"; };
CBE48CF71CD0B3C30089DAF2 /* BleProtocol.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BleProtocol.m; sourceTree = "<group>"; };
CBE48CF91CD0B3D50089DAF2 /* BleProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BleProtocol.h; sourceTree = "<group>"; };
CBE48CFE1CD0B6AA0089DAF2 /* BleControl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BleControl.h; sourceTree = "<group>"; };
CBE48CFF1CD0B6AA0089DAF2 /* BleControl.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BleControl.m; sourceTree = "<group>"; };
CBE644071F30614800664E68 /* BleSearchResultTableViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BleSearchResultTableViewCell.h; sourceTree = "<group>"; };
CBE644081F30614800664E68 /* BleSearchResultTableViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BleSearchResultTableViewCell.m; sourceTree = "<group>"; };
CBE644091F30614800664E68 /* BleSearchResultTableViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BleSearchResultTableViewController.h; sourceTree = "<group>"; };
CBE6440A1F30614800664E68 /* BleSearchResultTableViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = BleSearchResultTableViewController.m; sourceTree = "<group>"; };
CBF4AEF31EE54D910029CE7D /* FirmwareUpdateController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = FirmwareUpdateController.xib; sourceTree = "<group>"; };
CBF4AEF51EE54DE10029CE7D /* FirmwareUpdateController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FirmwareUpdateController.h; sourceTree = "<group>"; };
CBF4AEF61EE54DE10029CE7D /* FirmwareUpdateController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FirmwareUpdateController.m; sourceTree = "<group>"; };
CBF4AEFA1EE55B620029CE7D /* AFHTTPSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPSessionManager.h; sourceTree = "<group>"; };
CBF4AEFB1EE55B620029CE7D /* AFHTTPSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPSessionManager.m; sourceTree = "<group>"; };
CBF4AEFC1EE55B620029CE7D /* AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworking.h; sourceTree = "<group>"; };
CBF4AEFD1EE55B620029CE7D /* AFNetworkReachabilityManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkReachabilityManager.h; sourceTree = "<group>"; };
CBF4AEFE1EE55B620029CE7D /* AFNetworkReachabilityManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkReachabilityManager.m; sourceTree = "<group>"; };
CBF4AEFF1EE55B620029CE7D /* AFSecurityPolicy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFSecurityPolicy.h; sourceTree = "<group>"; };
CBF4AF001EE55B620029CE7D /* AFSecurityPolicy.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFSecurityPolicy.m; sourceTree = "<group>"; };
CBF4AF011EE55B620029CE7D /* AFURLRequestSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLRequestSerialization.h; sourceTree = "<group>"; };
CBF4AF021EE55B620029CE7D /* AFURLRequestSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLRequestSerialization.m; sourceTree = "<group>"; };
CBF4AF031EE55B620029CE7D /* AFURLResponseSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLResponseSerialization.h; sourceTree = "<group>"; };
CBF4AF041EE55B620029CE7D /* AFURLResponseSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLResponseSerialization.m; sourceTree = "<group>"; };
CBF4AF051EE55B620029CE7D /* AFURLSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLSessionManager.h; sourceTree = "<group>"; };
CBF4AF061EE55B620029CE7D /* AFURLSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLSessionManager.m; sourceTree = "<group>"; };
CBF4AF0E1EE637830029CE7D /* Operation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Operation.h; path = Operation/Operation.h; sourceTree = SOURCE_ROOT; };
CBF4AF0F1EE637830029CE7D /* Operation.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Operation.m; path = Operation/Operation.m; sourceTree = SOURCE_ROOT; };
CBF4AF121EE6389C0029CE7D /* jacket_test_ios_prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = jacket_test_ios_prefix.pch; sourceTree = SOURCE_ROOT; };
CBF4AF131EE667B70029CE7D /* FirmwareDownloadController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FirmwareDownloadController.h; sourceTree = "<group>"; };
CBF4AF141EE667B70029CE7D /* FirmwareDownloadController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FirmwareDownloadController.m; sourceTree = "<group>"; };
CBF4AF151EE667B70029CE7D /* FirmwareDownloadController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = FirmwareDownloadController.xib; sourceTree = "<group>"; };
CBF4AF181EE667CA0029CE7D /* FirmwareWriteController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FirmwareWriteController.h; sourceTree = "<group>"; };
CBF4AF191EE667CA0029CE7D /* FirmwareWriteController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FirmwareWriteController.m; sourceTree = "<group>"; };
CBF4AF1A1EE667CA0029CE7D /* FirmwareWriteController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = FirmwareWriteController.xib; sourceTree = "<group>"; };
CBF4AF221EE670650029CE7D /* FirmwareDownloadControllerTableViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FirmwareDownloadControllerTableViewCell.h; sourceTree = "<group>"; };
CBF4AF231EE670650029CE7D /* FirmwareDownloadControllerTableViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FirmwareDownloadControllerTableViewCell.m; sourceTree = "<group>"; };
CBF4AF241EE670650029CE7D /* FirmwareDownloadControllerTableViewCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = FirmwareDownloadControllerTableViewCell.xib; sourceTree = "<group>"; };
CBF4AF2A1EE6AD660029CE7D /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = ../../../../../../usr/lib/libsqlite3.dylib; sourceTree = "<group>"; };
CBF4AF371EE6F1C60029CE7D /* DBManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DBManager.h; sourceTree = SOURCE_ROOT; };
CBF4AF381EE6F1F80029CE7D /* DBManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = DBManager.m; sourceTree = SOURCE_ROOT; };
CBF4AF3A1EE7C8F00029CE7D /* FirmwareWriteControllerTableViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FirmwareWriteControllerTableViewCell.h; sourceTree = "<group>"; };
CBF4AF3B1EE7C8F00029CE7D /* FirmwareWriteControllerTableViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FirmwareWriteControllerTableViewCell.m; sourceTree = "<group>"; };
CBF4AF3C1EE7C8F00029CE7D /* FirmwareWriteControllerTableViewCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = FirmwareWriteControllerTableViewCell.xib; sourceTree = "<group>"; };
CBF4AF3F1EE7EE290029CE7D /* NSData+NSString.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSData+NSString.h"; sourceTree = "<group>"; };
CBF4AF401EE7EE290029CE7D /* NSData+NSString.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSData+NSString.m"; sourceTree = "<group>"; };
CE3077231F8E259000EB87FF /* jacket_test_ios-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "jacket_test_ios-Bridging-Header.h"; sourceTree = "<group>"; };
CE3077261F8E289100EB87FF /* DemoView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoView.swift; sourceTree = "<group>"; };
CE3077291F8E2BD700EB87FF /* SenserData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SenserData.swift; sourceTree = "<group>"; };
CE30772C1F8E36BD00EB87FF /* UserNofitication.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserNofitication.swift; sourceTree = "<group>"; };
CE30772E1F8E36E500EB87FF /* UNResponseManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UNResponseManager.swift; sourceTree = "<group>"; };
CE3077301F8E37DA00EB87FF /* Caller.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Caller.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
CBE48CBD1CD07F0A0089DAF2 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
CBF4AF2B1EE6AD660029CE7D /* libsqlite3.dylib in Frameworks */,
CBE48CDB1CD080120089DAF2 /* CoreBluetooth.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
446613201E134FD500A56C82 /* Settings */ = {
isa = PBXGroup;
children = (
446613171E134FC000A56C82 /* SettingsController.h */,
446613181E134FC000A56C82 /* SettingsController.m */,
446613191E134FC000A56C82 /* SettingsController.xib */,
CB34DA281E5E9C4B00EBA2E4 /* InputMotorController.h */,
CB34DA291E5E9C4B00EBA2E4 /* InputMotorController.m */,
CB34DA261E5E9C2200EBA2E4 /* InputMotorController.xib */,
CBF4AEF51EE54DE10029CE7D /* FirmwareUpdateController.h */,
CBF4AEF61EE54DE10029CE7D /* FirmwareUpdateController.m */,
CBF4AEF31EE54D910029CE7D /* FirmwareUpdateController.xib */,
CBF4AF131EE667B70029CE7D /* FirmwareDownloadController.h */,
CBF4AF141EE667B70029CE7D /* FirmwareDownloadController.m */,
CBF4AF151EE667B70029CE7D /* FirmwareDownloadController.xib */,
CBF4AF221EE670650029CE7D /* FirmwareDownloadControllerTableViewCell.h */,
CBF4AF231EE670650029CE7D /* FirmwareDownloadControllerTableViewCell.m */,
CBF4AF241EE670650029CE7D /* FirmwareDownloadControllerTableViewCell.xib */,
CBF4AF181EE667CA0029CE7D /* FirmwareWriteController.h */,
CBF4AF191EE667CA0029CE7D /* FirmwareWriteController.m */,
CBF4AF1A1EE667CA0029CE7D /* FirmwareWriteController.xib */,
CBF4AF3A1EE7C8F00029CE7D /* FirmwareWriteControllerTableViewCell.h */,
CBF4AF3B1EE7C8F00029CE7D /* FirmwareWriteControllerTableViewCell.m */,
CBF4AF3C1EE7C8F00029CE7D /* FirmwareWriteControllerTableViewCell.xib */,
CBE0DBC41F25804D00E765A4 /* EepromController.h */,
CBE0DBC51F25804D00E765A4 /* EepromController.m */,
CBE0DBC61F25804D00E765A4 /* EepromController.xib */,
CBE0DBC91F258A4000E765A4 /* EepromTemplateController.h */,
CBE0DBCA1F258A4000E765A4 /* EepromTemplateController.m */,
CBE0DBCB1F258A4000E765A4 /* EepromTemplateController.xib */,
CBE0DBCE1F258A7400E765A4 /* EepromTemplateTableViewCell.h */,
CBE0DBCF1F258A7400E765A4 /* EepromTemplateTableViewCell.m */,
CBE0DBD01F258A7400E765A4 /* EepromTemplateTableViewCell.xib */,
CBE0DBD31F25DDE600E765A4 /* BootSettingController.h */,
CBE0DBD41F25DDE600E765A4 /* BootSettingController.m */,
CBE0DBD51F25DDE600E765A4 /* BootSettingController.xib */,
CB53F4541F871AF300970458 /* InputSoundController.h */,
CB53F4551F871AF300970458 /* InputSoundController.m */,
CB53F4561F871AF300970458 /* InputSoundController.xib */,
CE3077261F8E289100EB87FF /* DemoView.swift */,
);
name = Settings;
path = ..;
sourceTree = "<group>";
};
CBE48CB71CD07F0A0089DAF2 = {
isa = PBXGroup;
children = (
CBE48CC21CD07F0A0089DAF2 /* jacket_test_ios */,
CBF4AF111EE638870029CE7D /* Other Sources */,
CBE48CDD1CD084740089DAF2 /* BLE */,
CBF4AEF81EE55AF20029CE7D /* 3rdParties */,
CBE48CDC1CD080280089DAF2 /* Frameworks */,
CBE48CC11CD07F0A0089DAF2 /* Products */,
);
sourceTree = "<group>";
};
CBE48CC11CD07F0A0089DAF2 /* Products */ = {
isa = PBXGroup;
children = (
CBE48CC01CD07F0A0089DAF2 /* jacket_test_ios.app */,
);
name = Products;
sourceTree = "<group>";
};
CBE48CC21CD07F0A0089DAF2 /* jacket_test_ios */ = {
isa = PBXGroup;
children = (
CE30772B1F8E369C00EB87FF /* util */,
CE3077281F8E2BBE00EB87FF /* model */,
CBF4AF0D1EE637430029CE7D /* Operation */,
446613201E134FD500A56C82 /* Settings */,
CBE48CC61CD07F0A0089DAF2 /* AppDelegate.h */,
CBE48CC71CD07F0A0089DAF2 /* AppDelegate.m */,
CBF4AF371EE6F1C60029CE7D /* DBManager.h */,
CBF4AF381EE6F1F80029CE7D /* DBManager.m */,
CBE48CC91CD07F0A0089DAF2 /* BleSearchViewController.h */,
CBE48CCA1CD07F0A0089DAF2 /* BleSearchViewController.m */,
CBE644091F30614800664E68 /* BleSearchResultTableViewController.h */,
CBE6440A1F30614800664E68 /* BleSearchResultTableViewController.m */,
CBE644071F30614800664E68 /* BleSearchResultTableViewCell.h */,
CBE644081F30614800664E68 /* BleSearchResultTableViewCell.m */,
CBE48CCC1CD07F0A0089DAF2 /* Main.storyboard */,
CBE48CCF1CD07F0A0089DAF2 /* Assets.xcassets */,
CBE48CD11CD07F0A0089DAF2 /* LaunchScreen.storyboard */,
CBE48CD41CD07F0A0089DAF2 /* Info.plist */,
CBE48CEE1CD0B2700089DAF2 /* Protocol */,
CBE48CC31CD07F0A0089DAF2 /* Supporting Files */,
CBE48CFE1CD0B6AA0089DAF2 /* BleControl.h */,
CBE48CFF1CD0B6AA0089DAF2 /* BleControl.m */,
CBF4AF3F1EE7EE290029CE7D /* NSData+NSString.h */,
CBF4AF401EE7EE290029CE7D /* NSData+NSString.m */,
CE3077231F8E259000EB87FF /* jacket_test_ios-Bridging-Header.h */,
);
path = jacket_test_ios;
sourceTree = "<group>";
};
CBE48CC31CD07F0A0089DAF2 /* Supporting Files */ = {
isa = PBXGroup;
children = (
CBE48CC41CD07F0A0089DAF2 /* main.m */,
);
name = "Supporting Files";
sourceTree = "<group>";
};
CBE48CDC1CD080280089DAF2 /* Frameworks */ = {
isa = PBXGroup;
children = (
CBF4AF2A1EE6AD660029CE7D /* libsqlite3.dylib */,
CBE48CDA1CD080120089DAF2 /* CoreBluetooth.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
CBE48CDD1CD084740089DAF2 /* BLE */ = {
isa = PBXGroup;
children = (
CBE48CDE1CD084740089DAF2 /* BLE.h */,
CBE48CDF1CD084740089DAF2 /* BLE.m */,
CBE48CE01CD084740089DAF2 /* BLEDefines.h */,
);
path = BLE;
sourceTree = "<group>";
};
CBE48CEE1CD0B2700089DAF2 /* Protocol */ = {
isa = PBXGroup;
children = (
CBE48CF91CD0B3D50089DAF2 /* BleProtocol.h */,
CBE48CF71CD0B3C30089DAF2 /* BleProtocol.m */,
);
name = Protocol;
sourceTree = "<group>";
};
CBF4AEF81EE55AF20029CE7D /* 3rdParties */ = {
isa = PBXGroup;
children = (
CBF4AEF91EE55B620029CE7D /* AFNetworking */,
);
name = 3rdParties;
sourceTree = "<group>";
};
CBF4AEF91EE55B620029CE7D /* AFNetworking */ = {
isa = PBXGroup;
children = (
CBF4AEFA1EE55B620029CE7D /* AFHTTPSessionManager.h */,
CBF4AEFB1EE55B620029CE7D /* AFHTTPSessionManager.m */,
CBF4AEFC1EE55B620029CE7D /* AFNetworking.h */,
CBF4AEFD1EE55B620029CE7D /* AFNetworkReachabilityManager.h */,
CBF4AEFE1EE55B620029CE7D /* AFNetworkReachabilityManager.m */,
CBF4AEFF1EE55B620029CE7D /* AFSecurityPolicy.h */,
CBF4AF001EE55B620029CE7D /* AFSecurityPolicy.m */,
CBF4AF011EE55B620029CE7D /* AFURLRequestSerialization.h */,
CBF4AF021EE55B620029CE7D /* AFURLRequestSerialization.m */,
CBF4AF031EE55B620029CE7D /* AFURLResponseSerialization.h */,
CBF4AF041EE55B620029CE7D /* AFURLResponseSerialization.m */,
CBF4AF051EE55B620029CE7D /* AFURLSessionManager.h */,
CBF4AF061EE55B620029CE7D /* AFURLSessionManager.m */,
);
name = AFNetworking;
path = 3rdParties/AFNetworking;
sourceTree = "<group>";
};
CBF4AF0D1EE637430029CE7D /* Operation */ = {
isa = PBXGroup;
children = (
CBF4AF0E1EE637830029CE7D /* Operation.h */,
CBF4AF0F1EE637830029CE7D /* Operation.m */,
);
name = Operation;
sourceTree = "<group>";
};
CBF4AF111EE638870029CE7D /* Other Sources */ = {
isa = PBXGroup;
children = (
CBF4AF121EE6389C0029CE7D /* jacket_test_ios_prefix.pch */,
);
name = "Other Sources";
path = jacket_ios;
sourceTree = "<group>";
};
CE3077281F8E2BBE00EB87FF /* model */ = {
isa = PBXGroup;
children = (
CE3077291F8E2BD700EB87FF /* SenserData.swift */,
);
name = model;
sourceTree = "<group>";
};
CE30772B1F8E369C00EB87FF /* util */ = {
isa = PBXGroup;
children = (
CE30772C1F8E36BD00EB87FF /* UserNofitication.swift */,
CE30772E1F8E36E500EB87FF /* UNResponseManager.swift */,
CE3077301F8E37DA00EB87FF /* Caller.swift */,
);
name = util;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
CBE48CBF1CD07F0A0089DAF2 /* jacket_test_ios */ = {
isa = PBXNativeTarget;
buildConfigurationList = CBE48CD71CD07F0A0089DAF2 /* Build configuration list for PBXNativeTarget "jacket_test_ios" */;
buildPhases = (
CBE48CBC1CD07F0A0089DAF2 /* Sources */,
CBE48CBD1CD07F0A0089DAF2 /* Frameworks */,
CBE48CBE1CD07F0A0089DAF2 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = jacket_test_ios;
productName = jacket_ios;
productReference = CBE48CC01CD07F0A0089DAF2 /* jacket_test_ios.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
CBE48CB81CD07F0A0089DAF2 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 0900;
ORGANIZATIONNAME = "ドラッサル 亜嵐";
TargetAttributes = {
CBE48CBF1CD07F0A0089DAF2 = {
CreatedOnToolsVersion = 7.2;
DevelopmentTeam = 7KP2X5K7RJ;
LastSwiftMigration = 0900;
ProvisioningStyle = Automatic;
};
};
};
buildConfigurationList = CBE48CBB1CD07F0A0089DAF2 /* Build configuration list for PBXProject "jacket_test_ios" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = CBE48CB71CD07F0A0089DAF2;
productRefGroup = CBE48CC11CD07F0A0089DAF2 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
CBE48CBF1CD07F0A0089DAF2 /* jacket_test_ios */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
CBE48CBE1CD07F0A0089DAF2 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
CBE48CD31CD07F0A0089DAF2 /* LaunchScreen.storyboard in Resources */,
CBF4AEF41EE54D910029CE7D /* FirmwareUpdateController.xib in Resources */,
CBE48CD01CD07F0A0089DAF2 /* Assets.xcassets in Resources */,
CBE0DBCD1F258A4000E765A4 /* EepromTemplateController.xib in Resources */,
CBF4AF1C1EE667CA0029CE7D /* FirmwareWriteController.xib in Resources */,
CBF4AF3E1EE7C8F00029CE7D /* FirmwareWriteControllerTableViewCell.xib in Resources */,
CBE0DBD21F258A7400E765A4 /* EepromTemplateTableViewCell.xib in Resources */,
CBF4AF171EE667B70029CE7D /* FirmwareDownloadController.xib in Resources */,
CBF4AF261EE670650029CE7D /* FirmwareDownloadControllerTableViewCell.xib in Resources */,
CBE0DBD71F25DDE600E765A4 /* BootSettingController.xib in Resources */,
CBE0DBC81F25804D00E765A4 /* EepromController.xib in Resources */,
CB53F4581F871AF300970458 /* InputSoundController.xib in Resources */,
4466131F1E134FC000A56C82 /* SettingsController.xib in Resources */,
CB34DA271E5E9C2200EBA2E4 /* InputMotorController.xib in Resources */,
CBE48CCE1CD07F0A0089DAF2 /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
CBE48CBC1CD07F0A0089DAF2 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
CBE0DBD61F25DDE600E765A4 /* BootSettingController.m in Sources */,
CBF4AF091EE55B620029CE7D /* AFSecurityPolicy.m in Sources */,
CBE6440B1F30614800664E68 /* BleSearchResultTableViewCell.m in Sources */,
CBE48CCB1CD07F0A0089DAF2 /* BleSearchViewController.m in Sources */,
CE30772F1F8E36E500EB87FF /* UNResponseManager.swift in Sources */,
CBF4AF411EE7EE290029CE7D /* NSData+NSString.m in Sources */,
4466131E1E134FC000A56C82 /* SettingsController.m in Sources */,
CBF4AF391EE6F1F80029CE7D /* DBManager.m in Sources */,
CBF4AF161EE667B70029CE7D /* FirmwareDownloadController.m in Sources */,
CBE48CC81CD07F0A0089DAF2 /* AppDelegate.m in Sources */,
CBE0DBCC1F258A4000E765A4 /* EepromTemplateController.m in Sources */,
CB34DA2A1E5E9C4B00EBA2E4 /* InputMotorController.m in Sources */,
CBE0DBC71F25804D00E765A4 /* EepromController.m in Sources */,
CBE48CC51CD07F0A0089DAF2 /* main.m in Sources */,
CE30772A1F8E2BD700EB87FF /* SenserData.swift in Sources */,
CE3077271F8E289100EB87FF /* DemoView.swift in Sources */,
CBF4AF0C1EE55B620029CE7D /* AFURLSessionManager.m in Sources */,
CBF4AF101EE637830029CE7D /* Operation.m in Sources */,
CE3077311F8E37DA00EB87FF /* Caller.swift in Sources */,
CBE6440C1F30614800664E68 /* BleSearchResultTableViewController.m in Sources */,
CBF4AF1B1EE667CA0029CE7D /* FirmwareWriteController.m in Sources */,
CBF4AF3D1EE7C8F00029CE7D /* FirmwareWriteControllerTableViewCell.m in Sources */,
CBE48D001CD0B6AA0089DAF2 /* BleControl.m in Sources */,
CBE48CE11CD084740089DAF2 /* BLE.m in Sources */,
CB53F4571F871AF300970458 /* InputSoundController.m in Sources */,
CBF4AF071EE55B620029CE7D /* AFHTTPSessionManager.m in Sources */,
CBF4AF0B1EE55B620029CE7D /* AFURLResponseSerialization.m in Sources */,
CE30772D1F8E36BD00EB87FF /* UserNofitication.swift in Sources */,
CBE48CF81CD0B3C30089DAF2 /* BleProtocol.m in Sources */,
CBF4AF251EE670650029CE7D /* FirmwareDownloadControllerTableViewCell.m in Sources */,
CBF4AF0A1EE55B620029CE7D /* AFURLRequestSerialization.m in Sources */,
CBF4AEF71EE54DE10029CE7D /* FirmwareUpdateController.m in Sources */,
CBE0DBD11F258A7400E765A4 /* EepromTemplateTableViewCell.m in Sources */,
CBF4AF081EE55B620029CE7D /* AFNetworkReachabilityManager.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXVariantGroup section */
CBE48CCC1CD07F0A0089DAF2 /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
CBE48CCD1CD07F0A0089DAF2 /* Base */,
);
name = Main.storyboard;
sourceTree = "<group>";
};
CBE48CD11CD07F0A0089DAF2 /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
CBE48CD21CD07F0A0089DAF2 /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
CBE48CD51CD07F0A0089DAF2 /* 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_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = 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_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
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_PREFIX_HEADER = jacket_test_ios_prefix.pch;
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 = 10.3;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
USER_HEADER_SEARCH_PATHS = 3rdParties;
};
name = Debug;
};
CBE48CD61CD07F0A0089DAF2 /* 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_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = 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_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
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_PREFIX_HEADER = jacket_test_ios_prefix.pch;
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 = 10.3;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
TARGETED_DEVICE_FAMILY = "1,2";
USER_HEADER_SEARCH_PATHS = 3rdParties;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
CBE48CD81CD07F0A0089DAF2 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = 7KP2X5K7RJ;
INFOPLIST_FILE = jacket_test_ios/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "com.momo-ltd.jackettestios";
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE = "";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_OBJC_BRIDGING_HEADER = "jacket_test_ios/jacket_test_ios-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 3.0;
};
name = Debug;
};
CBE48CD91CD07F0A0089DAF2 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_IDENTITY = "iPhone Developer";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = 7KP2X5K7RJ;
INFOPLIST_FILE = jacket_test_ios/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 8.0;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = "com.momo-ltd.jackettestios";
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE = "";
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_OBJC_BRIDGING_HEADER = "jacket_test_ios/jacket_test_ios-Bridging-Header.h";
SWIFT_VERSION = 3.0;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
CBE48CBB1CD07F0A0089DAF2 /* Build configuration list for PBXProject "jacket_test_ios" */ = {
isa = XCConfigurationList;
buildConfigurations = (
CBE48CD51CD07F0A0089DAF2 /* Debug */,
CBE48CD61CD07F0A0089DAF2 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
CBE48CD71CD07F0A0089DAF2 /* Build configuration list for PBXNativeTarget "jacket_test_ios" */ = {
isa = XCConfigurationList;
buildConfigurations = (
CBE48CD81CD07F0A0089DAF2 /* Debug */,
CBE48CD91CD07F0A0089DAF2 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = CBE48CB81CD07F0A0089DAF2 /* Project object */;
}
//
// AppDelegate.h
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2016/04/27.
// Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
//
// AppDelegate.m
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2016/04/27.
// Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//
#import "AppDelegate.h"
#import "jacket_test_ios-Swift.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
return [[Caller sheardInstance]application:application didFinishLaunchingWithOptions:launchOptions];
}
- (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:.
}
@end
{
"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"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11762" systemVersion="16D32" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11757"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="Llm-lL-Icb"/>
<viewControllerLayoutGuide type="bottom" id="xb3-aO-Qok"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13196" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="Jcl-sF-EGT">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13173"/>
<capability name="Constraints to layout margins" minToolsVersion="6.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--BLEの検索-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" userLabel="BLEの検索" customClass="BleSearchViewController" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="zgC-Yy-hfH">
<rect key="frame" x="146" y="318.5" width="83" height="30"/>
<constraints>
<constraint firstAttribute="width" constant="83" id="Qng-i0-OaI"/>
</constraints>
<state key="normal" title="Scan"/>
<connections>
<action selector="btnConnectClicked:" destination="BYZ-38-t0r" eventType="touchUpInside" id="Qar-ro-0Px"/>
</connections>
</button>
<activityIndicatorView hidden="YES" opaque="NO" contentMode="scaleToFill" horizontalHuggingPriority="750" verticalHuggingPriority="750" style="gray" translatesAutoresizingMaskIntoConstraints="NO" id="tJd-HG-X4C">
<rect key="frame" x="177.5" y="274.5" width="20" height="20"/>
</activityIndicatorView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="zgC-Yy-hfH" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="3Jq-Zt-IcV"/>
<constraint firstItem="tJd-HG-X4C" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="mt3-aS-n2r"/>
<constraint firstItem="zgC-Yy-hfH" firstAttribute="centerY" secondItem="8bC-Xf-vdC" secondAttribute="centerY" id="wCI-lZ-WuA"/>
<constraint firstItem="zgC-Yy-hfH" firstAttribute="top" secondItem="tJd-HG-X4C" secondAttribute="bottom" constant="24" id="wkQ-pr-QRo"/>
</constraints>
</view>
<navigationItem key="navigationItem" title="BLEの検索" id="SM2-MW-czc"/>
<connections>
<outlet property="activityScanning" destination="tJd-HG-X4C" id="yK2-cc-98U"/>
<segue destination="fry-cf-FRa" kind="show" identifier="idSegueBleDeviceList" id="lA6-Ow-MYV"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="905" y="429"/>
</scene>
<!--BLE検索の結果-->
<scene sceneID="KmE-QO-shw">
<objects>
<tableViewController id="fry-cf-FRa" customClass="BleSearchResultTableViewController" sceneMemberID="viewController">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="58" sectionHeaderHeight="28" sectionFooterHeight="28" id="Fuw-mT-WaZ">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<prototypes>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="cell_uuid" rowHeight="58" id="u9M-5X-FJa" customClass="BleSearchResultTableViewCell">
<rect key="frame" x="0.0" y="28" width="375" height="58"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="u9M-5X-FJa" id="QlV-zH-myQ">
<rect key="frame" x="0.0" y="0.0" width="375" height="57.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="NAME" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="cy4-HT-u0h" userLabel="lblName">
<rect key="frame" x="15" y="31" width="47.5" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="RSSI" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="uxz-0k-13E" userLabel="lblRssi">
<rect key="frame" x="331" y="31" width="36" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="UUID" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="yFY-1X-zf0" userLabel="lblUuid">
<rect key="frame" x="15" y="8" width="41" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<constraints>
<constraint firstItem="uxz-0k-13E" firstAttribute="trailing" secondItem="QlV-zH-myQ" secondAttribute="trailingMargin" id="9jN-I7-d6c"/>
<constraint firstItem="yFY-1X-zf0" firstAttribute="leading" secondItem="QlV-zH-myQ" secondAttribute="leadingMargin" constant="7" id="Rfv-3G-4z8"/>
<constraint firstItem="cy4-HT-u0h" firstAttribute="top" secondItem="yFY-1X-zf0" secondAttribute="bottom" constant="2" id="VH3-9l-3uB"/>
<constraint firstItem="yFY-1X-zf0" firstAttribute="top" secondItem="QlV-zH-myQ" secondAttribute="topMargin" id="WRh-y7-Cqq"/>
<constraint firstItem="cy4-HT-u0h" firstAttribute="leading" secondItem="QlV-zH-myQ" secondAttribute="leadingMargin" constant="7" id="bBQ-ig-FHF"/>
<constraint firstItem="uxz-0k-13E" firstAttribute="top" secondItem="QlV-zH-myQ" secondAttribute="topMargin" constant="23" id="j78-Oo-gNJ"/>
</constraints>
</tableViewCellContentView>
<connections>
<outlet property="lblName" destination="cy4-HT-u0h" id="41U-YR-Li5"/>
<outlet property="lblRssi" destination="uxz-0k-13E" id="bfk-7L-SSb"/>
<outlet property="lblUuid" destination="yFY-1X-zf0" id="ziK-NG-Pat"/>
</connections>
</tableViewCell>
</prototypes>
<connections>
<outlet property="dataSource" destination="fry-cf-FRa" id="dJJ-jv-0L6"/>
<outlet property="delegate" destination="fry-cf-FRa" id="tlY-sa-np3"/>
</connections>
</tableView>
<navigationItem key="navigationItem" title="BLE検索の結果" id="1pT-1a-7lI"/>
</tableViewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="3rJ-4N-e5U" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="1781" y="429"/>
</scene>
<!--Navigation Controller-->
<scene sceneID="GkI-08-L2I">
<objects>
<navigationController automaticallyAdjustsScrollViewInsets="NO" id="Jcl-sF-EGT" sceneMemberID="viewController">
<toolbarItems/>
<navigationBar key="navigationBar" contentMode="scaleToFill" id="D8Z-ZJ-H0D">
<rect key="frame" x="0.0" y="20" width="375" height="44"/>
<autoresizingMask key="autoresizingMask"/>
</navigationBar>
<nil name="viewControllers"/>
<connections>
<segue destination="BYZ-38-t0r" kind="relationship" relationship="rootViewController" id="W7D-eH-hFH"/>
</connections>
</navigationController>
<placeholder placeholderIdentifier="IBFirstResponder" id="xz5-Ay-Tlj" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="93" y="429"/>
</scene>
</scenes>
</document>
//
// BleControl.h
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2016/04/27.
// Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "BleProtocol.h"
#import "BLE.h"
@interface BleControl : UIViewController <BLEProtocolDelegate> {
IBOutlet UILabel *currentTime;
IBOutlet UILabel *currentState;
IBOutlet UILabel *currentUsetime;
IBOutlet UILabel *currentWalking;
IBOutlet UILabel *currentSleep;
IBOutlet UILabel *currentWake;
bool stateCurrentWalking;
}
@property (strong, nonatomic) BLE *ble;
@property (strong, nonatomic) BleProtocol *protocol;
- (IBAction)btnEditState:(id)sender;
- (IBAction)btnEditTime:(id)sender;
- (IBAction)btnEditSleep:(id)sender;
- (IBAction)btnEditWake:(id)sender;
- (IBAction)btnEditWalking:(id)sender;
- (IBAction)btnResetUsetime:(id)sender;
- (IBAction)btnUsetime:(id)sender;
- (void)getNextSlot;
@end
//
// BleControl.m
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2016/04/27.
// Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//
#import "BleControl.h"
@interface BleControl ()
@property (nonatomic) NSInteger slotCounter;
@property (nonatomic) NSInteger slotCounterMin;
@property (nonatomic) NSInteger slotCounterMax;
@property (nonatomic) NSTimer * tmr;
@end
@implementation BleControl
@synthesize ble;
@synthesize protocol;
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
self.slotCounterMin = 0;
self.slotCounterMax = 5;
self.slotCounter = self.slotCounterMin;
}
- (void)viewWillAppear:(BOOL)animated {
protocol.delegate = self;
self.tmr = [NSTimer timerWithTimeInterval:0.1
target:self
selector:@selector(tmrMethod:)
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.tmr forMode:NSRunLoopCommonModes];
}
- (void)viewWillDisappear:(BOOL)animated {
[self.tmr invalidate];
}
- (void)tmrMethod:(NSTimer *)timer {
[self getNextSlot];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)getNextSlot {
// TODO: Fix
/*
if(self.slotCounter == 0) {
[protocol getTime];
} else if(self.slotCounter == 1) {
[protocol getUsetime];
} else if(self.slotCounter == 2) {
[protocol getState];
} else if(self.slotCounter == 3) {
[protocol getSleep];
} else if(self.slotCounter == 4) {
[protocol getWake];
} else if(self.slotCounter == 5) {
[protocol getWalking];
}
*/
self.slotCounter++;
if(self.slotCounter > self.slotCounterMax) {
self.slotCounter = self.slotCounterMin;
}
}
- (IBAction)btnEditState:(id)sender {
[self performSegueWithIdentifier:@"idSegueEditState" sender:self];
}
- (IBAction)btnEditTime:(id)sender {
[self performSegueWithIdentifier:@"idSegueEditTime" sender:self];
}
- (IBAction)btnEditSleep:(id)sender {
[self performSegueWithIdentifier:@"idSegueEditSleep" sender:self];
}
- (IBAction)btnEditWake:(id)sender {
[self performSegueWithIdentifier:@"idSegueEditWake" sender:self];
}
- (IBAction)btnEditWalking:(id)sender {
// TODO: Fix
if(stateCurrentWalking == false) {
//[protocol setWalking:true];
} else {
//[protocol setWalking:false];
}
}
- (IBAction)btnResetUsetime:(id)sender {
// TODO: Fix
//[protocol resetUsetime];
}
- (IBAction)btnUsetime:(id)sender {
[self performSegueWithIdentifier:@"idSegueUsetime" sender:self];
}
- (IBAction)btnCaseUnlock:(id)sender {
// TODO: Fix
//[protocol setUnlock];
}
- (void) protocolDidReceiveState:(NSString *)data text:(NSString *)text {
[currentState setText:text];
}
- (void) protocolDidReceiveTime:(NSString *) data {
[currentTime setText:data];
}
- (void) protocolDidReceiveSleepingBegin:(NSString *) data {
[currentSleep setText:data];
}
- (void) protocolDidReceiveSleepingEnd:(NSString *) data {
[currentWake setText:data];
}
- (void) protocolDidReceiveUsetime:(NSInteger) data {
int seconds = data % 60;
int minutes = (data / 60) % 60;
int hours = (int)data / 3600;
NSString *strUsetime = [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
[currentUsetime setText:strUsetime];
}
- (void) protocolDidReceiveUsetimeSlot:(NSInteger) dataSlot dataStamp:(NSTimeInterval) dataStamp dataUsetime: (NSInteger) dataUsetime {
}
- (void) protocolDidReceiveWalking:(BOOL)data {
stateCurrentWalking = data;
NSString *strData = [NSString alloc];
if(stateCurrentWalking == false) {
strData = @"無効";
} else {
strData = @"有効";
}
[currentWalking setText:strData];
}
@end
/*
Copyright (c) 2013-2014 RedBearLab
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/Foundation.h>
#import "BLE.h"
#import <UIKit/UIKit.h>
@protocol BLEProtocolDelegate
@optional
- (void)protocolDidGetData:(NSString *)type data:(NSString *)data;
@required
@end
@interface BleProtocol : NSObject
@property (strong, nonatomic) BLE *ble;
@property (nonatomic,assign) id <BLEProtocolDelegate> delegate;
- (void) parseData:(unsigned char *) data length:(int) length;
/* APIs for query and read/write pins */
- (void)sendCommand: (uint8_t *) data Length:(uint8_t) length;
- (void)sendDisconnect;
- (void)putData:(NSString *)type data:(NSString *)data;
- (void)bleWriteRaw:(NSData*)data;
@end
/*
Copyright (c) 2013-2014 RedBearLab
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 "BleProtocol.h"
#import "jacket_test_ios-Swift.h"
@implementation BleProtocol
@synthesize ble;
//#define PROT_DEBUG
-(void)parseData:(unsigned char *) data length:(int) length
{
NSString *dataStringRaw = [NSString stringWithCString: (const char *)data encoding:NSUTF8StringEncoding];
dataStringRaw = [dataStringRaw substringToIndex:length];
NSLog(@"[BleProtocol parseData] %@",dataStringRaw);
/* for iot Demo */
NSArray *parsed = [[SenserData sheardInstance] parseData:dataStringRaw];
if(parsed != nil){
NSString *type = parsed[2];
NSString *payload = parsed[3];
[[SenserData sheardInstance] setData:type data:payload];
}
/* for iot Demo end */
NSArray *dataStringRawSplit = [[NSMutableArray alloc]initWithArray: [dataStringRaw componentsSeparatedByString:@"@"]];
for(id object in dataStringRawSplit) {
NSString * dataString = object;
NSInteger dataStringLength = [object length];
NSLog(@"%@",dataString);
if([dataString length] < 2) {
dataString = [dataString stringByAppendingString:@"@"];
}
if([dataString length] > 1) {
if(![[dataString substringWithRange:NSMakeRange([dataString length] - 1, 1)] isEqualToString: @"?"]) {
if([dataString hasPrefix:@"ii"]) {
NSString *strData = [NSString stringWithFormat:@"%@",
[dataString substringWithRange:NSMakeRange(2, dataStringLength - 2)]];
[[self delegate] protocolDidGetData:@"infoDeviceId" data:strData];
} else if([dataString hasPrefix:@"it"]) {
NSString *strData = [NSString stringWithFormat:@"%@",
[dataString substringWithRange:NSMakeRange(2, dataStringLength - 2)]];
[[self delegate] protocolDidGetData:@"infoDeviceType" data:strData];
} else if([dataString hasPrefix:@"im"]) {
NSString *strData = [NSString stringWithFormat:@"%@",
[dataString substringWithRange:NSMakeRange(2, dataStringLength - 2)]];
[[self delegate] protocolDidGetData:@"infoDeviceModel" data:strData];
} else if([dataString hasPrefix:@"io"]) {
NSString *strData = [NSString stringWithFormat:@"%@",
[dataString substringWithRange:NSMakeRange(2, dataStringLength - 2)]];
[[self delegate] protocolDidGetData:@"infoDeviceOs" data:strData];
} else if([dataString hasPrefix:@"ip"]) {
NSString *strData = [NSString stringWithFormat:@"%@",
[dataString substringWithRange:NSMakeRange(2, dataStringLength - 2)]];
[[self delegate] protocolDidGetData:@"infoDevicePin" data:strData];
} else if([dataString hasPrefix:@"ki"]) {
NSString *strData = [NSString stringWithFormat:@"%@",
[dataString substringWithRange:NSMakeRange(2, dataStringLength - 2)]];
[[self delegate] protocolDidGetData:@"readDeviceId" data:strData];
} else if([dataString hasPrefix:@"kt"]) {
NSString *strData = [NSString stringWithFormat:@"%@",
[dataString substringWithRange:NSMakeRange(2, dataStringLength - 2)]];
[[self delegate] protocolDidGetData:@"readDeviceType" data:strData];
} else if([dataString hasPrefix:@"km"]) {
NSString *strData = [NSString stringWithFormat:@"%@",
[dataString substringWithRange:NSMakeRange(2, dataStringLength - 2)]];
[[self delegate] protocolDidGetData:@"readDeviceModel" data:strData];
} else if([dataString hasPrefix:@"ko"]) {
NSString *strData = [NSString stringWithFormat:@"%@",
[dataString substringWithRange:NSMakeRange(2, dataStringLength - 2)]];
[[self delegate] protocolDidGetData:@"readDeviceOs" data:strData];
} else if([dataString hasPrefix:@"kp"]) {
NSString *strData = [NSString stringWithFormat:@"%@",
[dataString substringWithRange:NSMakeRange(2, dataStringLength - 2)]];
[[self delegate] protocolDidGetData:@"readDevicePin" data:strData];
} else if([dataString hasPrefix:@"ji"]) {
[[self delegate] protocolDidGetData:@"writeDeviceId" data:@"OK"];
} else if([dataString hasPrefix:@"jm"]) {
[[self delegate] protocolDidGetData:@"writeDeviceModel" data:@"OK"];
} else if([dataString hasPrefix:@"jt"]) {
[[self delegate] protocolDidGetData:@"writeDeviceType" data:@"OK"];
} else if([dataString hasPrefix:@"jo"]) {
[[self delegate] protocolDidGetData:@"writeDeviceOs" data:@"OK"];
} else if([dataString hasPrefix:@"jp"]) {
[[self delegate] protocolDidGetData:@"writeDevicePin" data:@"OK"];
} else if([dataString hasPrefix:@"rm"]) {
if(dataStringLength == 3) {
NSString *strMotor = [dataString substringWithRange:NSMakeRange(2,1)];
NSString *strMotorText = @"";
if([strMotor isEqualToString:@"0"]) {
strMotorText = @"OFF";
} else if([strMotor isEqualToString:@"1"]) {
strMotorText = @"ON0";
} else if([strMotor isEqualToString:@"2"]) {
strMotorText = @"ON2";
}
[[self delegate] protocolDidGetData:@"readMotor" data:strMotorText];
}
} else if([dataString hasPrefix:@"wm"]) {
[[self delegate] protocolDidGetData:@"writeMotor" data:@"OK"];
} else if([dataString hasPrefix:@"ws"]) {
[[self delegate] protocolDidGetData:@"writeSound" data:@"OK"];
} else if([dataString hasPrefix:@"ep"]) {
if(dataStringLength == 3) {
NSString *strData = [dataString substringWithRange:NSMakeRange(2,1)];
[[self delegate] protocolDidGetData:@"eepromWriteProtect" data:strData];
}
} else if([dataString hasPrefix:@"fi"]) {
if(dataStringLength == 3) {
NSString *strData = [dataString substringWithRange:NSMakeRange(2,1)];
[[self delegate] protocolDidGetData:@"firmwareImageSelect" data:strData];
}
} else if([dataString hasPrefix:@"fc"]) {
[[self delegate] protocolDidGetData:@"firmwareBufferClear" data:@"OK"];
} else if([dataString hasPrefix:@"fw"]) {
if(dataStringLength == 4) {
NSString *strData = [dataString substringWithRange:NSMakeRange(2,2)];
[[self delegate] protocolDidGetData:@"firmwareFlashWrite" data:strData];
}
} else if([dataString hasPrefix:@"fe"]) {
if(dataStringLength == 3) {
NSString *strData = [dataString substringWithRange:NSMakeRange(2,1)];
NSString *strDataText = @"";
if([strData isEqualToString:@"0"]) {
strDataText = @"0";
} else if([strData isEqualToString:@"1"]) {
strDataText = @"1";
}
[[self delegate] protocolDidGetData:@"firmwareFlashErase" data:strDataText];
}
} else if([dataString hasPrefix:@"sr"]) {
[[self delegate] protocolDidGetData:@"systemReset" data:@"OK"];
} else if([dataString hasPrefix:@"su"]) {
[[self delegate] protocolDidGetData:@"systemResetInBootloader" data:@"OK"];
} else if(dataStringLength == 1) {
//data write success
[[self delegate] protocolDidGetData:@"firmwareBufferWrite" data:@"OK"];
} else {
//unknown data received
[[self delegate] protocolDidGetData:@"unknown" data:@"unknown"];
}
} else if([dataString hasPrefix:@"x"]) {
//error
[[self delegate] protocolDidGetData:@"firmwareBufferWrite" data:@"NG"];
}
}
}
}
- (void)sendCommand: (uint8_t *) data Length:(uint8_t) length
{
uint8_t buf[length+1];
memcpy(&buf[0], data, length);
uint8_t len = length+1;
buf[len - 1] = '@';
NSData *nsData = [[NSData alloc] initWithBytes:buf length:len];
[ble write:nsData];
}
- (void)sendDisconnect {
NSString *strData = @"sd@";
NSData *nsData = [strData dataUsingEncoding:NSUTF8StringEncoding];
[ble write:nsData];
}
- (void)putData:(NSString *)type data:(NSString *)data {
NSString *blePut = nil;
if([type isEqualToString:@"infoDeviceId"]) {
NSString *bleCommand = @"ii";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"infoDeviceType"]) {
NSString *bleCommand = @"it";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"infoDeviceModel"]) {
NSString *bleCommand = @"im";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"infoDeviceOs"]) {
NSString *bleCommand = @"io";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"infoDevicePin"]) {
NSString *bleCommand = @"ip";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"readDeviceId"]) {
NSString *bleCommand = @"ki";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"readDeviceType"]) {
NSString *bleCommand = @"kt";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"readDeviceModel"]) {
NSString *bleCommand = @"km";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"readDeviceOs"]) {
NSString *bleCommand = @"ko";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"readDevicePin"]) {
NSString *bleCommand = @"kp";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"writeDeviceId"]) {
NSString *bleCommand = @"ji";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"writeDeviceModel"]) {
NSString *bleCommand = @"jm";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"writeDeviceType"]) {
NSString *bleCommand = @"jt";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"writeDeviceOs"]) {
NSString *bleCommand = @"jo";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"writeDevicePin"]) {
NSString *bleCommand = @"jp";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"readMotor"]) {
NSString *bleCommand = @"rm";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"writeMotor"]) {
NSString *bleCommand = @"wm";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"writeSound"]) {
NSString *bleCommand = @"ws";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"eepromWriteProtect"]) {
NSString *bleCommand = @"ep";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"firmwareImageSelect"]) {
NSString *bleCommand = @"fi";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"firmwareBufferClear"]) {
NSString *bleCommand = @"fc";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"firmwareFlashErase"]) {
NSString *bleCommand = @"fe";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"firmwareFlashWrite"]) {
NSString *bleCommand = @"fw";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"systemReset"]) {
NSString *bleCommand = @"sr";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
} else if([type isEqualToString:@"systemResetInBootloader"]) {
NSString *bleCommand = @"su";
blePut = [NSString stringWithFormat:@"%@%@@",bleCommand,[self safeNil:data]];
}
if(blePut) {
NSLog(@"BLE_WRITE: %@", blePut);
NSData *nsData = [blePut dataUsingEncoding:NSUTF8StringEncoding];
[ble write:nsData];
} else {
NSLog(@"BLE_WRITE: ERROR %@ UNKNOWN", type);
}
}
- (void)bleWriteRaw:(NSData*)data {
[ble write:data];
}
- (NSString *)safeNil:(NSString *)data {
if(data == nil) return @"";
return data;
}
@end
//
// DetailViewTableViewCell.h
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2016/04/27.
// Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface BleSearchResultTableViewCell : UITableViewCell {
IBOutlet UILabel *lblUuidTapped;
IBOutlet UILabel *lblRssiTapped;
IBOutlet UILabel *lblNameTapped;
}
@property (strong, nonatomic) UILabel *lblUuid;
@property (strong, nonatomic) UILabel *lblRssi;
@property (strong, nonatomic) UILabel *lblName;
@end
//
// DetailViewTableViewCell.m
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2016/04/27.
// Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//
#import "BleSearchResultTableViewCell.h"
@implementation BleSearchResultTableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
@end
//
// BleSearchResultTableViewController.h
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2016/04/27.
// Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "BLE.h"
#import "BleProtocol.h"
@interface BleSearchResultTableViewController : UITableViewController
@property (strong, nonatomic) BLE *ble;
@property (strong, nonatomic) BleProtocol *protocol;
@property (strong, nonatomic) NSMutableArray *BLEDevices;
@property (strong, nonatomic) NSMutableArray *BLEDevicesRssi;
@property (strong, nonatomic) NSMutableArray *BLEDevicesName;
@end
//
// BleSearchResultTableViewController.m
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2016/04/27.
// Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//
#import "BleSearchResultTableViewController.h"
#import "BleSearchResultTableViewCell.h"
@interface BleSearchResultTableViewController ()
@end
@implementation BleSearchResultTableViewController
@synthesize ble;
@synthesize BLEDevicesRssi;
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
self.BLEDevicesRssi = [NSMutableArray arrayWithArray:ble.peripheralsRssi];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void) connectionTimer:(NSTimer *)timer
{
[self.BLEDevices removeAllObjects];
[self.BLEDevicesRssi removeAllObjects];
[self.BLEDevicesName removeAllObjects];
if (ble.peripherals.count > 0)
{
for (int i = 0; i < ble.peripherals.count; i++)
{
CBPeripheral *p = [ble.peripherals objectAtIndex:i];
NSNumber *n = [ble.peripheralsRssi objectAtIndex:i];
NSString *name = [[ble.peripherals objectAtIndex:i] name];
if (p.identifier.UUIDString != NULL)
{
[self.BLEDevices insertObject:p.identifier.UUIDString atIndex:i];
[self.BLEDevicesRssi insertObject:n atIndex:i];
if (name != nil)
{
[self.BLEDevicesName insertObject:name atIndex:i];
}
else
{
[self.BLEDevicesName insertObject:@"RedBear Device" atIndex:i];
}
}
else
{
[self.BLEDevices insertObject:@"NULL" atIndex:i];
[self.BLEDevicesRssi insertObject:@"0" atIndex:i];
[self.BLEDevicesName insertObject:@"RedBear Device" atIndex:i];
}
}
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"No BLE Device(s) found."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
[self.tableView reloadData];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return self.BLEDevices.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *tableIdentifier = @"cell_uuid";
BleSearchResultTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableIdentifier forIndexPath:indexPath];
// Configure the cell...
UIFont *newFont = [UIFont fontWithName:@"Arial" size:13.5];
cell.lblUuid.font = newFont;
cell.lblUuid.text = [self.BLEDevices objectAtIndex:indexPath.row];
newFont = [UIFont fontWithName:@"Arial" size:11.0];
cell.lblRssi.font = newFont;
NSMutableString *rssiString = [NSMutableString stringWithFormat:@"RSSI : %@", [self.BLEDevicesRssi objectAtIndex:indexPath.row]];
cell.lblRssi.text = rssiString;
newFont = [UIFont fontWithName:@"Arial" size:13.0];
cell.lblName.font = newFont;
cell.lblName.text = [self.BLEDevicesName objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(ble.isConnected) {
[self.protocol sendDisconnect];
}
[ble connectPeripheral:[ble.peripherals objectAtIndex:indexPath.row]];
}
@end
//
// ViewController.h
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2016/04/27.
// Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "BLE.h"
#import "BleProtocol.h"
@interface BleSearchViewController : UIViewController <BLEDelegate>
{
IBOutlet UIActivityIndicatorView *activityScanning;
IBOutlet UIButton *btnConnect;
IBOutlet UIButton *btnConnectLast;
IBOutlet UILabel *lblVersion;
BOOL showAlert;
bool isFindingLast;
}
@property (strong, nonatomic) BLE *ble;
@property (strong, nonatomic) BleProtocol *protocol;
@property (strong, nonatomic) NSMutableArray *mDevices;
@property (strong, nonatomic) NSMutableArray *mDevicesName;
@property (strong,nonatomic) NSString *lastUUID;
- (IBAction)btnConnectClicked:(id)sender;
- (IBAction)lastClick:(id)sender;
- (void)bleDidConnect;
- (void)bleDidDisconnect;
- (void)bleDidReceiveData:(unsigned char *)data length:(int)length;
- (void)bleDidUpdateRSSI:(NSNumber *) rssi;
- (NSString *)getUUIDString:(CFUUIDRef)ref;
@end
//
// BleSearchViewController.m
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2016/04/27.
// Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//
#import "BleSearchViewController.h"
#import "BleControl.h"
#import "BleSearchResultTableViewController.h"
#import "SettingsController.h"
#import "Operation.h"
#import "jacket_test_ios-Swift.h"
@interface BleSearchViewController ()
@end
NSString * const UUIDPrefKey = @"UUIDPrefKey";
@implementation BleSearchViewController
@synthesize ble;
@synthesize protocol;
BleControl *cv;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
ble = [[BLE alloc] init];
[ble controlSetup];
ble.delegate = self;
self.mDevices = [[NSMutableArray alloc] init];
self.mDevicesName = [[NSMutableArray alloc] init];
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"])
{
[[NSUserDefaults standardUserDefaults] setObject:@"" forKey:UUIDPrefKey];
}
//Retrieve saved UUID from system
self.lastUUID = [[NSUserDefaults standardUserDefaults] objectForKey:UUIDPrefKey];
if ([self.lastUUID isEqualToString:@""])
{
[btnConnectLast setEnabled:NO];
}
else
{
[btnConnectLast setEnabled:YES];
}
protocol = [[BleProtocol alloc] init];
protocol.ble = ble;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"idSegueBleDeviceList"])
{
BleSearchResultTableViewController *vc = [segue destinationViewController];
vc.BLEDevices = self.mDevices;
vc.BLEDevicesName = self.mDevicesName;
vc.ble = ble;
vc.protocol = protocol;
}
else if ([[segue identifier] isEqualToString:@"idSegueBleDevice"])
{
cv = [segue destinationViewController];
cv.ble = ble;
cv.protocol = protocol;
}
}
- (void)connectionTimer:(NSTimer *)timer
{
showAlert = YES;
[btnConnect setEnabled:YES];
self.lastUUID = [[NSUserDefaults standardUserDefaults] objectForKey:UUIDPrefKey];
if ([self.lastUUID isEqualToString:@""])
{
[btnConnectLast setEnabled:NO];
}
else
{
[btnConnectLast setEnabled:YES];
}
if (ble.peripherals.count > 0)
{
if(isFindingLast)
{
int i;
for (i = 0; i < ble.peripherals.count; i++)
{
CBPeripheral *p = [ble.peripherals objectAtIndex:i];
if (p.identifier.UUIDString != NULL)
{
//Comparing UUIDs and call connectPeripheral is matched
if([self.lastUUID isEqualToString:p.identifier.UUIDString])
{
showAlert = NO;
[ble connectPeripheral:p];
}
}
}
}
else
{
[self.mDevices removeAllObjects];
[self.mDevicesName removeAllObjects];
int i;
for (i = 0; i < ble.peripherals.count; i++)
{
CBPeripheral *p = [ble.peripherals objectAtIndex:i];
if (p.identifier.UUIDString != NULL)
{
[self.mDevices insertObject:p.identifier.UUIDString atIndex:i];
if (p.name != nil) {
[self.mDevicesName insertObject:p.name atIndex:i];
} else {
[self.mDevicesName insertObject:@"RedBear Device" atIndex:i];
}
}
else
{
[self.mDevices insertObject:@"NULL" atIndex:i];
[self.mDevicesName insertObject:@"RedBear Device" atIndex:i];
}
}
showAlert = NO;
[self performSegueWithIdentifier:@"idSegueBleDeviceList" sender:self];
}
}
if (showAlert == YES) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"No BLE Device(s) found."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
[activityScanning stopAnimating];
}
- (IBAction)btnConnectClicked:(id)sender
{
if (ble.activePeripheral)
if(ble.activePeripheral.state == CBPeripheralStateConnected)
{
[[ble CM] cancelPeripheralConnection:[ble activePeripheral]];
return;
}
if (ble.peripherals)
ble.peripherals = nil;
[btnConnect setEnabled:false];
[btnConnectLast setEnabled:NO];
[ble findBLEPeripherals:3];
[NSTimer scheduledTimerWithTimeInterval:(float)3.0 target:self selector:@selector(connectionTimer:) userInfo:nil repeats:NO];
isFindingLast = false;
[activityScanning startAnimating];
}
- (IBAction)lastClick:(id)sender {
if (ble.peripherals) {
ble.peripherals = nil;
}
[btnConnect setEnabled:false];
[btnConnectLast setEnabled:NO];
[ble findBLEPeripherals:3];
[NSTimer scheduledTimerWithTimeInterval:(float)3.0 target:self selector:@selector(connectionTimer:) userInfo:nil repeats:NO];
isFindingLast = true;
[activityScanning startAnimating];
}
- (void) bleDidConnect
{
NSLog(@"->DidConnect");
self.lastUUID = ble.activePeripheral.identifier.UUIDString;
[[NSUserDefaults standardUserDefaults] setObject:self.lastUUID forKey:UUIDPrefKey];
[[NSUserDefaults standardUserDefaults] synchronize];
self.lastUUID = [[NSUserDefaults standardUserDefaults] objectForKey:UUIDPrefKey];
if ([self.lastUUID isEqualToString:@""]) {
[btnConnectLast setEnabled:NO];
} else {
[btnConnectLast setEnabled:YES];
}
[activityScanning stopAnimating];
[self populatePcbInfo];
[SettingsController show:(NSString *)protocol navigationController:self.navigationController];
}
- (void)bleDidDisconnect
{
NSLog(@"->DidDisconnect");
[activityScanning stopAnimating];
[self.navigationController popToRootViewControllerAnimated:true];
}
- (void)populatePcbInfo {
if([Operation sharedOperation].pcbDeviceId == nil) {
[protocol putData:@"infoDeviceId" data:nil];
} else if([Operation sharedOperation].pcbDeviceType == nil) {
[protocol putData:@"infoDeviceType" data:nil];
} else if([Operation sharedOperation].pcbDeviceModel == nil) {
[protocol putData:@"infoDeviceModel" data:nil];
} else if([Operation sharedOperation].pcbDeviceOs == nil) {
[protocol putData:@"infoDeviceOs" data:nil];
}
}
- (void) bleDidReceiveData:(unsigned char *)data length:(int)length
{
NSLog(@"data!!!%s", data);
for(int i = 0; i < length; i++) {
if((data[i] < 32) || (data[i] > 127)) {
data[i] = ' ';
}
}
NSString* dataString = [NSString stringWithCString: (const char *)data encoding:NSUTF8StringEncoding];
dataString = [dataString substringToIndex:length];
NSLog(@"->DidReceiveData- %@",dataString);
if([dataString hasPrefix:@"ii"]) {
[Operation sharedOperation].pcbDeviceId = [dataString substringWithRange:NSMakeRange(2, [dataString length] - 3)];
[self populatePcbInfo];
} else if ([dataString hasPrefix:@"it"]) {
[Operation sharedOperation].pcbDeviceType = [dataString substringWithRange:NSMakeRange(2, [dataString length] - 3)];
[self populatePcbInfo];
} else if ([dataString hasPrefix:@"im"]) {
[Operation sharedOperation].pcbDeviceModel = [dataString substringWithRange:NSMakeRange(2, [dataString length] - 3)];
[self populatePcbInfo];
} else if ([dataString hasPrefix:@"io"]) {
[Operation sharedOperation].pcbDeviceOs = [dataString substringWithRange:NSMakeRange(2, [dataString length] - 3)];
[self populatePcbInfo];
}
[protocol parseData:data length:length];
/* for iot Demo */
[[Caller sheardInstance] proximityNofitication :[SenserData sheardInstance].proximity ];
/* for iot Demo end */
}
- (void) bleDidUpdateRSSI:(NSNumber *) rssi
{
}
- (NSString *)getUUIDString:(CFUUIDRef)ref {
NSString *str = [NSString stringWithFormat:@"%@", ref];
return [[NSString stringWithFormat:@"%@", str] substringWithRange:NSMakeRange(str.length - 36, 36)];
}
@end
//
// caller.swift
// jacket_test_ios
//
// Created by USER on 2017/10/11.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
import Foundation
import UIKit
import UserNotifications
class Caller:NSObject{
public static let sheardInstance:Caller = Caller()
public func proximityNofitication(_ data:Int){
if(data > 100 ){return}
if #available(iOS 10.0, *) {
NSLog("yobareta");
UserNofitication.sharedInstance.easyNofitication(
/* nofitication detail */
identifier : "nofity",
title : "データが届きました",
body : String(data) + "cm",
actions : [
UNNotificationAction(
identifier: "possitive",
title: "",
options:[])], completionHandler: ({(Error)->Void in
}),
/* response callback */
response : UNResponseManager.sharedInstance.setResponse(identifier: "nofity") {(_ actionIdentifier:String) in
switch actionIdentifier {
case "positive":
break
case UNNotificationDismissActionIdentifier:
/* 選択せずにnofiticationを消去の場合*/
break
case UNNotificationDefaultActionIdentifier:
/* 選択せずにアプリ起動場合*/
break
default:
break
}
})
} else {
// Fallback on earlier versions
}
}
public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert], completionHandler: { (granted, error) in
if error != nil {
print(error?.localizedDescription)
return
}
})
}
return true
}
}
//
// caller.swift
// jacket_test_ios
//
// Created by USER on 2017/10/11.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
import Foundation
class Caller{
UserNofitication.sharedInstance.easyNofitication(
/* nofitication detail */
identifier : "accident",
title : DefaultText.AccidentTitle.rawValue,
body : DefaultText.AccidentBody.rawValue,
actions : [
UNNotificationAction(
identifier:"negative",
title: DefaultText.AccidentNegativeButton.rawValue,
options: []),
UNNotificationAction(
identifier: "possitive",
title: DefaultText.AccidentPositiveButton.rawValue,
options:[])], completionHandler: ({(Error)->Void in
/* 応答がなければ アクシデントとみなす */
if(UserState.instance._hasAccident)!{
_ = Timer.scheduledTimer(
timeInterval: 120.0,
target : self,
selector : #selector(core_functions.sharedInstance.accidentHappend),
userInfo : nil,
repeats : false ).fire()
}
}),
/* response callback */
response : UNResponseManager.sharedInstance.setResponse(identifier: "accident") {(_ actionIdentifier:String) in
NSLog("accident happend")
switch actionIdentifier {
case "negative":
core_functions.sharedInstance.accidentHappend()
break
case "positive":
core_functions.sharedInstance.accidentCancel()
break
case UNNotificationDismissActionIdentifier:
/* 選択せずにnofiticationを消去の場合*/
break
case UNNotificationDefaultActionIdentifier:
/* 選択せずにアプリ起動場合*/
break
default:
break
}
})
}
}
//
// DemoViewController.swift
// jacket_test_ios
//
// Created by USER on 2017/10/11.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
import UIKit
class DemoViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>jacket_test_ios</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>0.1</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
//
// NSData+NSString.h
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2017/06/07.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSData (NSString)
- (NSString *)toString;
@end
//
// NSData+NSString.m
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2017/06/07.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
#import "NSData+NSString.h"
@implementation NSData (NSString)
- (NSString *)toString
{
Byte *dataPointer = (Byte *)[self bytes];
NSMutableString *result = [NSMutableString stringWithCapacity:0];
NSUInteger index;
for (index = 0; index < [self length]; index++)
{
[result appendFormat:@"0x%02x,", dataPointer[index]];
}
return result;
}
@end
//
// Data.swift
// jacket_test_ios
//
// Created by USER on 2017/10/11.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
import Foundation
class SenserData:NSObject{
public static let sheardInstance:SenserData = SenserData()
public var data:String = "1"
public var proximity:Int = 0
public func setData(_ type:String,data:String){
switch type {
case "03":
proximity = Int(data, radix: 16)!
break
default:
break
}
}
public func parseData(_ data:String)->[String]?{
if(5 > data.count ){return nil}
var parsed = [String]()
parsed.append(substr(data,start: 0, end: 4))
NSLog(substr(data,start: 0, end: 4))
parsed.append(substr(data,start: 4, end: 8))
NSLog(substr(data,start: 4, end: 8))
parsed.append(substr(data,start: 8, end: 10))
NSLog(substr(data,start: 8, end: 10))
parsed.append(substr(data,start: 10, end: 14))
parsed.append(substr(data,start: 14, end: 16))
return parsed
}
public func lessThan(_ val:Int , of:Int)->Int?{
if(val < of){ return of }
return nil
}
private func substr(_ str:String,start:Int,end:Int)->String{
let startIndex = str.index(str.startIndex, offsetBy: start)
let endIndex = str.index(str.startIndex, offsetBy: end)
return str.substring(with: startIndex..<endIndex)
}
}
//
// UserNofiticationManager.swift
// ko-seigen
//
// Created by USER on 2017/10/04.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
import Foundation
//
// UNNofiticationResponse.swift
// ko-seigen
//
// Created by USER on 2017/10/04.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
import Foundation
import UserNotifications
class UNResponseManager:NSObject, UNUserNotificationCenterDelegate{
static let sharedInstance = UNResponseManager();
private var Response:[String:((_ actionIdentifier:String) -> Void )] = [:]
public func setResponse( identifier:String,response:@escaping ((_ actionIdentifier:String) -> Void ))
->UNResponseManager{
if(Response[identifier] == nil){
Response[identifier] = response
}
return self
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert,.sound])
NSLog("called")
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let id = response.notification.request.content.categoryIdentifier
if(Response[id] != nil){
Response[id]!(response.actionIdentifier)
}
completionHandler()
}
}
import Foundation
//
// UNNofitication.swift
// ko-seigen
//
// Created by USER on 2017/10/04.
// Copyright © 2017年 ドラッサル 亜嵐. All rights reserved.
//
import Foundation
import UserNotifications
class UserNofitication:NSObject{
static let sharedInstance = UserNofitication()
@available(iOS 10.0, *)
public func easyNofitication(
identifier : String,
title : String,
body : String,
actions : [UNNotificationAction],
completionHandler :((Error?) -> Void)?,
response :UNResponseManager
){
let category = UNNotificationCategory(identifier: identifier,
actions: actions ,
intentIdentifiers: [],
options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = UNNotificationSound.default()
content.categoryIdentifier = identifier
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: identifier,
content: content,
trigger: trigger)
let center = UNUserNotificationCenter.current()
center.delegate = UNResponseManager.sharedInstance
center.add(request, withCompletionHandler:completionHandler)
}
}
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
//
// main.m
// jacket_ios
//
// Created by ドラッサル 亜嵐 on 2016/04/27.
// Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
//
// jacket_ios_prefix.pch
// tuber
//
// Created by ドラッサル 亜嵐 on 2016/06/09.
// Copyright © 2016年 ドラッサル 亜嵐. All rights reserved.
//
#ifndef jacket_ios_prefix_pch
#define jacket_ios_prefix_pch
// Include any system framework and library headers here that should be included in all compilation units.
// You will also need to set the Prefix Header build setting of one or more of your targets to reference this file.
#define URL_BASE @"http://jacketapi.momo-ltd.com"
#define URL_PATH_API @"/jacketapi/%@"
#define URL_PATH_STORE_FIRMWARE @"/jacketapi/firmware_download.php?uuid=%@"
#define USER_USERID @"username"
#define USER_PASSWORD @"password"
#define KEY_USER_USERID @"username"
#define KEY_USER_PASSWORD @"password"
#define AGENT_KEY @"agent"
#define VNAME_KEY @"vname"
#define DATABASE @"sqlitedb.sql"
#endif /* Tuber_Prefix_pch */