Vasilis

new project added

Showing 129 changed files with 25094 additions and 0 deletions
No preview for this file type
No preview for this file type
//
// WarplyEvents.h
// App
//
// Created by Fotios Kalaitzidis on 23/10/2018.
// Copyright © 2018 Facebook. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface WarplyReactMethods : NSObject
@end
//
// WarplyEvents.m
// App
//
// Created by Fotios Kalaitzidis on 23/10/2018.
// Copyright © 2018 Facebook. All rights reserved.
//
#import "WarplyReactMethods.h"
#import "WLUserManager.h"
#import "WLAnalyticsManager.h"
#import "Warply.h"
#import <AdSupport/AdSupport.h>
@implementation WarplyReactMethods
- (void) sendEvent: (NSString *) eventName priority: (BOOL) priority {
NSString *event_Name = eventName;
NSNumber *time_submitted = [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]];
NSDictionary *inapp_event = [NSDictionary dictionaryWithObjectsAndKeys:event_Name, @"event_id", nil, @"page_id", time_submitted, @"time_submitted", nil, @"action_metadata", nil];
NSDictionary *eventContext = [NSDictionary dictionaryWithObject:inapp_event forKey:@"inapp_analytics"];
WLEventSimple *simpleEvent = [[WLEventSimple alloc] initWithType:@"inapp_analytics" andContext:eventContext];
[[Warply sharedService] addEvent:simpleEvent priority:priority];
}
- (NSString *) getUniqueId {
return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
}
- (NSString *) getAdvertisementId {
return [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
}
@end
MIT License
Copyright © 2018 Matan Cohen
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.
\ No newline at end of file
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
{
"images" : [
{
"filename" : "logo.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"filename" : "logo-1.png",
"idiom" : "universal",
"scale" : "2x"
},
{
"filename" : "logo-2.png",
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
No preview for this file type
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLEvent.h
The WLEvent provides a functional interface for Warply events.
Use the methods declared here to initialise and create events with arbitrary
context and type.
@copyright Warply Inc.
*/
#import <Foundation/Foundation.h>
/*!
@class WLEvent
@discussion This class provides methods for creating an event with arbitrary
context.
*/
@interface WLEvent : NSObject
{
@protected
NSString *_time;
NSMutableDictionary *_data;
}
/*!
@methodgroup Class Methods
@discussion Convinience class methods for initialising an event.
*/
/*!
@abstract Creates an event.
@discussion Initializes and returns a newly allocated WLEvent object.
Initializes and returns a newly allocated WLEvent object.
@return Returns WLEvent object.
*/
+ (id)event;
/*!
@abstract Creates an event with arbitrary context.
@discussion Initializes and returns a newly allocated WLEvent object with the
arbitrary context.
@param context A dictionary object with arbitrary key-value entries.
@return Returns WLEvent object.
*/
+ (id)eventWithContext:(NSDictionary*)context;
/*!
@property time
@abstract A string with event created time in epoch format. Read only property.
*/
@property (nonatomic, readonly) NSString *time;
/*!
@property data
@abstract A dictionary with event context. Read only property.
*/
@property (nonatomic, readonly) NSMutableDictionary *data;
/*!
@methodgroup Initialising Event
*/
/*!
@abstract Initialise an WLevent object.
@discussion Initializes and returns a newly allocated WLEvent object with the
arbitrary context.
@param context A dictionary object with arbitrary key-value entries.
@return Returns WLEvent object.
*/
- (id)initWithContext:(NSDictionary*)context;
/*!
@methodgroup Getting Event Type
*/
/*!
@abstract Get event type.
@discussion This method returns the type of the event.
@return Returns a string object with event type.
*/
- (NSString *)getType;
/*!
@methodgroup Adding Context to Event
*/
/*!
@abstract Add context to event.
@discussion This method adds a key-value pair to existing context of an event.
@param value An id object with the value of the key.
@param key A string object with the key of the value.
*/
- (void)addDataWithValue:(id)value forKey:(NSString*)key;
@end
/*!
@class WLEventSimple
@discussion This class provides methods for creating an event with arbitrary
context and type.
*/
@interface WLEventSimple : WLEvent
{
@private
NSString *_type;
}
/*!
@methodgroup Class Methods
@discussion Convinience class methods for initialising an event.
*/
/*!
@abstract Creates an event with arbitrary type.
@discussion Initializes and returns a newly allocated WLEventSimple object
with arbitrary type.
@param aType A string object with the event type.
@return Returns WLEvent object.
*/
+ (id)eventWithType:(NSString*)aType;
/*!
@abstract Creates an event with arbitrary type and context.
@discussion Initializes and returns a newly allocated WLEventSimple object
with arbitrary type and context.
@param aType A string object with the event type.
@param context A dictionary with arbitrary context.
@return Returns WLEvent object.
*/
+ (id)eventWithType:(NSString*)aType andContext:(NSDictionary*)context;
/*!
@methodgroup Initialising Event
*/
/*!
@abstract Initialise an event with arbitrary type.
@discussion Initializes and returns a newly allocated WLEvent object with the
arbitrary type.
@param aType A string object with the event type.
@return Returns WLEvent object.
*/
- (id)initWithType:(NSString*)aType;
/*!
@abstract Initialise an event with arbitrary type and context.
@discussion Initializes and returns a newly allocated WLEvent object with the
arbitrary type and context.
@param aType A string object with the event type.
@param context A dictionary with arbitrary context.
@return Returns WLEvent object.
*/
- (id)initWithType:(NSString*)aType andContext:(NSDictionary*)context;
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "WLEvent.h"
#import "WLGlobals.h"
@interface WLEvent()
- (void)gatherIndividualData:(NSDictionary*)context;
- (void)gatherData:(NSDictionary*)context;
@end
@implementation WLEvent
@synthesize time = _time;
@synthesize data = _data;
#pragma mark - Static Methods
///////////////////////////////////////////////////////////////////////////////////////////////////
+ (id)event
{
#if ! __has_feature(objc_arc)
return [[[self alloc] init] autorelease];
#else
return [[self alloc] init];
#endif
}
///////////////////////////////////////////////////////////////////////////////////////////////////
+ (id)eventWithContext:(NSDictionary*)context
{
#if ! __has_feature(objc_arc)
return [[[self alloc] initWithContext:context] autorelease];
#else
return [[self alloc] initWithContext:context];
#endif
}
#pragma mark - Initialization
///////////////////////////////////////////////////////////////////////////////////////////////////
- (id)init
{
self = [super init];
if (self) {
_data = [NSMutableDictionary new];
}
return self;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (id)initWithContext:(NSDictionary*)context
{
self = [self init];
if (self) {
[self gatherData:context];
}
return self;
}
#pragma mark - Public Methods
///////////////////////////////////////////////////////////////////////////////////////////////////
- (NSString*)getType
{
return @"base";
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)addDataWithValue:(id)value forKey:(NSString*)key
{
if (value && key)
[_data setObject:value forKey:key];
}
#pragma mark - Private Methods
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)gatherIndividualData:(NSDictionary*)context { }
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)gatherData:(NSDictionary*)context {
// in case we re-use a event object
_time = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
[_data removeAllObjects];
// gather individual data
[self gatherIndividualData:context];
}
@end
///////////////////////////////////////////////////////////////////////////////////////////////////
@implementation WLEventSimple
#pragma mark - Static Methods
///////////////////////////////////////////////////////////////////////////////////////////////////
+ (id)eventWithType:(NSString*)aType
{
return [[self alloc] initWithType:aType];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
+ (id)eventWithType:(NSString*)aType andContext:(NSDictionary*)context
{
return [[self alloc] initWithType:aType andContext:context];
}
#pragma mark - Initialization
///////////////////////////////////////////////////////////////////////////////////////////////////
- (id)initWithType:(NSString*)aType
{
self=[super init];
if (self) {
_type = aType;
}
return self;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (id)initWithType:(NSString*)aType andContext:(NSDictionary*)context
{
self = [super initWithContext:context];
if (self) {
_type = aType;
}
return self;
}
#pragma mark - Public Methods
///////////////////////////////////////////////////////////////////////////////////////////////////
- (NSString*)getType
{
return _type;
}
#pragma mark - Override Methods
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)gatherIndividualData:(NSDictionary*)context
{
WLLOG(@"WLEvent Context: %@", context);
[_data addEntriesFromDictionary:context];
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
///////////////////////////////////////////////////////////////////////////////
// Base URL
//#define WARP_PRODUCTION_BASE_URL @"https://engage-stage.warp.ly"
//#define WARP_HOST @"engage-stage.warp.ly"
//#define WARP_ERROR_DOMAIN @"engage-stage.warp.ly"
extern NSString* WARP_PRODUCTION_BASE_URL;
extern NSString* WARP_HOST;
extern NSString* WARP_ERROR_DOMAIN;
extern NSString* MERCHANT_ID;
extern NSString* LANG;
#define WARP_PAGE_URL_FORMAT @"%@/api/session/%@"
#define WARP_IMAGE_URL_FORMAT @"%@/api/session/logo/%@"
///////////////////////////////////////////////////////////////////////////////
// Settings
#ifdef _WL_VERSION
#define WL_VERSION @ _WL_VERSION
#else
#define WL_VERSION @ "3.2.0a"
#endif
#define GEOFENCING_POIS_ENABLED @"GEOFENCING_POIS_ENABLED"
#define WL_IOS_LOCATION_FOREGROUND_MODE @"IOS_LOCATION_FOREGROUND_MODE"
#define WL_IOS_LOCATION_BACKGROUND_MODE @"IOS_LOCATION_BACKGROUND_MODE"
#define WL_IOS_GEOFENCING_ENABLED @"IOS_GEOFENCING_ENABLED"
#define WL_IOS_FOREGROUND_DISTANCE_FILTER @"IOS_FOREGROUND_DISTANCE_FILTER"
#define WL_IOS_BACKGROUND_DISTANCE_FILTER @"IOS_BACKGROUND_DISTANCE_FILTER"
#define WL_DEVICE_INFO_ENABLED @"DEVICE_INFO_ENABLED"
#define WL_OFFERS_ENABLED @"OFFERS_ENABLED"
#define WL_CONSUMER_DATA_ENABLED @"CONSUMER_DATA_ENABLED"
#define WL_USER_SESSION_ENABLED @"USER_SESSION_ENABLED"
#define WL_CUSTOM_ANALYTICS_ENABLED @"CUSTOM_ANALYTICS_ENABLED"
#define WL_USER_TAGGING_ENABLED @"USER_TAGGING_ENABLED"
#define WL_APPLICATION_DATA_ENABLED @"APPLICATION_DATA_ENABLED"
#define WL_WARPLY_ENABLED @"WARPLY_ENABLED"
#define WL_FEATURES_CHECK_INTERVAL @"FEATURES_CHECK_INTERVAL"
#define WL_LIFECYCLE_ANALYTICS_ENABLED @"LIFECYCLE_ANALYTICS_ENABLED"
#define WL_IOS_LOCATION_FOREGROUND_DESIRED_ACCURACY @"IOS_LOCATION_FOREGROUND_DESIRED_ACCURACY"
#define WL_IOS_LOCATION_BACKGROUND_DESIRED_ACCURACY @"IOS_LOCATION_BACKGROUND_DESIRED_ACCURACY"
#define WL_IOS_DEVICE_IS_WARPED @"is_warped"
#define WL_IOS_DEVICE_HAS_DEVICE_INFO @"has_device_info"
#define WL_IOS_DEVICE_HAS_APPLICATION_INFO @"has_application_info"
#define WL_FEATURE_IS_DISABLED_WITH_KEY(KEY) \
([[NSUserDefaults standardUserDefaults] boolForKey:KEY] == NO \
&& [[NSUserDefaults standardUserDefaults] objectForKey:KEY] != nil) \
#define WL_WARP_NOTIFICATIONS_ENABLED @"warp_enabled"
#define WL_APPLICATION_DATA @"application_data"
#define WL_DEVICE_STATUS @"device_status"
#define WL_BEACON_ENABLED @"BEACON_ENABLED"
#define WL_BEACON_TIME_INTERVAL_TO_RESEND @"BEACON_TIME_INTERVAL_TO_RESEND"
///////////////////////////////////////////////////////////////////////////////
// Logging
#ifdef DEBUG
#define WLLOG(xx, ...) NSLog(@"%s(%d): " xx, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define WLLOG(xx, ...) ((void)0)
#endif // #ifdef DEBUG
///////////////////////////////////////////////////////////////////////////////
// Version Interface
#define WL_VERSION_INTERFACE() \
+ (NSString *)get;
#define WL_VERSION_IMPLEMENTATION(VERSION_STR) \
+ (NSString *)get { \
return VERSION_STR; \
} \
///////////////////////////////////////////////////////////////////////////////
// System Versioning
#define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
///////////////////////////////////////////////////////////////////////////////
// Enum Versioning
#ifdef __IPHONE_6_0 // iOS6 and later
# define WLTextAlignmentCenter NSTextAlignmentCenter
# define WLTextAlignmentLeft NSTextAlignmentLeft
# define WLTextAlignmentRight NSTextAlignmentRight
# define WLTextTruncationTail NSLineBreakByTruncatingTail
# define WLTextTruncationMiddle NSLineBreakByWordWrapping
# define WLLineBreakByWordWrapping NSLineBreakByWordWrapping
#else // older versions
# define WLTextAlignmentCenter UITextAlignmentCenter
# define WLTextAlignmentLeft UITextAlignmentLeft
# define WLTextAlignmentRight UITextAlignmentRight
# define WLTextTruncationTail UILineBreakModeTailTruncation
# define WLTextTruncationMiddle UILineBreakModeMiddleTruncation
# define WLLineBreakByWordWrapping UILineBreakModeWordWrap
#endif
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header Warply.h
Provides a functional interface for Warply service.
Use the methods declared here to launch or abolish Warply service, access and
manage available functionality managers, add events and send them, get campaigns
inbox and POST/GET context from/to Warply service.
@copyright Warply Inc.
*/
#import <Foundation/Foundation.h>
#import "WLGlobals.h"
#import "WLEvent.h"
#import "WLLocationManager.h"
#import "WLAnalyticsManager.h"
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
#import "WLPushManager.h"
@class WLUserManager;
@protocol WLActionHandler;
/*!
@defined WL_FMDBLogError
@abstract Defines an error logger for the local DB.
*/
#define WL_FMDBLogError if ([_db hadError]) { WLLOG(@"Err %d: %@", [_db lastErrorCode], [_db lastErrorMessage]); }
/*!
@typedef _WLResultCodes
@abstract Warply related custom result codes.
@field WLResultCodesSuccess The call was sucessful.
@field WLResultCodesError The structure or the parameters of the call are wrong.
@field WLResultCodesReadOnly You can read only and not write the selected attribute.
@field WLResultCodesInvalidCampaignID Either the campaing is expired or revoked.
@field WLResultCodesInvalidAppID You need to set the correct app id as shown in Warply.
@field WLResultCodesDeviceRegistrationFailed Check that device token is in correct format.
@field WLResultCodesInvalidJsonPath Check the path you trying to access.
@field WLResultCodesNotImplemented The call doesn't exists yet.
@field WLResultCodesInvalidWebID Need to register device again.
@field WLResultCodesAuthorizationFailed Invalid hash was sent.
@field WLResultCodesNotRegistered Need to register device prior to make the call.
@discussion These result codes are custom and related to Warply service. They
indicate whether a call is sucessfull and if not why it failed.
*/
typedef enum {
WLResultCodesSuccess = 1,
WLResultCodesError,
WLResultCodesReadOnly,
WLResultCodesInvalidCampaignID,
WLResultCodesInvalidAppID,
WLResultCodesDeviceRegistrationFailed,
WLResultCodesInvalidJsonPath,
WLResultCodesNotImplemented,
WLResultCodesInvalidWebID,
WLResultCodesAuthorizationFailed,
WLResultCodesNotRegistered
} _WLResultCodes;
/*!
@typedef WLContextRequestType
@abstract Warply related request types.
@field WLContextRequestTypeGet A GET type request.
@field WLContextRequestTypePost A POST type request.
@discussion These two types of requests indicate whether a request is GET or POST.
*/
typedef enum {
WLContextRequestTypeGet,
WLContextRequestTypePost
}WLContextRequestType;
/*!
@typedef WLServerType
@abstract Warply related servers types.
@field WLServerTypeDevelopment The developement Warply server. Mainly, used for
development and testing.
@field WLServerTypeProduction The production Warply server. Used by all live apps.
*/
typedef enum {
WLServerTypeDevelopment = 0,
WLServerTypeProduction
}WLServerType;
/*!
@defined WLResultCodesDescriptions
@abstract Defines an array of Warply releated results status.
*/
#define WLResultCodesDescriptions [NSArray arrayWithObjects:@"Success", @"Error", @"Read-only or Invalid context property", @"Invalid Campaign ID", @"Invalid Application ID", @"Device Registration Failed", @"Invalid JSON Path", @"Not Implemented", @"Invalid web-id", @"Authorisation Failed", nil]
/*!
@class WLAppService
@discussion The WLAppService provides a functional interface for Warply service.
*/
@interface Warply : NSObject
{
@private
//DB
FMDatabase *_db;
//Services
WLPushManager *_pushManager;
WLLocationManager *_locationManager;
}
/*!
@methodgroup Getting Shared Instance
*/
/*!
@abstract Returns a shared instance of WLAppService.
*/
+ (Warply *)sharedService;
/*!
@methodgroup Launching and Abolishing Warp service.
*/
/*!
@abstract Launching the Warply service.
@discussion This class method initialises the shared instance of WLAppService,
passes the launch options (if any) to managers in order to handle them and
launches the communication with Warply service using the provided unique app identification.
@param appUUID A string with the unique app identification.
@param launchOptions A dictionary with the application launch options. May be
empty if application launched by user.
*/
+ (void)launchWithAppUUID:(NSString *)appUUID launchOptions:(NSDictionary *)launchOptions;
/*!
@abstract Launching the Warply service.
@discussion This class method initialises the shared instance of WLAppService,
passes the launch options (if any) to managers in order to handle them and
launches the communication with Warply service using the provided unique app identification.
@param launchOptions A dictionary with the application launch options. May be
empty if application launched by user.
@param appUUID A string with the unique app identification.
@param customPushDelegate an class conforming to the WLCustomPushDelegate protocol responsible for handling the push notification.
*/
+ (void)launchWithAppUUID:(NSString *)appUUID launchOptions:(NSDictionary *)launchOptions customPushHandler:(id <WLCustomPushHandler>)customPushHandler;
/*!
@abstract Launching the Warply service.
@discussion This class method initialises the shared instance of WLAppService,
passes the launch options (if any) to managers in order to handle them and
launches the communication with Warply service using the provided unique app identification.
@param launchOptions A dictionary with the application launch options. May be
empty if application launched by user.
@param appUUID A string with the unique app identification.
@param customPushDelegate an class conforming to the WLCustomPushDelegate protocol responsible for handling the push notification.
@param baseUrl: A NSString parameter for defining the base url.
*/
+ (void)launchWithAppUUID:(NSString *)appUUID launchOptions:(NSDictionary *)launchOptions customPushDelegate:(id <WLCustomPushHandler>)customPushDelegate serverBaseUrl:(NSString *)baseUrl;
/*!
@property baseURL
@abstract A string the url of Warply server. Read-only access.
*/
@property (nonatomic, readonly, copy) NSString *baseURL;
/*!
@property webId
@abstract A string with the unique web id of the device.
*/
@property (nonatomic, copy, readonly) NSString *webId;
/*!
@property apiKey
@abstract A string with the unique identifier of the application.
*/
@property (nonatomic, copy) NSString *apiKey;
//Services
/*!
@property pushManager
@abstract A WLPush Manager for handling received Remote Notifications (Push).
*/
@property (nonatomic, strong) WLPushManager *pushManager;
/*!
@property locationManager
@abstract A WLLocation Manager for handling and reporting device location.
*/
@property (nonatomic, readonly, strong) WLLocationManager *locationManager;
/*!
@property consumerDataManager
@abstract A WLConsumer Manager for handling user name,e-mail and MSISDN.
*/
@property (nonatomic, readonly, strong) WLUserManager *consumerDataManager;
/*!
@property allOffers
@abstract All cached campaigns that the Warply Service provides the application according to the appUUID.
*/
@property (nonatomic, strong) NSArray *allOffers;
@property (nonatomic, strong) NSArray *allProducts;
/*!
@defined WL_VERSION_INTERFACE
@abstract Defines macros for geeting the SDK version.
@parseOnly
*/
WL_VERSION_INTERFACE()
/*!
@methodgroup App Lifecycle Methods
@discussion Convenience methods for mananging Managers behaviour and sendining
in-app analytics according to app state.
*/
/*!
@abstract Notify that app did enter background.
@discussion This method notifies managers and sends in-app analytic that app did
enter background.
*/
- (void)applicationDidEnterBackground;
/*!
@abstract Notify that app will enter foreground.
@discussion This method notifies managers and sends in-app analytic that app will
enter foreground.
*/
- (void)applicationWillEnterForeground;
/*!
@abstract Notify that app did become active.
@discussion This method notifies managers and sends in-app analytic that app did
become active.
*/
- (void)applicationDidBecomeActive;
/*!
@abstract Notify that app will terminate.
@discussion This method notifies managers and sends in-app analytic that app will
terminate.
*/
- (void)applicationWillTerminate;
/*!
@methodgroup Public API
@discussion Convenience methods for doing the most common tasks
*/
/*!
@abstract Send an event.
@discussion This method sends an event. This event is stored into a local DB
and is sent over to Warply service when a threshold of stored events is exceeded or immediately if the priority parameter is YES
@param event A WLEvent object.
@param priority A BOOL value indicating if the event should be sent immediately or not.
@see //apple_ref/occ/cl/WLEvent WLEvent
@seealso //apple_ref/occ/instm/WLAppService/addPriorityEvent: addPriorityEvent:
*/
- (void)addEvent:(WLEvent *)event priority:(BOOL)priority;
/*!
@abstract Get inbox from Warply service.
@attributeblock successBlock This block is called when getInbox is sucessful and returns an array with the available WLInboxItem items.
@attributeblock failureBlock This block is called when getInbox fails and returns an error object with failure code and description.
@see //apple_ref/occ/cl/WLInboxItem WLInboxItem
@return Returns YES if the app is registered with Warply and thus the success or failure block will definitely be called and NO otherwise. In the latter case, the call is queued and will be called as soon as / if the app registers with Warply.
@discussion This method gets the inbox with campaigns from Warply service. The
method returns an array with WLInboxItem objects (campaigns). The caller will probably want to use the return parameter and a timer to update the UI or do any other operation after a certain amount of time that the app remains unregistered and thus, cannot make the call.
*/
- (BOOL)getInboxWithSuccessBlock:(void (^)(NSArray *list))success failureBlock:(void (^)(NSError *error))failure;
- (void)getProductsWithSuccessBlock:(NSString*)filter :(void(^)(NSMutableArray *params))success failureBlock:(void(^)(NSError *error))failure;
- (void)sendContactWithSuccessBlock:(NSString *)name andEmail:(NSString *)email andMsisdn:msisdn andMessage:message :(void(^)(NSMutableArray *params)) success failureBlock:(void(^)(NSError *error))failure;
- (void)getContentWithCategoryWithSuccessBlock:(NSString *)category andTags:(NSArray *)tags :(void(^)(NSMutableArray *params)) success failureBlock:(void(^)(NSError *error))failure;
- (void)getMerchantCategoriesWithSuccessBlock :(void(^)(NSMutableArray *params)) success failureBlock:(void(^)(NSError *error))failure;
- (void)getMerchantsWithSuccessBlock:(void(^)(NSMutableArray *params)) success failureBlock:(void(^)(NSError *error))failure;
- (void)getTagsCategoriesWithSuccessBlock :(void(^)(NSMutableArray *tagsCategories))success failureBlock:(void(^)(NSError *error))failure;
- (void)getTagsWithSuccessBlock :(void(^)(NSMutableArray *tagsCategories))success failureBlock:(void(^)(NSError *error))failure;
- (void)loginWithSuccessBlock:(NSString*)id andPassword:(NSString*)password andLoginType:(NSString*)loginType :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)webAuthorizeWithSuccessBlock:(NSDictionary*)contextResponse andId:(NSString*)id andLoginType:(NSString*)loginType :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)tokenWithSuccessBlock:(NSDictionary*)contextResponse andClientId:(NSString*)clientId andClientSecret:(NSString*)clientSecret andLoginType:(NSString*) loginType :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)registerWithSuccessBlock:(NSString*)id andPassword:(NSString*)password andName:(NSString*)name andEmail:(NSString*)email andSegmentation:(NSNumber*)segmentation andNewsletter:(NSNumber*)newsletter :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)refreshToken:(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)changePasswordWithSuccessBlock:(NSString*)oldPassword andNewPassword:(NSString*)newPassword :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)getProfileWithSuccessBlock :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)editProfileWithSuccessBlock:(NSString*)firstName andLastName:(NSString*)lastName andEmail:(NSString*)email andSalutation:(NSString*)salutation andMsisdn:(NSString*)msisdn
andNickname:(NSString*)nickname andGender:(NSString*)gender andBirthday:(NSString*)birthday andNameDay:(NSString*)nameday andTaxID:(NSString*)taxID andProfileMetadata:(NSDictionary*)profileMetadata optin:(NSNumber*) optin newsLetter:(NSNumber*)newsletter
andSMS:(NSNumber*)sms andSegmentation:(NSNumber*)segmentation andSMSSegmentation:(NSNumber*)smsSegmentation :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)changeProfileImageWithSuccessBlock:(NSString*)image andUserId:(NSString*)userId :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)addCardWithSuccessBlock:(NSString*)number andCardIssuer:(NSString*)cardIssuer andCardHolder:(NSString*)cardHolder andExpirationMonth:(NSString*)expirationMonth andExpirationYear:(NSString*)expirationYear :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)getCardsWithSuccessBlock:(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)deleteCardWithSuccessBlock:(NSString*)token :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)getCouponsWithSuccessBlock:(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)getTransactionHistoryWithSuccessBlock:(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)getPointsHistoryWithSuccessBlock:(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)verifyTicketWithSuccessBlock:(NSString*)guid :(NSString*)ticket :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)addAddressWithSuccessBlock:(NSString*)friendlyName :(NSString*)addressName :(NSString*)addressNumber :(NSString*)postalCode :(NSNumber*)floorNumber :(NSString*)doorbel :(NSString*)region :(NSString*)latitude :(NSString*)longitude :(NSString*)notes :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)getAddressWithSuccessBlock:(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)editAddressWithSuccessBlock:(NSString*)friendlyName andAddressName:(NSString*)addressName andAddressNumber:(NSString*)addressNumber andPostalCode:(NSString*)postalCode andFloorNumber:(NSNumber*)floorNumber andDoorbel:(NSString*)doorbel andRegion:(NSString*)region andLatitude:(NSString*)latitude andLongitude:(NSString*)longitude andNotes:(NSString*)notes andUuid:(NSString*)uuid :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)deleteAddressWithSuccessBlock:(NSString*)uuid :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)redeemCouponWithSuccessBlock:(NSString*)id andUuid:(NSString*)uuid :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)forgotPasswordWithIdWithSuccessBlock:(NSString*)id andConfCode:(NSString*)confCode andOtpUuid:(NSString*)otpUuid :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)requestOtpWithMsisdnWithSuccessBlock:(NSString*)msisdn andScope:(NSString*)scope :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)resetPasswordWithPasswordWithSuccessBlock:(NSString*)password andConfCode:(NSString*)confCode andOtpUuid:(NSString*)otpUuid andConfToken:(NSString*)confToken :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
- (void)retrieveMultilingualMerchantsWithCategoriesWithSuccessBlock:(NSArray*)categories andDefaultShown:(NSNumber*)defaultShown andCenter:(NSNumber*)center andTags:(NSArray*)tags andUuid:(NSString*)uuid andDistance:(NSNumber*)distance :(void(^)(NSDictionary *response))success failureBlock:(void(^)(NSError *error))failure;
/*!
@abstract Get the full page add accordint to the display_type of a campaign.
@attributeblock successBlock This block is called when getInbox is sucessful and allOffers is empty or nil and returns an array with the available WLInboxItem items. Otherwise, the allOffers array is filtered.
@attributeblock failureBlock This block is called when getInbox fails and returns an error object with failure code and description.
@see //apple_ref/occ/cl/WLInboxItem WLInboxItem
@return Returns YES if the app is registered with Warply and thus the success or failure block will definitely be called and NO otherwise. In the latter case, the call is queued and will be called as soon as / if the app registers with Warply.
@discussion This method gets the inbox with full_page campaigns from Warply service. The method returns an array with WLInboxItem objects (campaigns) with display_type = full_page. The caller will probably want to use the return parameter and a timer to update the UI or do any other operation after a certain amount of time that the app remains unregistered and thus, cannot make the call.
*/
- (BOOL)showFullPageAdIfExists:(void (^)(NSArray *list))success failureBlock:(void (^)(NSError *error))failure;
/*!
@abstract Get inbox from Warply service by filter.
@attributeblock successBlock This block is called when getInbox is sucessful and returns an array with the avaiable filtered WLInboxItem items.
@attributeblock failureBlock This block is called when getInbox fails and returns an error object with failure code and description.
@see //apple_ref/occ/cl/WLInboxItem WLInboxItem
@return Returns YES if the app is registered with Warply and thus the success or failure block will definitely be called and NO otherwise. In the latter case, the call is queued and will be called as soon as / if the app registers with Warply.
*/
- (BOOL)getInboxByFilter:(NSString*)filter andValue:(NSString*)value withSuccessBlock:(void (^)(NSArray *list))success failureBlock:(void (^)(NSError *error))failure;
/*!
@abstract Gets the inbox items that are linked to locations near the given location.
@attributeblock successBlock This block is called when getInbox is sucessful and returns an array with the avaiable WLInboxItem items.
@attributeblock failureBlock This block is called when getInbox fails and returns an error object with failure code and description.
@see //apple_ref/occ/cl/WLInboxItem WLInboxItem
@return Returns YES if the app is registered with Warply and thus the success or failure block will definitely be called and NO otherwise. In the latter case, the call is queued and will be called as soon as / if the app registers with Warply.
@discussion This method gets the inbox with campaigns from Warply service. The
method returns an array with WLInboxItem objects (campaigns). The caller will probably want to use the return parameter and a timer to update the UI or do any other operation after a certain amount of time that the app remains unregistered and thus, cannot make the call.
*/
- (BOOL)getInboxItemsNearLocation:(CLLocationCoordinate2D)coordinates withSuccessBlock:(void (^)(NSArray *list))success failureBlock:(void (^)(NSError *error))failure;
/*!
@abstract Gets the inbox items that are linked to locations near user.
@attributeblock successBlock This block is called when getInbox is sucessful and returns an array with the avaiable WLInboxItem items.
@attributeblock failureBlock This block is called when getInbox fails and returns an error object with failure code and description.
@see //apple_ref/occ/cl/WLInboxItem WLInboxItem
@return Returns YES if the app is registered with Warply and thus the success or failure block will definitely be called and NO otherwise. In the latter case, the call is queued and will be called as soon as / if the app registers with Warply.
@discussion This method gets the inbox with campaigns from Warply service. The
method returns an array with WLInboxItem objects (campaigns). The caller will probably want to use the return parameter and a timer to update the UI or do any other operation after a certain amount of time that the app remains unregistered and thus, cannot make the call.
*/
- (BOOL)getInboxItemsNearMeWithSuccessBlock:(void (^)(NSArray *list))success failureBlock:(void (^)(NSError *error))failure;
/*
@abstract Get the statistics for the inbox.
@param success: A block that is executed when the call succeeds and has int parameters the count of the items in the inbox, the new items and the unread items;
@param failure: A block with an NSError parameter that gets called when the call fails.
*/
- (void)getInboxStatusWithSuccessBlock:(void (^)(int count, int newItems, int unread))success failureBlock:(void (^)(NSError *error))failure;
/*!
@methodgroup Low Level API
@discussion Convenience methods for either GET/POST context or send all events
stored in local DB.
*/
/*!
@abstract Get context for the specified path.
@param path A string with the path to access and get the value.
@attributeblock successBlock This block is called when getContex is sucessful and returns an id.
@attributeblock failureBlock This block is called when getInbox fails and returns an error object with failure code and description.
@return Returns YES if the app is registered with Warply and thus the success or failure block will definitely be called and NO otherwise. In the latter case, the call is queued and will be called as soon as / if the app registers with Warply.
@discussion This method gets the context for the specified path. The success block has a parameter of type
id as the type of the data returned value may differ in each case depending on the specified
path. The caller will probably want to use the return parameter and a timer to update the UI or do any other operation after a certain amount of time that the app remains unregistered and thus, cannot make the call.
*/
- (BOOL)getContextWithPath:(NSString *)path
successBlock:(void (^)(id contextResponse))successBlock
failureBlock:(void (^)(NSError *error))failureBlock;
/*!
@abstract Post context to a specified path.
@param context The data you want to send to the server under the "context" key.
@attributeblock successBlock This block is called when sendContext is sucessful and returns an id.
@attributeblock failureBlock This block is called when the call fails and returns an error object with failure code and description.
@see //apple_ref/c/tdef/_WLResultCodes WLResultCodes
@return Returns YES if the app is registered with Warply and thus the success or failure block will definitely be called and NO otherwise. In the latter case, the call is queued and will be called as soon as / if the app registers with Warply.
@discussion This method post the context for the specified path. Make sure that
the path, you are trying to access, has write and not only read permissions. If
it has only read permsissions the post will fail with WLResultCodesReadOnly error
code. The caller will probably want to use the return parameter and a timer to update the UI or do any other operation after a certain amount of time that the app remains unregistered and thus, cannot make the call.
*/
- (BOOL)sendContext:(NSData*)context
successBlock:(void (^)(NSDictionary *contextResponse))successBlock
failureBlock:(void (^)(NSError *error))failureBlock;
/*!
@abstract Send all localy stored events to Warply service.
@discussion This method flags and sends all the locally stored events to Warply
service. This happend independent if number of locally stored event threshold
has be reached or not. The events are deleted from local DB only when the call is
sucesful. Otherwise, the events remain stored until either the threshold of stored
events is excited and they automatically send to Warply service or this method is
called again.
@attributeblock completionBlock This block is called when sendAllEvents is sucessful.
@attributeblock failureBlock This block is called when sendAllEvents fails and returns an error object with failure code and description.
*/
- (void)sendAllEventsWithCompletionBlock:(void (^)(void))successBlock failureBlock:(void (^)(void))failureBlock;
//TODO: needs revision
/*!
@abstract Gets the context and updates properties relevant with feature (microapp) and application variables availability .
@attributeblock completionBlock This block is called when the call to the server is completed successfully.
@attributeblock failureBlock This block is called when the call to the server fails.
*/
- (void)getAppSettingsWithSuccessBlock:(void (^)(void))success failureBlock:(void(^)(NSError *error))failure;
// TODO: add documentation
- (void)registerActionHandler:(id <WLActionHandler>)handler;
- (BOOL)handleActionUrl:(NSURL *)url;
-(BOOL)checkIfUserLoactionIsInPois:(CLLocation *) location;
@end
// TODO: add documentation
@protocol WLActionHandler <NSObject>
- (BOOL)canHandleActionUrl:(NSURL *)url;
- (void)handleActionUrl:(NSURL *)url;
@end
This diff could not be displayed because it is too large.
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Foundation/Foundation.h>
#import <StoreKit/StoreKit.h>
#import "Warply.h"
@interface WLAPPActionHandler : NSObject <WLActionHandler,SKStoreProductViewControllerDelegate>
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "WLAPPActionHandler.h"
#import "WLAnalyticsManager.h"
#import "WLInboxItemViewController.h"
#import "NSString+SSToolkitAdditions.h"
#import "UIViewController+WLAdditions.h"
@interface WLAPPActionHandler ()
@property (nonatomic, assign) WLInboxItemViewController *inboxVC;
@property (nonatomic) BOOL *loadingProduct;
@end
@implementation WLAPPActionHandler
#pragma mark - Static Methods
////////////////////////////////////////////////////////////////////////////////
- (BOOL)canHandleActionUrl:(NSURL *)url
{
return [url.scheme isEqualToString: @"itms-apps"];
}
#pragma mark - Override Methods
////////////////////////////////////////////////////////////////////////////////
- (void)handleActionUrl:(NSURL *)url
{
UINavigationController *inboxNavCon = (UINavigationController *)[([UIApplication sharedApplication].delegate).window.rootViewController topModalViewController];
self.inboxVC = [inboxNavCon.viewControllers objectAtIndex:0];
NSString *appID = nil;
if ([SKStoreProductViewController class]) {
__block SKStoreProductViewController *storeViewController = [[SKStoreProductViewController alloc] init];
storeViewController.delegate = self;
NSString *escapedResourceSpecifier = [url.resourceSpecifier stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSRange appIDRange = [escapedResourceSpecifier rangeOfString:@"id"];
NSRange appQuestionMarkRange = [escapedResourceSpecifier rangeOfString:@"?"];
if (appIDRange.location != NSNotFound && appQuestionMarkRange.location != NSNotFound) {
appID = [escapedResourceSpecifier substringWithRange:NSMakeRange(appIDRange.location + 2, appQuestionMarkRange.location - (appIDRange.location + 2))];
}
NSDictionary *parameters = @{SKStoreProductParameterITunesItemIdentifier:[NSNumber numberWithInteger:[appID intValue]]};
[storeViewController loadProductWithParameters:parameters
completionBlock:^(BOOL result, NSError *error) {
if (result) {
[self.inboxVC presentViewController:storeViewController animated:YES completion:nil];
}
}];
} else {
[[UIApplication sharedApplication] openURL:url];
}
[WLAnalyticsManager logUrgentEventWithEventId:@"NB_CUSTOM_ACTION" pageId:@"APP_DOWNLOAD" actionMetadata:@{@"result":@[@"APPSTORE"], @"session_uuid":self.inboxVC.session_uuid, @"url": [url absoluteString]}];
}
#pragma mark - SKStoreProductViewControllerDelegate
////////////////////////////////////////////////////////////////////////////////
-(void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController
{
[viewController dismissViewControllerAnimated:YES completion:nil];
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <MessageUI/MessageUI.h>
#import "Warply.h"
@interface WLSMSActionHandlerDeprecated : NSObject <MFMessageComposeViewControllerDelegate, WLActionHandler>
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "WLSMSActionHandlerDeprecated.h"
#import "WLGlobals.h"
#import "WLInboxItemViewController.h"
#import "UIViewController+WLAdditions.h"
@interface WLSMSActionHandlerDeprecated ()
@property (nonatomic , weak) WLInboxItemViewController *inboxVC;
@end
@implementation WLSMSActionHandlerDeprecated
#pragma mark - Static Methods
///////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)canHandleActionUrl:(NSURL *)url
{
return [[url scheme] isEqualToString: @"rsms"];
}
#pragma mark - Override Methods
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)handleActionUrl:(NSURL *)url
{
self.inboxVC = (WLInboxItemViewController *)[([UIApplication sharedApplication].delegate).window.rootViewController topModalViewController];
NSArray *args = [url.resourceSpecifier componentsSeparatedByString:@"/"];
if (args == nil)
return;
if ([args count] < 4)
return;
MFMessageComposeViewController *smsController = [[MFMessageComposeViewController alloc] init];
@try {
[smsController setRecipients:[NSArray arrayWithObject:[args objectAtIndex:4]]];
//[smsController setBody:[NSString stringWithFormat:@"Hello from %@", BRAND_NAME]];
if ([args count] > 4) {
NSString *body = [[args objectAtIndex:5] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[smsController setBody:body];
}
[smsController setMessageComposeDelegate:self];
[_inboxVC presentViewController:smsController animated:YES completion:nil];
}
@finally {
}
}
#pragma mark - MFMessageComposeViewControllerDelegate
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
WLInboxItemViewController *inboxItemViewController = (WLInboxItemViewController *)[([UIApplication sharedApplication].delegate).window.rootViewController topModalViewController];
NSString *resultString;
switch (result) {
case MessageComposeResultCancelled:
resultString = @"sms_cancelled";
break;
case MessageComposeResultFailed:
resultString = @"sms_failed";
break;
case MessageComposeResultSent:
resultString = @"sms_sent";
}
[WLAnalyticsManager logEventWithEventId:@"NB_ACTION" pageId:inboxItemViewController.session_uuid actionMetadata:[NSDictionary dictionaryWithObjectsAndKeys:resultString, @"sms_result", self.inboxVC.requestedUrl.absoluteString, @"action_url", nil]];
[controller dismissViewControllerAnimated:YES completion:nil];
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <MessageUI/MessageUI.h>
#import "Warply.h"
@interface WLSMSActionHanlder : NSObject <MFMessageComposeViewControllerDelegate, WLActionHandler>
@end
\ No newline at end of file
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "WLSMSActionHanlder.h"
#import "WLGlobals.h"
#import "WLAnalyticsManager.h"
#import "WLInboxItemViewController.h"
#import "WLBaseItem.h"
#import "UIViewController+WLAdditions.h"
@interface WLSMSActionHanlder ()
@property (nonatomic, weak) WLInboxItemViewController *inboxVC;
@end
@implementation WLSMSActionHanlder
#pragma mark - Static Methods
///////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)canHandleActionUrl:(NSURL *)url
{
return [url.scheme isEqualToString: @"sms"];
}
#pragma mark - Override Methods
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)handleActionUrl:(NSURL *)url
{
UINavigationController *inboxNavCon = (UINavigationController *)[([UIApplication sharedApplication].delegate).window.rootViewController topModalViewController];
self.inboxVC = [inboxNavCon.viewControllers objectAtIndex:0];
if (![MFMessageComposeViewController canSendText]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"This device does not support text messages", @"Warply") message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"Warply") otherButtonTitles:nil];
[alert show];
return;
}
WLLOG(@"SMS URI: %@", url.absoluteString);
if (url.resourceSpecifier == nil) {
return;
}
NSString *escapedResourceSpecifier = [url.resourceSpecifier stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSArray *args = [escapedResourceSpecifier componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"?&"]];
NSString *recipientsString = [args objectAtIndex:0];
NSArray *recipients = [recipientsString componentsSeparatedByString:@","];
NSString *bodyString = nil;
for (NSString *argument in args) {
if ([argument isEqualToString:recipientsString]) {
continue;
}
NSRange bodyKeyRange = [argument rangeOfString:@"body="];
if (bodyKeyRange.location != NSNotFound) {
bodyString = [argument substringFromIndex:bodyKeyRange.length];
}
}
MFMessageComposeViewController *smsController = [[MFMessageComposeViewController alloc] init];
[smsController setRecipients:recipients];
[smsController setBody:bodyString];
[smsController setMessageComposeDelegate:self];
[_inboxVC presentViewController:smsController animated:YES completion:nil];
}
#pragma mark - MFMessageComposeViewControllerDelegate
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
NSArray *results;
switch (result) {
case MessageComposeResultCancelled:
results = @[@"sms_prompt_clicked", @"sms_cancelled"];
break;
case MessageComposeResultFailed:
results = @[@"sms_prompt_clicked", @"sms_failed"];
break;
case MessageComposeResultSent:
results = @[@"sms_prompt_clicked", @"sms_sent"];
}
[WLAnalyticsManager logUrgentEventWithEventId:@"NB_CUSTOM_ACTION" pageId:@"SMS" actionMetadata:@{@"session_uuid": self.inboxVC.session_uuid, @"result":results}];
[controller dismissViewControllerAnimated:YES completion:nil];
}
@end
// 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 Managing Security Policy
///-------------------------------
/**
The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. A security policy configured with `AFSSLPinningModePublicKey` or `AFSSLPinningModeCertificate` can only be applied on a session manager initialized with a secure base URL (i.e. https). Applying a security policy with pinning enabled on an insecure session manager throws an `Invalid Security Policy` exception.
*/
@property (nonatomic, strong) AFSecurityPolicy *securityPolicy;
///---------------------
/// @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];
}
@dynamic securityPolicy;
- (void)setSecurityPolicy:(AFSecurityPolicy *)securityPolicy {
if (securityPolicy.SSLPinningMode != AFSSLPinningModeNone && ![self.baseURL.scheme isEqualToString:@"https"]) {
NSString *pinningMode = @"Unknown Pinning Mode";
switch (securityPolicy.SSLPinningMode) {
case AFSSLPinningModeNone: pinningMode = @"AFSSLPinningModeNone"; break;
case AFSSLPinningModeCertificate: pinningMode = @"AFSSLPinningModeCertificate"; break;
case AFSSLPinningModePublicKey: pinningMode = @"AFSSLPinningModePublicKey"; break;
}
NSString *reason = [NSString stringWithFormat:@"A security policy configured with `%@` can only be applied on a manager with a secure base URL (i.e. https)", pinningMode];
@throw [NSException exceptionWithName:@"Invalid Security Policy" reason:reason userInfo:nil];
}
[super setSecurityPolicy:securityPolicy];
}
#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;
/**
* Initializes an instance of a network reachability manager
*
* @return nil as this method is unavailable
*/
- (nullable instancetype)init NS_UNAVAILABLE;
///--------------------------------------------------
/// @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;
SecPolicyRef policy = nil;
SecTrustRef allowedTrust = nil;
SecTrustResultType result;
allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
__Require_Quiet(allowedCertificate != NULL, _out);
policy = SecPolicyCreateBasicX509();
__Require_noErr_Quiet(SecTrustCreateWithCertificates(allowedCertificate, 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 (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"];
}
if (![NSJSONSerialization isValidJSONObject:parameters]) {
if (error) {
NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"The `parameters` argument is not valid JSON.", @"AFNetworking", nil)};
*error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
}
return nil;
}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error];
if (!jsonData) {
return nil;
}
[mutableRequest setHTTPBody:jsonData];
}
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"];
}
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error];
if (!plistData) {
return nil;
}
[mutableRequest setHTTPBody:plistData];
}
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;
@property (nonatomic, assign) NSStringEncoding stringEncoding DEPRECATED_MSG_ATTRIBUTE("The string encoding is never used. AFHTTPResponseSerializer only validates status codes and content types but does not try to decode the received data in any way.");
/**
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.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;
}
}
// 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) {
return nil;
}
NSError *serializationError = nil;
id responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
if (!responseObject)
{
if (error) {
*error = AFErrorWithUnderlyingError(serializationError, *error);
}
return nil;
}
if (self.removesKeysWithNullValues) {
return AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions);
}
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 = [super copyWithZone:zone];
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 (!document)
{
if (error) {
*error = AFErrorWithUnderlyingError(serializationError, *error);
}
return nil;
}
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 = [super copyWithZone:zone];
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;
}
}
if (!data) {
return nil;
}
NSError *serializationError = nil;
id responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError];
if (!responseObject)
{
if (error) {
*error = AFErrorWithUnderlyingError(serializationError, *error);
}
return nil;
}
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 = [super copyWithZone:zone];
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 = [super copyWithZone:zone];
#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 = [super copyWithZone:zone];
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>
- (instancetype)initWithTask:(NSURLSessionTask *)task;
@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)initWithTask:(NSURLSessionTask *)task {
self = [super init];
if (!self) {
return nil;
}
_mutableData = [NSMutableData data];
_uploadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil];
_downloadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil];
__weak __typeof__(task) weakTask = task;
for (NSProgress *progress in @[ _uploadProgress, _downloadProgress ])
{
progress.totalUnitCount = NSURLSessionTransferSizeUnknown;
progress.cancellable = YES;
progress.cancellationHandler = ^{
[weakTask cancel];
};
progress.pausable = YES;
progress.pausingHandler = ^{
[weakTask suspend];
};
if ([progress respondsToSelector:@selector(setResumingHandler:)]) {
progress.resumingHandler = ^{
[weakTask resume];
};
}
[progress addObserver:self
forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
options:NSKeyValueObservingOptionNew
context:NULL];
}
return self;
}
- (void)dealloc {
[self.downloadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))];
[self.uploadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))];
}
#pragma mark - NSProgress Tracking
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
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 - NSURLSessionDataDelegate
- (void)URLSession:(__unused NSURLSession *)session
dataTask:(__unused NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data
{
self.downloadProgress.totalUnitCount = dataTask.countOfBytesExpectedToReceive;
self.downloadProgress.completedUnitCount = dataTask.countOfBytesReceived;
[self.mutableData appendData:data];
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didSendBodyData:(int64_t)bytesSent
totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend;
self.uploadProgress.completedUnitCount = task.countOfBytesSent;
}
#pragma mark - NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
self.downloadProgress.totalUnitCount = totalBytesExpectedToWrite;
self.downloadProgress.completedUnitCount = totalBytesWritten;
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
self.downloadProgress.totalUnitCount = expectedTotalBytes;
self.downloadProgress.completedUnitCount = fileOffset;
}
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
self.downloadFileURL = nil;
if (self.downloadTaskDidFinishDownloading) {
self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location);
if (self.downloadFileURL) {
NSError *fileManagerError = nil;
if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&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;
[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] initWithTask:dataTask];
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] initWithTask:uploadTask];
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] initWithTask:downloadTask];
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);
[self.lock lock];
[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 {
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];
}
}
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task];
if (delegate) {
[delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalBytesExpectedToSend];
}
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;
if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&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
{
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
if (delegate) {
[delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite: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
{
AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask];
if (delegate) {
[delegate URLSession:session downloadTask:downloadTask didResumeAtOffset:fileOffset expectedTotalBytes: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
// AFAutoPurgingImageCache.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <TargetConditionals.h>
#import <Foundation/Foundation.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
The `AFImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously.
*/
@protocol AFImageCache <NSObject>
/**
Adds the image to the cache with the given identifier.
@param image The image to cache.
@param identifier The unique identifier for the image in the cache.
*/
- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier;
/**
Removes the image from the cache matching the given identifier.
@param identifier The unique identifier for the image in the cache.
@return A BOOL indicating whether or not the image was removed from the cache.
*/
- (BOOL)removeImageWithIdentifier:(NSString *)identifier;
/**
Removes all images from the cache.
@return A BOOL indicating whether or not all images were removed from the cache.
*/
- (BOOL)removeAllImages;
/**
Returns the image in the cache associated with the given identifier.
@param identifier The unique identifier for the image in the cache.
@return An image for the matching identifier, or nil.
*/
- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier;
@end
/**
The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and fetching images from a cache given an `NSURLRequest` and additional identifier.
*/
@protocol AFImageRequestCache <AFImageCache>
/**
Adds the image to the cache using an identifier created from the request and additional identifier.
@param image The image to cache.
@param request The unique URL request identifing the image asset.
@param identifier The additional identifier to apply to the URL request to identify the image.
*/
- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
/**
Removes the image from the cache using an identifier created from the request and additional identifier.
@param request The unique URL request identifing the image asset.
@param identifier The additional identifier to apply to the URL request to identify the image.
@return A BOOL indicating whether or not all images were removed from the cache.
*/
- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
/**
Returns the image from the cache associated with an identifier created from the request and additional identifier.
@param request The unique URL request identifing the image asset.
@param identifier The additional identifier to apply to the URL request to identify the image.
@return An image for the matching request and identifier, or nil.
*/
- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier;
@end
/**
The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated.
*/
@interface AFAutoPurgingImageCache : NSObject <AFImageRequestCache>
/**
The total memory capacity of the cache in bytes.
*/
@property (nonatomic, assign) UInt64 memoryCapacity;
/**
The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit.
*/
@property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge;
/**
The current total memory usage in bytes of all images stored within the cache.
*/
@property (nonatomic, assign, readonly) UInt64 memoryUsage;
/**
Initialies the `AutoPurgingImageCache` instance with default values for memory capacity and preferred memory usage after purge limit. `memoryCapcity` defaults to `100 MB`. `preferredMemoryUsageAfterPurge` defaults to `60 MB`.
@return The new `AutoPurgingImageCache` instance.
*/
- (instancetype)init;
/**
Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage
after purge limit.
@param memoryCapacity The total memory capacity of the cache in bytes.
@param preferredMemoryCapacity The preferred memory usage after purge in bytes.
@return The new `AutoPurgingImageCache` instance.
*/
- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity;
@end
NS_ASSUME_NONNULL_END
#endif
// AFAutoPurgingImageCache.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import "AFAutoPurgingImageCache.h"
@interface AFCachedImage : NSObject
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) NSString *identifier;
@property (nonatomic, assign) UInt64 totalBytes;
@property (nonatomic, strong) NSDate *lastAccessDate;
@property (nonatomic, assign) UInt64 currentMemoryUsage;
@end
@implementation AFCachedImage
-(instancetype)initWithImage:(UIImage *)image identifier:(NSString *)identifier {
if (self = [self init]) {
self.image = image;
self.identifier = identifier;
CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale);
CGFloat bytesPerPixel = 4.0;
CGFloat bytesPerSize = imageSize.width * imageSize.height;
self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerSize;
self.lastAccessDate = [NSDate date];
}
return self;
}
- (UIImage*)accessImage {
self.lastAccessDate = [NSDate date];
return self.image;
}
- (NSString *)description {
NSString *descriptionString = [NSString stringWithFormat:@"Idenfitier: %@ lastAccessDate: %@ ", self.identifier, self.lastAccessDate];
return descriptionString;
}
@end
@interface AFAutoPurgingImageCache ()
@property (nonatomic, strong) NSMutableDictionary <NSString* , AFCachedImage*> *cachedImages;
@property (nonatomic, assign) UInt64 currentMemoryUsage;
@property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
@end
@implementation AFAutoPurgingImageCache
- (instancetype)init {
return [self initWithMemoryCapacity:100 * 1024 * 1024 preferredMemoryCapacity:60 * 1024 * 1024];
}
- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity {
if (self = [super init]) {
self.memoryCapacity = memoryCapacity;
self.preferredMemoryUsageAfterPurge = preferredMemoryCapacity;
self.cachedImages = [[NSMutableDictionary alloc] init];
NSString *queueName = [NSString stringWithFormat:@"com.alamofire.autopurgingimagecache-%@", [[NSUUID UUID] UUIDString]];
self.synchronizationQueue = dispatch_queue_create([queueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT);
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(removeAllImages)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (UInt64)memoryUsage {
__block UInt64 result = 0;
dispatch_sync(self.synchronizationQueue, ^{
result = self.currentMemoryUsage;
});
return result;
}
- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier {
dispatch_barrier_async(self.synchronizationQueue, ^{
AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier];
AFCachedImage *previousCachedImage = self.cachedImages[identifier];
if (previousCachedImage != nil) {
self.currentMemoryUsage -= previousCachedImage.totalBytes;
}
self.cachedImages[identifier] = cacheImage;
self.currentMemoryUsage += cacheImage.totalBytes;
});
dispatch_barrier_async(self.synchronizationQueue, ^{
if (self.currentMemoryUsage > self.memoryCapacity) {
UInt64 bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge;
NSMutableArray <AFCachedImage*> *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate"
ascending:YES];
[sortedImages sortUsingDescriptors:@[sortDescriptor]];
UInt64 bytesPurged = 0;
for (AFCachedImage *cachedImage in sortedImages) {
[self.cachedImages removeObjectForKey:cachedImage.identifier];
bytesPurged += cachedImage.totalBytes;
if (bytesPurged >= bytesToPurge) {
break ;
}
}
self.currentMemoryUsage -= bytesPurged;
}
});
}
- (BOOL)removeImageWithIdentifier:(NSString *)identifier {
__block BOOL removed = NO;
dispatch_barrier_sync(self.synchronizationQueue, ^{
AFCachedImage *cachedImage = self.cachedImages[identifier];
if (cachedImage != nil) {
[self.cachedImages removeObjectForKey:identifier];
self.currentMemoryUsage -= cachedImage.totalBytes;
removed = YES;
}
});
return removed;
}
- (BOOL)removeAllImages {
__block BOOL removed = NO;
dispatch_barrier_sync(self.synchronizationQueue, ^{
if (self.cachedImages.count > 0) {
[self.cachedImages removeAllObjects];
self.currentMemoryUsage = 0;
removed = YES;
}
});
return removed;
}
- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier {
__block UIImage *image = nil;
dispatch_sync(self.synchronizationQueue, ^{
AFCachedImage *cachedImage = self.cachedImages[identifier];
image = [cachedImage accessImage];
});
return image;
}
- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
[self addImage:image withIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
}
- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
return [self removeImageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
}
- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier {
return [self imageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]];
}
- (NSString *)imageCacheKeyFromURLRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)additionalIdentifier {
NSString *key = request.URL.absoluteString;
if (additionalIdentifier != nil) {
key = [key stringByAppendingString:additionalIdentifier];
}
return key;
}
@end
#endif
// AFImageDownloader.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import <Foundation/Foundation.h>
#import "AFAutoPurgingImageCache.h"
#import "AFHTTPSessionManager.h"
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, AFImageDownloadPrioritization) {
AFImageDownloadPrioritizationFIFO,
AFImageDownloadPrioritizationLIFO
};
/**
The `AFImageDownloadReceipt` is an object vended by the `AFImageDownloader` when starting a data task. It can be used to cancel active tasks running on the `AFImageDownloader` session. As a general rule, image data tasks should be cancelled using the `AFImageDownloadReceipt` instead of calling `cancel` directly on the `task` itself. The `AFImageDownloader` is optimized to handle duplicate task scenarios as well as pending versus active downloads.
*/
@interface AFImageDownloadReceipt : NSObject
/**
The data task created by the `AFImageDownloader`.
*/
@property (nonatomic, strong) NSURLSessionDataTask *task;
/**
The unique identifier for the success and failure blocks when duplicate requests are made.
*/
@property (nonatomic, strong) NSUUID *receiptID;
@end
/** The `AFImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying `NSURLCache` as well as the in-memory image cache. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation.
*/
@interface AFImageDownloader : NSObject
/**
The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default.
*/
@property (nonatomic, strong, nullable) id <AFImageRequestCache> imageCache;
/**
The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads.
*/
@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
/**
Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default.
*/
@property (nonatomic, assign) AFImageDownloadPrioritization downloadPrioritizaton;
/**
The shared default instance of `AFImageDownloader` initialized with default values.
*/
+ (instancetype)defaultInstance;
/**
Creates a default `NSURLCache` with common usage parameter values.
@returns The default `NSURLCache` instance.
*/
+ (NSURLCache *)defaultURLCache;
/**
Default initializer
@return An instance of `AFImageDownloader` initialized with default values.
*/
- (instancetype)init;
/**
Initializes the `AFImageDownloader` instance with the given session manager, download prioritization, maximum active download count and image cache.
@param sessionManager The session manager to use to download images.
@param downloadPrioritization The download prioritization of the download queue.
@param maximumActiveDownloads The maximum number of active downloads allowed at any given time. Recommend `4`.
@param imageCache The image cache used to store all downloaded images in.
@return The new `AFImageDownloader` instance.
*/
- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager
downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization
maximumActiveDownloads:(NSInteger)maximumActiveDownloads
imageCache:(nullable id <AFImageRequestCache>)imageCache;
/**
Creates a data task using the `sessionManager` instance for the specified URL request.
If the same data task is already in the queue or currently being downloaded, the success and failure blocks are
appended to the already existing task. Once the task completes, all success or failure blocks attached to the
task are executed in the order they were added.
@param request The URL request.
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
@return The image download receipt for the data task if available. `nil` if the image is stored in the cache.
cache and the URL request cache policy allows the cache to be used.
*/
- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
/**
Creates a data task using the `sessionManager` instance for the specified URL request.
If the same data task is already in the queue or currently being downloaded, the success and failure blocks are
appended to the already existing task. Once the task completes, all success or failure blocks attached to the
task are executed in the order they were added.
@param request The URL request.
@param receiptID The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request.
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
@return The image download receipt for the data task if available. `nil` if the image is stored in the cache.
cache and the URL request cache policy allows the cache to be used.
*/
- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
withReceiptID:(NSUUID *)receiptID
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
/**
Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary.
If the data task is pending in the queue, it will be cancelled if no other success and failure blocks are registered with the data task. If the data task is currently executing or is already completed, the success and failure blocks are removed and will not be called when the task finishes.
@param imageDownloadReceipt The image download receipt to cancel.
*/
- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt;
@end
#endif
NS_ASSUME_NONNULL_END
// AFImageDownloader.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import "AFImageDownloader.h"
#import "AFHTTPSessionManager.h"
@interface AFImageDownloaderResponseHandler : NSObject
@property (nonatomic, strong) NSUUID *uuid;
@property (nonatomic, copy) void (^successBlock)(NSURLRequest*, NSHTTPURLResponse*, UIImage*);
@property (nonatomic, copy) void (^failureBlock)(NSURLRequest*, NSHTTPURLResponse*, NSError*);
@end
@implementation AFImageDownloaderResponseHandler
- (instancetype)initWithUUID:(NSUUID *)uuid
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure {
if (self = [self init]) {
self.uuid = uuid;
self.successBlock = success;
self.failureBlock = failure;
}
return self;
}
- (NSString *)description {
return [NSString stringWithFormat: @"<AFImageDownloaderResponseHandler>UUID: %@", [self.uuid UUIDString]];
}
@end
@interface AFImageDownloaderMergedTask : NSObject
@property (nonatomic, strong) NSString *URLIdentifier;
@property (nonatomic, strong) NSUUID *identifier;
@property (nonatomic, strong) NSURLSessionDataTask *task;
@property (nonatomic, strong) NSMutableArray <AFImageDownloaderResponseHandler*> *responseHandlers;
@end
@implementation AFImageDownloaderMergedTask
- (instancetype)initWithURLIdentifier:(NSString *)URLIdentifier identifier:(NSUUID *)identifier task:(NSURLSessionDataTask *)task {
if (self = [self init]) {
self.URLIdentifier = URLIdentifier;
self.task = task;
self.identifier = identifier;
self.responseHandlers = [[NSMutableArray alloc] init];
}
return self;
}
- (void)addResponseHandler:(AFImageDownloaderResponseHandler*)handler {
[self.responseHandlers addObject:handler];
}
- (void)removeResponseHandler:(AFImageDownloaderResponseHandler*)handler {
[self.responseHandlers removeObject:handler];
}
@end
@implementation AFImageDownloadReceipt
- (instancetype)initWithReceiptID:(NSUUID *)receiptID task:(NSURLSessionDataTask *)task {
if (self = [self init]) {
self.receiptID = receiptID;
self.task = task;
}
return self;
}
@end
@interface AFImageDownloader ()
@property (nonatomic, strong) dispatch_queue_t synchronizationQueue;
@property (nonatomic, strong) dispatch_queue_t responseQueue;
@property (nonatomic, assign) NSInteger maximumActiveDownloads;
@property (nonatomic, assign) NSInteger activeRequestCount;
@property (nonatomic, strong) NSMutableArray *queuedMergedTasks;
@property (nonatomic, strong) NSMutableDictionary *mergedTasks;
@end
@implementation AFImageDownloader
+ (NSURLCache *)defaultURLCache {
// It's been discovered that a crash will occur on certain versions
// of iOS if you customize the cache.
//
// More info can be found here: https://devforums.apple.com/message/1102182#1102182
//
// When iOS 7 support is dropped, this should be modified to use
// NSProcessInfo methods instead.
if ([[[UIDevice currentDevice] systemVersion] compare:@"8.2" options:NSNumericSearch] == NSOrderedAscending) {
return [NSURLCache sharedURLCache];
}
return [[NSURLCache alloc] initWithMemoryCapacity:20 * 1024 * 1024
diskCapacity:150 * 1024 * 1024
diskPath:@"com.alamofire.imagedownloader"];
}
+ (NSURLSessionConfiguration *)defaultURLSessionConfiguration {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//TODO set the default HTTP headers
configuration.HTTPShouldSetCookies = YES;
configuration.HTTPShouldUsePipelining = NO;
configuration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy;
configuration.allowsCellularAccess = YES;
configuration.timeoutIntervalForRequest = 60.0;
configuration.URLCache = [AFImageDownloader defaultURLCache];
return configuration;
}
- (instancetype)init {
NSURLSessionConfiguration *defaultConfiguration = [self.class defaultURLSessionConfiguration];
AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:defaultConfiguration];
sessionManager.responseSerializer = [AFImageResponseSerializer serializer];
return [self initWithSessionManager:sessionManager
downloadPrioritization:AFImageDownloadPrioritizationFIFO
maximumActiveDownloads:4
imageCache:[[AFAutoPurgingImageCache alloc] init]];
}
- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager
downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization
maximumActiveDownloads:(NSInteger)maximumActiveDownloads
imageCache:(id <AFImageRequestCache>)imageCache {
if (self = [super init]) {
self.sessionManager = sessionManager;
self.downloadPrioritizaton = downloadPrioritization;
self.maximumActiveDownloads = maximumActiveDownloads;
self.imageCache = imageCache;
self.queuedMergedTasks = [[NSMutableArray alloc] init];
self.mergedTasks = [[NSMutableDictionary alloc] init];
self.activeRequestCount = 0;
NSString *name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.synchronizationqueue-%@", [[NSUUID UUID] UUIDString]];
self.synchronizationQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL);
name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.responsequeue-%@", [[NSUUID UUID] UUIDString]];
self.responseQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT);
}
return self;
}
+ (instancetype)defaultInstance {
static AFImageDownloader *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
success:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, UIImage * _Nonnull))success
failure:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, NSError * _Nonnull))failure {
return [self downloadImageForURLRequest:request withReceiptID:[NSUUID UUID] success:success failure:failure];
}
- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request
withReceiptID:(nonnull NSUUID *)receiptID
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure {
__block NSURLSessionDataTask *task = nil;
dispatch_sync(self.synchronizationQueue, ^{
NSString *URLIdentifier = request.URL.absoluteString;
if (URLIdentifier == nil) {
if (failure) {
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil];
dispatch_async(dispatch_get_main_queue(), ^{
failure(request, nil, error);
});
}
return;
}
// 1) Append the success and failure blocks to a pre-existing request if it already exists
AFImageDownloaderMergedTask *existingMergedTask = self.mergedTasks[URLIdentifier];
if (existingMergedTask != nil) {
AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID success:success failure:failure];
[existingMergedTask addResponseHandler:handler];
task = existingMergedTask.task;
return;
}
// 2) Attempt to load the image from the image cache if the cache policy allows it
switch (request.cachePolicy) {
case NSURLRequestUseProtocolCachePolicy:
case NSURLRequestReturnCacheDataElseLoad:
case NSURLRequestReturnCacheDataDontLoad: {
UIImage *cachedImage = [self.imageCache imageforRequest:request withAdditionalIdentifier:nil];
if (cachedImage != nil) {
if (success) {
dispatch_async(dispatch_get_main_queue(), ^{
success(request, nil, cachedImage);
});
}
return;
}
break;
}
default:
break;
}
// 3) Create the request and set up authentication, validation and response serialization
NSUUID *mergedTaskIdentifier = [NSUUID UUID];
NSURLSessionDataTask *createdTask;
__weak __typeof__(self) weakSelf = self;
createdTask = [self.sessionManager
dataTaskWithRequest:request
uploadProgress:nil
downloadProgress:nil
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
dispatch_async(self.responseQueue, ^{
__strong __typeof__(weakSelf) strongSelf = weakSelf;
AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
if ([mergedTask.identifier isEqual:mergedTaskIdentifier]) {
mergedTask = [strongSelf safelyRemoveMergedTaskWithURLIdentifier:URLIdentifier];
if (error) {
for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {
if (handler.failureBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
handler.failureBlock(request, (NSHTTPURLResponse*)response, error);
});
}
}
} else {
[strongSelf.imageCache addImage:responseObject forRequest:request withAdditionalIdentifier:nil];
for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) {
if (handler.successBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
handler.successBlock(request, (NSHTTPURLResponse*)response, responseObject);
});
}
}
}
}
[strongSelf safelyDecrementActiveTaskCount];
[strongSelf safelyStartNextTaskIfNecessary];
});
}];
// 4) Store the response handler for use when the request completes
AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID
success:success
failure:failure];
AFImageDownloaderMergedTask *mergedTask = [[AFImageDownloaderMergedTask alloc]
initWithURLIdentifier:URLIdentifier
identifier:mergedTaskIdentifier
task:createdTask];
[mergedTask addResponseHandler:handler];
self.mergedTasks[URLIdentifier] = mergedTask;
// 5) Either start the request or enqueue it depending on the current active request count
if ([self isActiveRequestCountBelowMaximumLimit]) {
[self startMergedTask:mergedTask];
} else {
[self enqueueMergedTask:mergedTask];
}
task = mergedTask.task;
});
if (task) {
return [[AFImageDownloadReceipt alloc] initWithReceiptID:receiptID task:task];
} else {
return nil;
}
}
- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt {
dispatch_sync(self.synchronizationQueue, ^{
NSString *URLIdentifier = imageDownloadReceipt.task.originalRequest.URL.absoluteString;
AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
NSUInteger index = [mergedTask.responseHandlers indexOfObjectPassingTest:^BOOL(AFImageDownloaderResponseHandler * _Nonnull handler, __unused NSUInteger idx, __unused BOOL * _Nonnull stop) {
return handler.uuid == imageDownloadReceipt.receiptID;
}];
if (index != NSNotFound) {
AFImageDownloaderResponseHandler *handler = mergedTask.responseHandlers[index];
[mergedTask removeResponseHandler:handler];
NSString *failureReason = [NSString stringWithFormat:@"ImageDownloader cancelled URL request: %@",imageDownloadReceipt.task.originalRequest.URL.absoluteString];
NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey:failureReason};
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
if (handler.failureBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
handler.failureBlock(imageDownloadReceipt.task.originalRequest, nil, error);
});
}
}
if (mergedTask.responseHandlers.count == 0 && mergedTask.task.state == NSURLSessionTaskStateSuspended) {
[mergedTask.task cancel];
[self removeMergedTaskWithURLIdentifier:URLIdentifier];
}
});
}
- (AFImageDownloaderMergedTask*)safelyRemoveMergedTaskWithURLIdentifier:(NSString *)URLIdentifier {
__block AFImageDownloaderMergedTask *mergedTask = nil;
dispatch_sync(self.synchronizationQueue, ^{
mergedTask = [self removeMergedTaskWithURLIdentifier:URLIdentifier];
});
return mergedTask;
}
//This method should only be called from safely within the synchronizationQueue
- (AFImageDownloaderMergedTask *)removeMergedTaskWithURLIdentifier:(NSString *)URLIdentifier {
AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier];
[self.mergedTasks removeObjectForKey:URLIdentifier];
return mergedTask;
}
- (void)safelyDecrementActiveTaskCount {
dispatch_sync(self.synchronizationQueue, ^{
if (self.activeRequestCount > 0) {
self.activeRequestCount -= 1;
}
});
}
- (void)safelyStartNextTaskIfNecessary {
dispatch_sync(self.synchronizationQueue, ^{
if ([self isActiveRequestCountBelowMaximumLimit]) {
while (self.queuedMergedTasks.count > 0) {
AFImageDownloaderMergedTask *mergedTask = [self dequeueMergedTask];
if (mergedTask.task.state == NSURLSessionTaskStateSuspended) {
[self startMergedTask:mergedTask];
break;
}
}
}
});
}
- (void)startMergedTask:(AFImageDownloaderMergedTask *)mergedTask {
[mergedTask.task resume];
++self.activeRequestCount;
}
- (void)enqueueMergedTask:(AFImageDownloaderMergedTask *)mergedTask {
switch (self.downloadPrioritizaton) {
case AFImageDownloadPrioritizationFIFO:
[self.queuedMergedTasks addObject:mergedTask];
break;
case AFImageDownloadPrioritizationLIFO:
[self.queuedMergedTasks insertObject:mergedTask atIndex:0];
break;
}
}
- (AFImageDownloaderMergedTask *)dequeueMergedTask {
AFImageDownloaderMergedTask *mergedTask = nil;
mergedTask = [self.queuedMergedTasks firstObject];
[self.queuedMergedTasks removeObject:mergedTask];
return mergedTask;
}
- (BOOL)isActiveRequestCountBelowMaximumLimit {
return self.activeRequestCount < self.maximumActiveDownloads;
}
@end
#endif
// AFNetworkActivityIndicatorManager.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <TargetConditionals.h>
#if TARGET_OS_IOS
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
`AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a session task has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero.
You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code:
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
By setting `enabled` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself.
See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information:
http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44
*/
NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.")
@interface AFNetworkActivityIndicatorManager : NSObject
/**
A Boolean value indicating whether the manager is enabled.
If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO.
*/
@property (nonatomic, assign, getter = isEnabled) BOOL enabled;
/**
A Boolean value indicating whether the network activity indicator manager is currently active.
*/
@property (readonly, nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
/**
A time interval indicating the minimum duration of networking activity that should occur before the activity indicator is displayed. The default value 1 second. If the network activity indicator should be displayed immediately when network activity occurs, this value should be set to 0 seconds.
Apple's HIG describes the following:
> Display the network activity indicator to provide feedback when your app accesses the network for more than a couple of seconds. If the operation finishes sooner than that, you don’t have to show the network activity indicator, because the indicator is likely to disappear before users notice its presence.
*/
@property (nonatomic, assign) NSTimeInterval activationDelay;
/**
A time interval indicating the duration of time of no networking activity required before the activity indicator is disabled. This allows for continuous display of the network activity indicator across multiple requests. The default value is 0.17 seconds.
*/
@property (nonatomic, assign) NSTimeInterval completionDelay;
/**
Returns the shared network activity indicator manager object for the system.
@return The systemwide network activity indicator manager.
*/
+ (instancetype)sharedManager;
/**
Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator.
*/
- (void)incrementActivityCount;
/**
Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator.
*/
- (void)decrementActivityCount;
/**
Set the a custom method to be executed when the network activity indicator manager should be hidden/shown. By default, this is null, and the UIApplication Network Activity Indicator will be managed automatically. If this block is set, it is the responsiblity of the caller to manager the network activity indicator going forward.
@param block A block to be executed when the network activity indicator status changes.
*/
- (void)setNetworkingActivityActionWithBlock:(nullable void (^)(BOOL networkActivityIndicatorVisible))block;
@end
NS_ASSUME_NONNULL_END
#endif
// AFNetworkActivityIndicatorManager.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFNetworkActivityIndicatorManager.h"
#if TARGET_OS_IOS
#import "AFURLSessionManager.h"
typedef NS_ENUM(NSInteger, AFNetworkActivityManagerState) {
AFNetworkActivityManagerStateNotActive,
AFNetworkActivityManagerStateDelayingStart,
AFNetworkActivityManagerStateActive,
AFNetworkActivityManagerStateDelayingEnd
};
static NSTimeInterval const kDefaultAFNetworkActivityManagerActivationDelay = 1.0;
static NSTimeInterval const kDefaultAFNetworkActivityManagerCompletionDelay = 0.17;
static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) {
if ([[notification object] respondsToSelector:@selector(originalRequest)]) {
return [(NSURLSessionTask *)[notification object] originalRequest];
} else {
return nil;
}
}
typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisible);
@interface AFNetworkActivityIndicatorManager ()
@property (readwrite, nonatomic, assign) NSInteger activityCount;
@property (readwrite, nonatomic, strong) NSTimer *activationDelayTimer;
@property (readwrite, nonatomic, strong) NSTimer *completionDelayTimer;
@property (readonly, nonatomic, getter = isNetworkActivityOccurring) BOOL networkActivityOccurring;
@property (nonatomic, copy) AFNetworkActivityActionBlock networkActivityActionBlock;
@property (nonatomic, assign) AFNetworkActivityManagerState currentState;
@property (nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
- (void)updateCurrentStateForNetworkActivityChange;
@end
@implementation AFNetworkActivityIndicatorManager
+ (instancetype)sharedManager {
static AFNetworkActivityIndicatorManager *_sharedManager = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedManager = [[self alloc] init];
});
return _sharedManager;
}
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
}
self.currentState = AFNetworkActivityManagerStateNotActive;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil];
self.activationDelay = kDefaultAFNetworkActivityManagerActivationDelay;
self.completionDelay = kDefaultAFNetworkActivityManagerCompletionDelay;
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[_activationDelayTimer invalidate];
[_completionDelayTimer invalidate];
}
- (void)setEnabled:(BOOL)enabled {
_enabled = enabled;
if (enabled == NO) {
[self setCurrentState:AFNetworkActivityManagerStateNotActive];
}
}
- (void)setNetworkingActivityActionWithBlock:(void (^)(BOOL networkActivityIndicatorVisible))block {
self.networkActivityActionBlock = block;
}
- (BOOL)isNetworkActivityOccurring {
@synchronized(self) {
return self.activityCount > 0;
}
}
- (void)setNetworkActivityIndicatorVisible:(BOOL)networkActivityIndicatorVisible {
if (_networkActivityIndicatorVisible != networkActivityIndicatorVisible) {
[self willChangeValueForKey:@"networkActivityIndicatorVisible"];
@synchronized(self) {
_networkActivityIndicatorVisible = networkActivityIndicatorVisible;
}
[self didChangeValueForKey:@"networkActivityIndicatorVisible"];
if (self.networkActivityActionBlock) {
self.networkActivityActionBlock(networkActivityIndicatorVisible);
} else {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:networkActivityIndicatorVisible];
}
}
}
- (void)setActivityCount:(NSInteger)activityCount {
@synchronized(self) {
_activityCount = activityCount;
}
dispatch_async(dispatch_get_main_queue(), ^{
[self updateCurrentStateForNetworkActivityChange];
});
}
- (void)incrementActivityCount {
[self willChangeValueForKey:@"activityCount"];
@synchronized(self) {
_activityCount++;
}
[self didChangeValueForKey:@"activityCount"];
dispatch_async(dispatch_get_main_queue(), ^{
[self updateCurrentStateForNetworkActivityChange];
});
}
- (void)decrementActivityCount {
[self willChangeValueForKey:@"activityCount"];
@synchronized(self) {
_activityCount = MAX(_activityCount - 1, 0);
}
[self didChangeValueForKey:@"activityCount"];
dispatch_async(dispatch_get_main_queue(), ^{
[self updateCurrentStateForNetworkActivityChange];
});
}
- (void)networkRequestDidStart:(NSNotification *)notification {
if ([AFNetworkRequestFromNotification(notification) URL]) {
[self incrementActivityCount];
}
}
- (void)networkRequestDidFinish:(NSNotification *)notification {
if ([AFNetworkRequestFromNotification(notification) URL]) {
[self decrementActivityCount];
}
}
#pragma mark - Internal State Management
- (void)setCurrentState:(AFNetworkActivityManagerState)currentState {
@synchronized(self) {
if (_currentState != currentState) {
[self willChangeValueForKey:@"currentState"];
_currentState = currentState;
switch (currentState) {
case AFNetworkActivityManagerStateNotActive:
[self cancelActivationDelayTimer];
[self cancelCompletionDelayTimer];
[self setNetworkActivityIndicatorVisible:NO];
break;
case AFNetworkActivityManagerStateDelayingStart:
[self startActivationDelayTimer];
break;
case AFNetworkActivityManagerStateActive:
[self cancelCompletionDelayTimer];
[self setNetworkActivityIndicatorVisible:YES];
break;
case AFNetworkActivityManagerStateDelayingEnd:
[self startCompletionDelayTimer];
break;
}
[self didChangeValueForKey:@"currentState"];
}
}
}
- (void)updateCurrentStateForNetworkActivityChange {
if (self.enabled) {
switch (self.currentState) {
case AFNetworkActivityManagerStateNotActive:
if (self.isNetworkActivityOccurring) {
[self setCurrentState:AFNetworkActivityManagerStateDelayingStart];
}
break;
case AFNetworkActivityManagerStateDelayingStart:
//No op. Let the delay timer finish out.
break;
case AFNetworkActivityManagerStateActive:
if (!self.isNetworkActivityOccurring) {
[self setCurrentState:AFNetworkActivityManagerStateDelayingEnd];
}
break;
case AFNetworkActivityManagerStateDelayingEnd:
if (self.isNetworkActivityOccurring) {
[self setCurrentState:AFNetworkActivityManagerStateActive];
}
break;
}
}
}
- (void)startActivationDelayTimer {
self.activationDelayTimer = [NSTimer
timerWithTimeInterval:self.activationDelay target:self selector:@selector(activationDelayTimerFired) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:self.activationDelayTimer forMode:NSRunLoopCommonModes];
}
- (void)activationDelayTimerFired {
if (self.networkActivityOccurring) {
[self setCurrentState:AFNetworkActivityManagerStateActive];
} else {
[self setCurrentState:AFNetworkActivityManagerStateNotActive];
}
}
- (void)startCompletionDelayTimer {
[self.completionDelayTimer invalidate];
self.completionDelayTimer = [NSTimer timerWithTimeInterval:self.completionDelay target:self selector:@selector(completionDelayTimerFired) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:self.completionDelayTimer forMode:NSRunLoopCommonModes];
}
- (void)completionDelayTimerFired {
[self setCurrentState:AFNetworkActivityManagerStateNotActive];
}
- (void)cancelActivationDelayTimer {
[self.activationDelayTimer invalidate];
}
- (void)cancelCompletionDelayTimer {
[self.completionDelayTimer invalidate];
}
@end
#endif
// UIActivityIndicatorView+AFNetworking.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import <UIKit/UIKit.h>
/**
This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a session task.
*/
@interface UIActivityIndicatorView (AFNetworking)
///----------------------------------
/// @name Animating for Session Tasks
///----------------------------------
/**
Binds the animating state to the state of the specified task.
@param task The task. If `nil`, automatic updating from any previously specified operation will be disabled.
*/
- (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task;
@end
#endif
// UIActivityIndicatorView+AFNetworking.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "UIActivityIndicatorView+AFNetworking.h"
#import <objc/runtime.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import "AFURLSessionManager.h"
@interface AFActivityIndicatorViewNotificationObserver : NSObject
@property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView;
- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView;
- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task;
@end
@implementation UIActivityIndicatorView (AFNetworking)
- (AFActivityIndicatorViewNotificationObserver *)af_notificationObserver {
AFActivityIndicatorViewNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver));
if (notificationObserver == nil) {
notificationObserver = [[AFActivityIndicatorViewNotificationObserver alloc] initWithActivityIndicatorView:self];
objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return notificationObserver;
}
- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
[[self af_notificationObserver] setAnimatingWithStateOfTask:task];
}
@end
@implementation AFActivityIndicatorViewNotificationObserver
- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView
{
self = [super init];
if (self) {
_activityIndicatorView = activityIndicatorView;
}
return self;
}
- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
if (task) {
if (task.state != NSURLSessionTaskStateCompleted) {
UIActivityIndicatorView *activityIndicatorView = self.activityIndicatorView;
if (task.state == NSURLSessionTaskStateRunning) {
[activityIndicatorView startAnimating];
} else {
[activityIndicatorView stopAnimating];
}
[notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task];
[notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task];
[notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidSuspendNotification object:task];
}
}
}
#pragma mark -
- (void)af_startAnimating {
dispatch_async(dispatch_get_main_queue(), ^{
[self.activityIndicatorView startAnimating];
});
}
- (void)af_stopAnimating {
dispatch_async(dispatch_get_main_queue(), ^{
[self.activityIndicatorView stopAnimating];
});
}
#pragma mark -
- (void)dealloc {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
}
@end
#endif
// UIButton+AFNetworking.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@class AFImageDownloader;
/**
This category adds methods to the UIKit framework's `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL.
@warning Compound values for control `state` (such as `UIControlStateHighlighted | UIControlStateDisabled`) are unsupported.
*/
@interface UIButton (AFNetworking)
///------------------------------------
/// @name Accessing the Image Downloader
///------------------------------------
/**
Set the shared image downloader used to download images.
@param imageDownloader The shared image downloader used to download images.
*/
+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader;
/**
The shared image downloader used to download images.
*/
+ (AFImageDownloader *)sharedImageDownloader;
///--------------------
/// @name Setting Image
///--------------------
/**
Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
@param state The control state.
@param url The URL used for the image request.
*/
- (void)setImageForState:(UIControlState)state
withURL:(NSURL *)url;
/**
Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
@param state The control state.
@param url The URL used for the image request.
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes.
*/
- (void)setImageForState:(UIControlState)state
withURL:(NSURL *)url
placeholderImage:(nullable UIImage *)placeholderImage;
/**
Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setImage:forState:` is applied.
@param state The control state.
@param urlRequest The URL request used for the image request.
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes.
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
*/
- (void)setImageForState:(UIControlState)state
withURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(nullable UIImage *)placeholderImage
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
///-------------------------------
/// @name Setting Background Image
///-------------------------------
/**
Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous background image request for the receiver will be cancelled.
If the background image is cached locally, the background image is set immediately, otherwise the specified placeholder background image will be set immediately, and then the remote background image will be set once the request is finished.
@param state The control state.
@param url The URL used for the background image request.
*/
- (void)setBackgroundImageForState:(UIControlState)state
withURL:(NSURL *)url;
/**
Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
@param state The control state.
@param url The URL used for the background image request.
@param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes.
*/
- (void)setBackgroundImageForState:(UIControlState)state
withURL:(NSURL *)url
placeholderImage:(nullable UIImage *)placeholderImage;
/**
Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled.
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setBackgroundImage:forState:` is applied.
@param state The control state.
@param urlRequest The URL request used for the image request.
@param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes.
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
*/
- (void)setBackgroundImageForState:(UIControlState)state
withURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(nullable UIImage *)placeholderImage
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
///------------------------------
/// @name Canceling Image Loading
///------------------------------
/**
Cancels any executing image task for the specified control state of the receiver, if one exists.
@param state The control state.
*/
- (void)cancelImageDownloadTaskForState:(UIControlState)state;
/**
Cancels any executing background image task for the specified control state of the receiver, if one exists.
@param state The control state.
*/
- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state;
@end
NS_ASSUME_NONNULL_END
#endif
// UIButton+AFNetworking.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "UIButton+AFNetworking.h"
#import <objc/runtime.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import "UIImageView+AFNetworking.h"
#import "AFImageDownloader.h"
@interface UIButton (_AFNetworking)
@end
@implementation UIButton (_AFNetworking)
#pragma mark -
static char AFImageDownloadReceiptNormal;
static char AFImageDownloadReceiptHighlighted;
static char AFImageDownloadReceiptSelected;
static char AFImageDownloadReceiptDisabled;
static const char * af_imageDownloadReceiptKeyForState(UIControlState state) {
switch (state) {
case UIControlStateHighlighted:
return &AFImageDownloadReceiptHighlighted;
case UIControlStateSelected:
return &AFImageDownloadReceiptSelected;
case UIControlStateDisabled:
return &AFImageDownloadReceiptDisabled;
case UIControlStateNormal:
default:
return &AFImageDownloadReceiptNormal;
}
}
- (AFImageDownloadReceipt *)af_imageDownloadReceiptForState:(UIControlState)state {
return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_imageDownloadReceiptKeyForState(state));
}
- (void)af_setImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt
forState:(UIControlState)state
{
objc_setAssociatedObject(self, af_imageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#pragma mark -
static char AFBackgroundImageDownloadReceiptNormal;
static char AFBackgroundImageDownloadReceiptHighlighted;
static char AFBackgroundImageDownloadReceiptSelected;
static char AFBackgroundImageDownloadReceiptDisabled;
static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState state) {
switch (state) {
case UIControlStateHighlighted:
return &AFBackgroundImageDownloadReceiptHighlighted;
case UIControlStateSelected:
return &AFBackgroundImageDownloadReceiptSelected;
case UIControlStateDisabled:
return &AFBackgroundImageDownloadReceiptDisabled;
case UIControlStateNormal:
default:
return &AFBackgroundImageDownloadReceiptNormal;
}
}
- (AFImageDownloadReceipt *)af_backgroundImageDownloadReceiptForState:(UIControlState)state {
return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state));
}
- (void)af_setBackgroundImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt
forState:(UIControlState)state
{
objc_setAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
#pragma mark -
@implementation UIButton (AFNetworking)
+ (AFImageDownloader *)sharedImageDownloader {
return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance];
}
+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader {
objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#pragma mark -
- (void)setImageForState:(UIControlState)state
withURL:(NSURL *)url
{
[self setImageForState:state withURL:url placeholderImage:nil];
}
- (void)setImageForState:(UIControlState)state
withURL:(NSURL *)url
placeholderImage:(UIImage *)placeholderImage
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
[self setImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
}
- (void)setImageForState:(UIControlState)state
withURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(nullable UIImage *)placeholderImage
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure
{
if ([self isActiveTaskURLEqualToURLRequest:urlRequest forState:state]) {
return;
}
[self cancelImageDownloadTaskForState:state];
AFImageDownloader *downloader = [[self class] sharedImageDownloader];
id <AFImageRequestCache> imageCache = downloader.imageCache;
//Use the image from the image cache if it exists
UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
if (cachedImage) {
if (success) {
success(urlRequest, nil, cachedImage);
} else {
[self setImage:cachedImage forState:state];
}
[self af_setImageDownloadReceipt:nil forState:state];
} else {
if (placeholderImage) {
[self setImage:placeholderImage forState:state];
}
__weak __typeof(self)weakSelf = self;
NSUUID *downloadID = [NSUUID UUID];
AFImageDownloadReceipt *receipt;
receipt = [downloader
downloadImageForURLRequest:urlRequest
withReceiptID:downloadID
success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
if (success) {
success(request, response, responseObject);
} else if(responseObject) {
[strongSelf setImage:responseObject forState:state];
}
[strongSelf af_setImageDownloadReceipt:nil forState:state];
}
}
failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
if (failure) {
failure(request, response, error);
}
[strongSelf af_setImageDownloadReceipt:nil forState:state];
}
}];
[self af_setImageDownloadReceipt:receipt forState:state];
}
}
#pragma mark -
- (void)setBackgroundImageForState:(UIControlState)state
withURL:(NSURL *)url
{
[self setBackgroundImageForState:state withURL:url placeholderImage:nil];
}
- (void)setBackgroundImageForState:(UIControlState)state
withURL:(NSURL *)url
placeholderImage:(nullable UIImage *)placeholderImage
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
[self setBackgroundImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
}
- (void)setBackgroundImageForState:(UIControlState)state
withURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(nullable UIImage *)placeholderImage
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure
{
if ([self isActiveBackgroundTaskURLEqualToURLRequest:urlRequest forState:state]) {
return;
}
[self cancelBackgroundImageDownloadTaskForState:state];
AFImageDownloader *downloader = [[self class] sharedImageDownloader];
id <AFImageRequestCache> imageCache = downloader.imageCache;
//Use the image from the image cache if it exists
UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
if (cachedImage) {
if (success) {
success(urlRequest, nil, cachedImage);
} else {
[self setBackgroundImage:cachedImage forState:state];
}
[self af_setBackgroundImageDownloadReceipt:nil forState:state];
} else {
if (placeholderImage) {
[self setBackgroundImage:placeholderImage forState:state];
}
__weak __typeof(self)weakSelf = self;
NSUUID *downloadID = [NSUUID UUID];
AFImageDownloadReceipt *receipt;
receipt = [downloader
downloadImageForURLRequest:urlRequest
withReceiptID:downloadID
success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
if (success) {
success(request, response, responseObject);
} else if(responseObject) {
[strongSelf setBackgroundImage:responseObject forState:state];
}
[strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state];
}
}
failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) {
if (failure) {
failure(request, response, error);
}
[strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state];
}
}];
[self af_setBackgroundImageDownloadReceipt:receipt forState:state];
}
}
#pragma mark -
- (void)cancelImageDownloadTaskForState:(UIControlState)state {
AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state];
if (receipt != nil) {
[[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt];
[self af_setImageDownloadReceipt:nil forState:state];
}
}
- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state {
AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state];
if (receipt != nil) {
[[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt];
[self af_setBackgroundImageDownloadReceipt:nil forState:state];
}
}
- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state {
AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state];
return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString];
}
- (BOOL)isActiveBackgroundTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state {
AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state];
return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString];
}
@end
#endif
//
// UIImage+AFNetworking.h
//
//
// Created by Paulo Ferreira on 08/07/15.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if TARGET_OS_IOS || TARGET_OS_TV
#import <UIKit/UIKit.h>
@interface UIImage (AFNetworking)
+ (UIImage*) safeImageWithData:(NSData*)data;
@end
#endif
// UIImageView+AFNetworking.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@class AFImageDownloader;
/**
This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL.
*/
@interface UIImageView (AFNetworking)
///------------------------------------
/// @name Accessing the Image Downloader
///------------------------------------
/**
Set the shared image downloader used to download images.
@param imageDownloader The shared image downloader used to download images.
*/
+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader;
/**
The shared image downloader used to download images.
*/
+ (AFImageDownloader *)sharedImageDownloader;
///--------------------
/// @name Setting Image
///--------------------
/**
Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
@param url The URL used for the image request.
*/
- (void)setImageWithURL:(NSURL *)url;
/**
Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`
@param url The URL used for the image request.
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
*/
- (void)setImageWithURL:(NSURL *)url
placeholderImage:(nullable UIImage *)placeholderImage;
/**
Asynchronously downloads an image from the specified URL request, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.
If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.
If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is applied.
@param urlRequest The URL request used for the image request.
@param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
@param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`.
@param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred.
*/
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(nullable UIImage *)placeholderImage
success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure;
/**
Cancels any executing image operation for the receiver, if one exists.
*/
- (void)cancelImageDownloadTask;
@end
NS_ASSUME_NONNULL_END
#endif
// UIImageView+AFNetworking.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "UIImageView+AFNetworking.h"
#import <objc/runtime.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import "AFImageDownloader.h"
@interface UIImageView (_AFNetworking)
@property (readwrite, nonatomic, strong, setter = af_setActiveImageDownloadReceipt:) AFImageDownloadReceipt *af_activeImageDownloadReceipt;
@end
@implementation UIImageView (_AFNetworking)
- (AFImageDownloadReceipt *)af_activeImageDownloadReceipt {
return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(af_activeImageDownloadReceipt));
}
- (void)af_setActiveImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt {
objc_setAssociatedObject(self, @selector(af_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
#pragma mark -
@implementation UIImageView (AFNetworking)
+ (AFImageDownloader *)sharedImageDownloader {
return objc_getAssociatedObject(self, @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance];
}
+ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader {
objc_setAssociatedObject(self, @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#pragma mark -
- (void)setImageWithURL:(NSURL *)url {
[self setImageWithURL:url placeholderImage:nil];
}
- (void)setImageWithURL:(NSURL *)url
placeholderImage:(UIImage *)placeholderImage
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
[self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil];
}
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
placeholderImage:(UIImage *)placeholderImage
success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success
failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure
{
if ([urlRequest URL] == nil) {
[self cancelImageDownloadTask];
self.image = placeholderImage;
return;
}
if ([self isActiveTaskURLEqualToURLRequest:urlRequest]){
return;
}
[self cancelImageDownloadTask];
AFImageDownloader *downloader = [[self class] sharedImageDownloader];
id <AFImageRequestCache> imageCache = downloader.imageCache;
//Use the image from the image cache if it exists
UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil];
if (cachedImage) {
if (success) {
success(urlRequest, nil, cachedImage);
} else {
self.image = cachedImage;
}
[self clearActiveDownloadInformation];
} else {
if (placeholderImage) {
self.image = placeholderImage;
}
__weak __typeof(self)weakSelf = self;
NSUUID *downloadID = [NSUUID UUID];
AFImageDownloadReceipt *receipt;
receipt = [downloader
downloadImageForURLRequest:urlRequest
withReceiptID:downloadID
success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) {
if (success) {
success(request, response, responseObject);
} else if(responseObject) {
strongSelf.image = responseObject;
}
[strongSelf clearActiveDownloadInformation];
}
}
failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) {
if (failure) {
failure(request, response, error);
}
[strongSelf clearActiveDownloadInformation];
}
}];
self.af_activeImageDownloadReceipt = receipt;
}
}
- (void)cancelImageDownloadTask {
if (self.af_activeImageDownloadReceipt != nil) {
[[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt];
[self clearActiveDownloadInformation];
}
}
- (void)clearActiveDownloadInformation {
self.af_activeImageDownloadReceipt = nil;
}
- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest {
return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString];
}
@end
#endif
// UIKit+AFNetworking.h
//
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if TARGET_OS_IOS || TARGET_OS_TV
#import <UIKit/UIKit.h>
#ifndef _UIKIT_AFNETWORKING_
#define _UIKIT_AFNETWORKING_
#if TARGET_OS_IOS
#import "AFAutoPurgingImageCache.h"
#import "AFImageDownloader.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "UIRefreshControl+AFNetworking.h"
#import "UIWebView+AFNetworking.h"
#endif
#import "UIActivityIndicatorView+AFNetworking.h"
#import "UIButton+AFNetworking.h"
#import "UIImageView+AFNetworking.h"
#import "UIProgressView+AFNetworking.h"
#endif /* _UIKIT_AFNETWORKING_ */
#endif
// UIProgressView+AFNetworking.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
This category adds methods to the UIKit framework's `UIProgressView` class. The methods in this category provide support for binding the progress to the upload and download progress of a session task.
*/
@interface UIProgressView (AFNetworking)
///------------------------------------
/// @name Setting Session Task Progress
///------------------------------------
/**
Binds the progress to the upload progress of the specified session task.
@param task The session task.
@param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
*/
- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
animated:(BOOL)animated;
/**
Binds the progress to the download progress of the specified session task.
@param task The session task.
@param animated `YES` if the change should be animated, `NO` if the change should happen immediately.
*/
- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
animated:(BOOL)animated;
@end
NS_ASSUME_NONNULL_END
#endif
// UIProgressView+AFNetworking.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "UIProgressView+AFNetworking.h"
#import <objc/runtime.h>
#if TARGET_OS_IOS || TARGET_OS_TV
#import "AFURLSessionManager.h"
static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext;
static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext;
#pragma mark -
@implementation UIProgressView (AFNetworking)
- (BOOL)af_uploadProgressAnimated {
return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_uploadProgressAnimated)) boolValue];
}
- (void)af_setUploadProgressAnimated:(BOOL)animated {
objc_setAssociatedObject(self, @selector(af_uploadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)af_downloadProgressAnimated {
return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_downloadProgressAnimated)) boolValue];
}
- (void)af_setDownloadProgressAnimated:(BOOL)animated {
objc_setAssociatedObject(self, @selector(af_downloadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#pragma mark -
- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task
animated:(BOOL)animated
{
if (task.state == NSURLSessionTaskStateCompleted) {
return;
}
[task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext];
[task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext];
[self af_setUploadProgressAnimated:animated];
}
- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task
animated:(BOOL)animated
{
if (task.state == NSURLSessionTaskStateCompleted) {
return;
}
[task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext];
[task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext];
[self af_setDownloadProgressAnimated:animated];
}
#pragma mark - NSKeyValueObserving
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(__unused NSDictionary *)change
context:(void *)context
{
if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) {
if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) {
if ([object countOfBytesExpectedToSend] > 0) {
dispatch_async(dispatch_get_main_queue(), ^{
[self setProgress:[object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f) animated:self.af_uploadProgressAnimated];
});
}
}
if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) {
if ([object countOfBytesExpectedToReceive] > 0) {
dispatch_async(dispatch_get_main_queue(), ^{
[self setProgress:[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f) animated:self.af_downloadProgressAnimated];
});
}
}
if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) {
if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) {
@try {
[object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))];
if (context == AFTaskCountOfBytesSentContext) {
[object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))];
}
if (context == AFTaskCountOfBytesReceivedContext) {
[object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))];
}
}
@catch (NSException * __unused exception) {}
}
}
}
}
@end
#endif
// UIRefreshControl+AFNetworking.m
//
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <TargetConditionals.h>
#if TARGET_OS_IOS
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically beginning and ending refreshing depending on the loading state of a session task.
*/
@interface UIRefreshControl (AFNetworking)
///-----------------------------------
/// @name Refreshing for Session Tasks
///-----------------------------------
/**
Binds the refreshing state to the state of the specified task.
@param task The task. If `nil`, automatic updating from any previously specified operation will be disabled.
*/
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task;
@end
NS_ASSUME_NONNULL_END
#endif
// UIRefreshControl+AFNetworking.m
//
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "UIRefreshControl+AFNetworking.h"
#import <objc/runtime.h>
#if TARGET_OS_IOS
#import "AFURLSessionManager.h"
@interface AFRefreshControlNotificationObserver : NSObject
@property (readonly, nonatomic, weak) UIRefreshControl *refreshControl;
- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl;
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task;
@end
@implementation UIRefreshControl (AFNetworking)
- (AFRefreshControlNotificationObserver *)af_notificationObserver {
AFRefreshControlNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver));
if (notificationObserver == nil) {
notificationObserver = [[AFRefreshControlNotificationObserver alloc] initWithActivityRefreshControl:self];
objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return notificationObserver;
}
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task {
[[self af_notificationObserver] setRefreshingWithStateOfTask:task];
}
@end
@implementation AFRefreshControlNotificationObserver
- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl
{
self = [super init];
if (self) {
_refreshControl = refreshControl;
}
return self;
}
- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
if (task) {
UIRefreshControl *refreshControl = self.refreshControl;
if (task.state == NSURLSessionTaskStateRunning) {
[refreshControl beginRefreshing];
[notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task];
[notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task];
[notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task];
} else {
[refreshControl endRefreshing];
}
}
}
#pragma mark -
- (void)af_beginRefreshing {
dispatch_async(dispatch_get_main_queue(), ^{
[self.refreshControl beginRefreshing];
});
}
- (void)af_endRefreshing {
dispatch_async(dispatch_get_main_queue(), ^{
[self.refreshControl endRefreshing];
});
}
#pragma mark -
- (void)dealloc {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil];
[notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil];
}
@end
#endif
// UIWebView+AFNetworking.h
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Foundation/Foundation.h>
#import <TargetConditionals.h>
#if TARGET_OS_IOS
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
NS_ASSUME_NONNULL_BEGIN
@class AFHTTPSessionManager;
/**
This category adds methods to the UIKit framework's `UIWebView` class. The methods in this category provide increased control over the request cycle, including progress monitoring and success / failure handling.
@discussion When using these category methods, make sure to assign `delegate` for the web view, which implements `–webView:shouldStartLoadWithRequest:navigationType:` appropriately. This allows for tapped links to be loaded through AFNetworking, and can ensure that `canGoBack` & `canGoForward` update their values correctly.
*/
@interface WKWebView (AFNetworking)
/**
The session manager used to download all requests.
*/
@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
/**
Asynchronously loads the specified request.
@param request A URL request identifying the location of the content to load. This must not be `nil`.
@param progress A progress object monitoring the current download progress.
@param success A block object to be executed when the request finishes loading successfully. This block returns the HTML string to be loaded by the web view, and takes two arguments: the response, and the response string.
@param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred.
*/
- (void)loadRequest:(NSURLRequest *)request
progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
failure:(nullable void (^)(NSError *error))failure;
/**
Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding.
@param request A URL request identifying the location of the content to load. This must not be `nil`.
@param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified.
@param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified.
@param progress A progress object monitoring the current download progress.
@param success A block object to be executed when the request finishes loading successfully. This block returns the data to be loaded by the web view and takes two arguments: the response, and the downloaded data.
@param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred.
*/
- (void)loadRequest:(NSURLRequest *)request
MIMEType:(nullable NSString *)MIMEType
textEncodingName:(nullable NSString *)textEncodingName
progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
failure:(nullable void (^)(NSError *error))failure;
@end
NS_ASSUME_NONNULL_END
#endif
// UIWebView+AFNetworking.m
// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "UIWebView+AFNetworking.h"
#import <objc/runtime.h>
#if TARGET_OS_IOS
#import "AFHTTPSessionManager.h"
#import "AFURLResponseSerialization.h"
#import "AFURLRequestSerialization.h"
@interface WKWebView (_AFNetworking)
@property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask;
@end
@implementation WKWebView (_AFNetworking)
- (NSURLSessionDataTask *)af_URLSessionTask {
return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask));
}
- (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask {
objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
#pragma mark -
@implementation WKWebView (AFNetworking)
- (AFHTTPSessionManager *)sessionManager {
static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
_af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
_af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
});
return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager;
}
- (void)setSessionManager:(AFHTTPSessionManager *)sessionManager {
objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (AFHTTPResponseSerializer <AFURLResponseSerialization> *)responseSerializer {
static AFHTTPResponseSerializer <AFURLResponseSerialization> *_af_defaultResponseSerializer = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer];
});
return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer;
}
- (void)setResponseSerializer:(AFHTTPResponseSerializer<AFURLResponseSerialization> *)responseSerializer {
objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#pragma mark -
- (void)loadRequest:(NSURLRequest *)request
progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
success:(NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success
failure:(void (^)(NSError *error))failure
{
[self loadRequest:request MIMEType:nil textEncodingName:nil progress:progress success:^NSData *(NSHTTPURLResponse *response, NSData *data) {
NSStringEncoding stringEncoding = NSUTF8StringEncoding;
if (response.textEncodingName) {
CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
if (encoding != kCFStringEncodingInvalidId) {
stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
}
}
NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding];
if (success) {
string = success(response, string);
}
return [string dataUsingEncoding:stringEncoding];
} failure:failure];
}
- (void)loadRequest:(NSURLRequest *)request
MIMEType:(NSString *)MIMEType
textEncodingName:(NSString *)textEncodingName
progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress
success:(NSData * (^)(NSHTTPURLResponse *response, NSData *data))success
failure:(void (^)(NSError *error))failure
{
NSParameterAssert(request);
if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) {
[self.af_URLSessionTask cancel];
}
self.af_URLSessionTask = nil;
__weak __typeof(self)weakSelf = self;
__block NSURLSessionDataTask *dataTask;
dataTask = [self.sessionManager
dataTaskWithRequest:request
uploadProgress:nil
downloadProgress:nil
completionHandler:^(NSURLResponse * _Nonnull response, id _Nonnull responseObject, NSError * _Nullable error) {
__strong __typeof(weakSelf) strongSelf = weakSelf;
if (error) {
if (failure) {
failure(error);
}
} else {
if (success) {
success((NSHTTPURLResponse *)response, responseObject);
}
[strongSelf loadData:responseObject MIMEType:MIMEType characterEncodingName:textEncodingName baseURL:[dataTask.currentRequest URL]];
if ([strongSelf.UIDelegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
[strongSelf.UIDelegate webViewDidClose:strongSelf];
}
}
}];
self.af_URLSessionTask = dataTask;
if (progress != nil) {
*progress = [self.sessionManager downloadProgressForTask:dataTask];
}
[self.af_URLSessionTask resume];
if ([self.UIDelegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
//[self.UIDelegate webViewDidStartLoad:self];
}
}
@end
#endif
#import "FMDatabase.h"
#import "FMResultSet.h"
#import "FMDatabaseAdditions.h"
#import "FMDatabaseQueue.h"
#import "FMDatabasePool.h"
#import <Foundation/Foundation.h>
#import "sqlite3.h"
#import "FMResultSet.h"
#import "FMDatabasePool.h"
#if ! __has_feature(objc_arc)
#define FMDBAutorelease(__v) ([__v autorelease]);
#define FMDBReturnAutoreleased FMDBAutorelease
#define FMDBRetain(__v) ([__v retain]);
#define FMDBReturnRetained FMDBRetain
#define FMDBRelease(__v) ([__v release]);
#define FMDBDispatchQueueRelease(__v) (dispatch_release(__v));
#else
// -fobjc-arc
#define FMDBAutorelease(__v)
#define FMDBReturnAutoreleased(__v) (__v)
#define FMDBRetain(__v)
#define FMDBReturnRetained(__v) (__v)
#define FMDBRelease(__v)
// If OS_OBJECT_USE_OBJC=1, then the dispatch objects will be treated like ObjC objects
// and will participate in ARC.
// See the section on "Dispatch Queues and Automatic Reference Counting" in "Grand Central Dispatch (GCD) Reference" for details.
#if OS_OBJECT_USE_OBJC
#define FMDBDispatchQueueRelease(__v)
#else
#define FMDBDispatchQueueRelease(__v) (dispatch_release(__v));
#endif
#endif
#if !__has_feature(objc_instancetype)
#define instancetype id
#endif
typedef int(^FMDBExecuteStatementsCallbackBlock)(NSDictionary *resultsDictionary);
/** A SQLite ([http://sqlite.org/](http://sqlite.org/)) Objective-C wrapper.
### Usage
The three main classes in FMDB are:
- `FMDatabase` - Represents a single SQLite database. Used for executing SQL statements.
- `<FMResultSet>` - Represents the results of executing a query on an `FMDatabase`.
- `<FMDatabaseQueue>` - If you want to perform queries and updates on multiple threads, you'll want to use this class.
### See also
- `<FMDatabasePool>` - A pool of `FMDatabase` objects.
- `<FMStatement>` - A wrapper for `sqlite_stmt`.
### External links
- [FMDB on GitHub](https://github.com/ccgus/fmdb) including introductory documentation
- [SQLite web site](http://sqlite.org/)
- [FMDB mailing list](http://groups.google.com/group/fmdb)
- [SQLite FAQ](http://www.sqlite.org/faq.html)
@warning Do not instantiate a single `FMDatabase` object and use it across multiple threads. Instead, use `<FMDatabaseQueue>`.
*/
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-interface-ivars"
@interface FMDatabase : NSObject {
sqlite3* _db;
NSString* _databasePath;
BOOL _logsErrors;
BOOL _crashOnErrors;
BOOL _traceExecution;
BOOL _checkedOut;
BOOL _shouldCacheStatements;
BOOL _isExecutingStatement;
BOOL _inTransaction;
NSTimeInterval _maxBusyRetryTimeInterval;
NSTimeInterval _startBusyRetryTime;
NSMutableDictionary *_cachedStatements;
NSMutableSet *_openResultSets;
NSMutableSet *_openFunctions;
NSDateFormatter *_dateFormat;
}
///-----------------
/// @name Properties
///-----------------
/** Whether should trace execution */
@property (atomic, assign) BOOL traceExecution;
/** Whether checked out or not */
@property (atomic, assign) BOOL checkedOut;
/** Crash on errors */
@property (atomic, assign) BOOL crashOnErrors;
/** Logs errors */
@property (atomic, assign) BOOL logsErrors;
/** Dictionary of cached statements */
@property (atomic, retain) NSMutableDictionary *cachedStatements;
///---------------------
/// @name Initialization
///---------------------
/** Create a `FMDatabase` object.
An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three:
1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you.
2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed.
3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed.
For example, to create/open a database in your Mac OS X `tmp` folder:
FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
Or, in iOS, you might open a database in the app's `Documents` directory:
NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"];
FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
(For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html))
@param inPath Path of database file
@return `FMDatabase` object if successful; `nil` if failure.
*/
+ (instancetype)databaseWithPath:(NSString*)inPath;
/** Initialize a `FMDatabase` object.
An `FMDatabase` is created with a path to a SQLite database file. This path can be one of these three:
1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you.
2. An empty string (`@""`). An empty database is created at a temporary location. This database is deleted with the `FMDatabase` connection is closed.
3. `nil`. An in-memory database is created. This database will be destroyed with the `FMDatabase` connection is closed.
For example, to create/open a database in your Mac OS X `tmp` folder:
FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];
Or, in iOS, you might open a database in the app's `Documents` directory:
NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *dbPath = [docsPath stringByAppendingPathComponent:@"test.db"];
FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
(For more information on temporary and in-memory databases, read the sqlite documentation on the subject: [http://www.sqlite.org/inmemorydb.html](http://www.sqlite.org/inmemorydb.html))
@param inPath Path of database file
@return `FMDatabase` object if successful; `nil` if failure.
*/
- (instancetype)initWithPath:(NSString*)inPath;
///-----------------------------------
/// @name Opening and closing database
///-----------------------------------
/** Opening a new database connection
The database is opened for reading and writing, and is created if it does not already exist.
@return `YES` if successful, `NO` on error.
@see [sqlite3_open()](http://sqlite.org/c3ref/open.html)
@see openWithFlags:
@see close
*/
- (BOOL)open;
/** Opening a new database connection with flags
@param flags one of the following three values, optionally combined with the `SQLITE_OPEN_NOMUTEX`, `SQLITE_OPEN_FULLMUTEX`, `SQLITE_OPEN_SHAREDCACHE`, `SQLITE_OPEN_PRIVATECACHE`, and/or `SQLITE_OPEN_URI` flags:
`SQLITE_OPEN_READONLY`
The database is opened in read-only mode. If the database does not already exist, an error is returned.
`SQLITE_OPEN_READWRITE`
The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned.
`SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE`
The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for `open` method.
@return `YES` if successful, `NO` on error.
@see [sqlite3_open_v2()](http://sqlite.org/c3ref/open.html)
@see open
@see close
*/
#if SQLITE_VERSION_NUMBER >= 3005000
- (BOOL)openWithFlags:(int)flags;
#endif
/** Closing a database connection
@return `YES` if success, `NO` on error.
@see [sqlite3_close()](http://sqlite.org/c3ref/close.html)
@see open
@see openWithFlags:
*/
- (BOOL)close;
/** Test to see if we have a good connection to the database.
This will confirm whether:
- is database open
- if open, it will try a simple SELECT statement and confirm that it succeeds.
@return `YES` if everything succeeds, `NO` on failure.
*/
- (BOOL)goodConnection;
///----------------------
/// @name Perform updates
///----------------------
/** Execute single update statement
This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update.
The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method.
@param sql The SQL to be performed, with optional `?` placeholders.
@param outErr A reference to the `NSError` pointer to be updated with an auto released `NSError` object if an error if an error occurs. If `nil`, no `NSError` object will be returned.
@param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.).
@return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see lastError
@see lastErrorCode
@see lastErrorMessage
@see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
*/
- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ...;
/** Execute single update statement
@see executeUpdate:withErrorAndBindings:
@warning **Deprecated**: Please use `<executeUpdate:withErrorAndBindings>` instead.
*/
- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... __attribute__ ((deprecated));
/** Execute single update statement
This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html), [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) to bind values to `?` placeholders in the SQL with the optional list of parameters, and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update.
The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method.
@param sql The SQL to be performed, with optional `?` placeholders.
@param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.).
@return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see lastError
@see lastErrorCode
@see lastErrorMessage
@see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
@note This technique supports the use of `?` placeholders in the SQL, automatically binding any supplied value parameters to those placeholders. This approach is more robust than techniques that entail using `stringWithFormat` to manually build SQL statements, which can be problematic if the values happened to include any characters that needed to be quoted.
@note If you want to use this from Swift, please note that you must include `FMDatabaseVariadic.swift` in your project. Without that, you cannot use this method directly, and instead have to use methods such as `<executeUpdate:withArgumentsInArray:>`.
*/
- (BOOL)executeUpdate:(NSString*)sql, ...;
/** Execute single update statement
This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL. Do not use `?` placeholders in the SQL if you use this method.
@param format The SQL to be performed, with `printf`-style escape sequences.
@param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement.
@return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see executeUpdate:
@see lastError
@see lastErrorCode
@see lastErrorMessage
@note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command
[db executeUpdateWithFormat:@"INSERT INTO test (name) VALUES (%@)", @"Gus"];
is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `<executeUpdate:>`
[db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"];
There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `VALUES` clause was _not_ `VALUES ('%@')` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `VALUES (%@)`.
*/
- (BOOL)executeUpdateWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
/** Execute single update statement
This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) binding any `?` placeholders in the SQL with the optional list of parameters.
The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method.
@param sql The SQL to be performed, with optional `?` placeholders.
@param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement.
@return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see lastError
@see lastErrorCode
@see lastErrorMessage
*/
- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments;
/** Execute single update statement
This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL.
The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method.
@param sql The SQL to be performed, with optional `?` placeholders.
@param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement.
@return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see lastError
@see lastErrorCode
@see lastErrorMessage
*/
- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments;
/** Execute single update statement
This method executes a single SQL update statement (i.e. any SQL that does not return results, such as `UPDATE`, `INSERT`, or `DELETE`. This method employs [`sqlite3_prepare_v2`](http://sqlite.org/c3ref/prepare.html) and [`sqlite_step`](http://sqlite.org/c3ref/step.html) to perform the update. Unlike the other `executeUpdate` methods, this uses printf-style formatters (e.g. `%s`, `%d`, etc.) to build the SQL.
The optional values provided to this method should be objects (e.g. `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects), not fundamental data types (e.g. `int`, `long`, `NSInteger`, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object's `description` method.
@param sql The SQL to be performed, with optional `?` placeholders.
@param args A `va_list` of arguments.
@return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see lastError
@see lastErrorCode
@see lastErrorMessage
*/
- (BOOL)executeUpdate:(NSString*)sql withVAList: (va_list)args;
/** Execute multiple SQL statements
This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`.
@param sql The SQL to be performed
@return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see executeStatements:withResultBlock:
@see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html)
*/
- (BOOL)executeStatements:(NSString *)sql;
/** Execute multiple SQL statements with callback handler
This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the `sqlite3` command line `.dump` command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses `sqlite3_exec`.
@param sql The SQL to be performed.
@param block A block that will be called for any result sets returned by any SQL statements.
Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use SQLITE_OK),
non-zero value upon failure (which will stop the bulk execution of the SQL). If a statement returns values, the block will be called with the results from the query in NSDictionary *resultsDictionary.
This may be `nil` if you don't care to receive any results.
@return `YES` upon success; `NO` upon failure. If failed, you can call `<lastError>`,
`<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see executeStatements:
@see [sqlite3_exec()](http://sqlite.org/c3ref/exec.html)
*/
- (BOOL)executeStatements:(NSString *)sql withResultBlock:(FMDBExecuteStatementsCallbackBlock)block;
/** Last insert rowid
Each entry in an SQLite table has a unique 64-bit signed integer key called the "rowid". The rowid is always available as an undeclared column named `ROWID`, `OID`, or `_ROWID_` as long as those names are not also used by explicitly declared columns. If the table has a column of type `INTEGER PRIMARY KEY` then that column is another alias for the rowid.
This routine returns the rowid of the most recent successful `INSERT` into the database from the database connection in the first argument. As of SQLite version 3.7.7, this routines records the last insert rowid of both ordinary tables and virtual tables. If no successful `INSERT`s have ever occurred on that database connection, zero is returned.
@return The rowid of the last inserted row.
@see [sqlite3_last_insert_rowid()](http://sqlite.org/c3ref/last_insert_rowid.html)
*/
- (sqlite_int64)lastInsertRowId;
/** The number of rows changed by prior SQL statement.
This function returns the number of database rows that were changed or inserted or deleted by the most recently completed SQL statement on the database connection specified by the first parameter. Only changes that are directly specified by the INSERT, UPDATE, or DELETE statement are counted.
@return The number of rows changed by prior SQL statement.
@see [sqlite3_changes()](http://sqlite.org/c3ref/changes.html)
*/
- (int)changes;
///-------------------------
/// @name Retrieving results
///-------------------------
/** Execute select statement
Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed.
In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other.
This method employs [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html) for any optional value parameters. This properly escapes any characters that need escape sequences (e.g. quotation marks), which eliminates simple SQL errors as well as protects against SQL injection attacks. This method natively handles `NSString`, `NSNumber`, `NSNull`, `NSDate`, and `NSData` objects. All other object types will be interpreted as text values using the object's `description` method.
@param sql The SELECT statement to be performed, with optional `?` placeholders.
@param ... Optional parameters to bind to `?` placeholders in the SQL statement. These should be Objective-C objects (e.g. `NSString`, `NSNumber`, etc.), not fundamental C data types (e.g. `int`, `char *`, etc.).
@return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see FMResultSet
@see [`FMResultSet next`](<[FMResultSet next]>)
@see [`sqlite3_bind`](http://sqlite.org/c3ref/bind_blob.html)
@note If you want to use this from Swift, please note that you must include `FMDatabaseVariadic.swift` in your project. Without that, you cannot use this method directly, and instead have to use methods such as `<executeQuery:withArgumentsInArray:>`.
*/
- (FMResultSet *)executeQuery:(NSString*)sql, ...;
/** Execute select statement
Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed.
In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other.
@param format The SQL to be performed, with `printf`-style escape sequences.
@param ... Optional parameters to bind to use in conjunction with the `printf`-style escape sequences in the SQL statement.
@return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see executeQuery:
@see FMResultSet
@see [`FMResultSet next`](<[FMResultSet next]>)
@note This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite `?` placeholder, and then bind values to that placeholder. Thus the following command
[db executeQueryWithFormat:@"SELECT * FROM test WHERE name=%@", @"Gus"];
is actually replacing the `%@` with `?` placeholder, and then performing something equivalent to `<executeQuery:>`
[db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"];
There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite `?` placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction with `pragma` statements and the like. Second, note the lack of quotation marks in the SQL. The `WHERE` clause was _not_ `WHERE name='%@'` (like you might have to do if you built a SQL statement using `NSString` method `stringWithFormat`), but rather simply `WHERE name=%@`.
*/
- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2);
/** Execute select statement
Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed.
In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other.
@param sql The SELECT statement to be performed, with optional `?` placeholders.
@param arguments A `NSArray` of objects to be used when binding values to the `?` placeholders in the SQL statement.
@return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see FMResultSet
@see [`FMResultSet next`](<[FMResultSet next]>)
*/
- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments;
/** Execute select statement
Executing queries returns an `<FMResultSet>` object if successful, and `nil` upon failure. Like executing updates, there is a variant that accepts an `NSError **` parameter. Otherwise you should use the `<lastErrorMessage>` and `<lastErrorMessage>` methods to determine why a query failed.
In order to iterate through the results of your query, you use a `while()` loop. You also need to "step" (via `<[FMResultSet next]>`) from one record to the other.
@param sql The SELECT statement to be performed, with optional `?` placeholders.
@param arguments A `NSDictionary` of objects keyed by column names that will be used when binding values to the `?` placeholders in the SQL statement.
@return A `<FMResultSet>` for the result set upon success; `nil` upon failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see FMResultSet
@see [`FMResultSet next`](<[FMResultSet next]>)
*/
- (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments;
// Documentation forthcoming.
- (FMResultSet *)executeQuery:(NSString*)sql withVAList: (va_list)args;
///-------------------
/// @name Transactions
///-------------------
/** Begin a transaction
@return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see commit
@see rollback
@see beginDeferredTransaction
@see inTransaction
*/
- (BOOL)beginTransaction;
/** Begin a deferred transaction
@return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see commit
@see rollback
@see beginTransaction
@see inTransaction
*/
- (BOOL)beginDeferredTransaction;
/** Commit a transaction
Commit a transaction that was initiated with either `<beginTransaction>` or with `<beginDeferredTransaction>`.
@return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see beginTransaction
@see beginDeferredTransaction
@see rollback
@see inTransaction
*/
- (BOOL)commit;
/** Rollback a transaction
Rollback a transaction that was initiated with either `<beginTransaction>` or with `<beginDeferredTransaction>`.
@return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see beginTransaction
@see beginDeferredTransaction
@see commit
@see inTransaction
*/
- (BOOL)rollback;
/** Identify whether currently in a transaction or not
@return `YES` if currently within transaction; `NO` if not.
@see beginTransaction
@see beginDeferredTransaction
@see commit
@see rollback
*/
- (BOOL)inTransaction;
///----------------------------------------
/// @name Cached statements and result sets
///----------------------------------------
/** Clear cached statements */
- (void)clearCachedStatements;
/** Close all open result sets */
- (void)closeOpenResultSets;
/** Whether database has any open result sets
@return `YES` if there are open result sets; `NO` if not.
*/
- (BOOL)hasOpenResultSets;
/** Return whether should cache statements or not
@return `YES` if should cache statements; `NO` if not.
*/
- (BOOL)shouldCacheStatements;
/** Set whether should cache statements or not
@param value `YES` if should cache statements; `NO` if not.
*/
- (void)setShouldCacheStatements:(BOOL)value;
///-------------------------
/// @name Encryption methods
///-------------------------
/** Set encryption key.
@param key The key to be used.
@return `YES` if success, `NO` on error.
@see http://www.sqlite-encrypt.com/develop-guide.htm
@warning You need to have purchased the sqlite encryption extensions for this method to work.
*/
- (BOOL)setKey:(NSString*)key;
/** Reset encryption key
@param key The key to be used.
@return `YES` if success, `NO` on error.
@see http://www.sqlite-encrypt.com/develop-guide.htm
@warning You need to have purchased the sqlite encryption extensions for this method to work.
*/
- (BOOL)rekey:(NSString*)key;
/** Set encryption key using `keyData`.
@param keyData The `NSData` to be used.
@return `YES` if success, `NO` on error.
@see http://www.sqlite-encrypt.com/develop-guide.htm
@warning You need to have purchased the sqlite encryption extensions for this method to work.
*/
- (BOOL)setKeyWithData:(NSData *)keyData;
/** Reset encryption key using `keyData`.
@param keyData The `NSData` to be used.
@return `YES` if success, `NO` on error.
@see http://www.sqlite-encrypt.com/develop-guide.htm
@warning You need to have purchased the sqlite encryption extensions for this method to work.
*/
- (BOOL)rekeyWithData:(NSData *)keyData;
///------------------------------
/// @name General inquiry methods
///------------------------------
/** The path of the database file
@return path of database.
*/
- (NSString *)databasePath;
/** The underlying SQLite handle
@return The `sqlite3` pointer.
*/
- (sqlite3*)sqliteHandle;
///-----------------------------
/// @name Retrieving error codes
///-----------------------------
/** Last error message
Returns the English-language text that describes the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined.
@return `NSString` of the last error message.
@see [sqlite3_errmsg()](http://sqlite.org/c3ref/errcode.html)
@see lastErrorCode
@see lastError
*/
- (NSString*)lastErrorMessage;
/** Last error code
Returns the numeric result code or extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined.
@return Integer value of the last error code.
@see [sqlite3_errcode()](http://sqlite.org/c3ref/errcode.html)
@see lastErrorMessage
@see lastError
*/
- (int)lastErrorCode;
/** Had error
@return `YES` if there was an error, `NO` if no error.
@see lastError
@see lastErrorCode
@see lastErrorMessage
*/
- (BOOL)hadError;
/** Last error
@return `NSError` representing the last error.
@see lastErrorCode
@see lastErrorMessage
*/
- (NSError*)lastError;
// description forthcoming
- (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeoutInSeconds;
- (NSTimeInterval)maxBusyRetryTimeInterval;
#if SQLITE_VERSION_NUMBER >= 3007000
///------------------
/// @name Save points
///------------------
/** Start save point
@param name Name of save point.
@param outErr A `NSError` object to receive any error object (if any).
@return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see releaseSavePointWithName:error:
@see rollbackToSavePointWithName:error:
*/
- (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr;
/** Release save point
@param name Name of save point.
@param outErr A `NSError` object to receive any error object (if any).
@return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see startSavePointWithName:error:
@see rollbackToSavePointWithName:error:
*/
- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr;
/** Roll back to save point
@param name Name of save point.
@param outErr A `NSError` object to receive any error object (if any).
@return `YES` on success; `NO` on failure. If failed, you can call `<lastError>`, `<lastErrorCode>`, or `<lastErrorMessage>` for diagnostic information regarding the failure.
@see startSavePointWithName:error:
@see releaseSavePointWithName:error:
*/
- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr;
/** Start save point
@param block Block of code to perform from within save point.
@return The NSError corresponding to the error, if any. If no error, returns `nil`.
@see startSavePointWithName:error:
@see releaseSavePointWithName:error:
@see rollbackToSavePointWithName:error:
*/
- (NSError*)inSavePoint:(void (^)(BOOL *rollback))block;
#endif
///----------------------------
/// @name SQLite library status
///----------------------------
/** Test to see if the library is threadsafe
@return `NO` if and only if SQLite was compiled with mutexing code omitted due to the SQLITE_THREADSAFE compile-time option being set to 0.
@see [sqlite3_threadsafe()](http://sqlite.org/c3ref/threadsafe.html)
*/
+ (BOOL)isSQLiteThreadSafe;
/** Run-time library version numbers
@return The sqlite library version string.
@see [sqlite3_libversion()](http://sqlite.org/c3ref/libversion.html)
*/
+ (NSString*)sqliteLibVersion;
+ (NSString*)FMDBUserVersion;
+ (SInt32)FMDBVersion;
///------------------------
/// @name Make SQL function
///------------------------
/** Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates.
For example:
[queue inDatabase:^(FMDatabase *adb) {
[adb executeUpdate:@"create table ftest (foo text)"];
[adb executeUpdate:@"insert into ftest values ('hello')"];
[adb executeUpdate:@"insert into ftest values ('hi')"];
[adb executeUpdate:@"insert into ftest values ('not h!')"];
[adb executeUpdate:@"insert into ftest values ('definitely not h!')"];
[adb makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(sqlite3_context *context, int aargc, sqlite3_value **aargv) {
if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) {
@autoreleasepool {
const char *c = (const char *)sqlite3_value_text(aargv[0]);
NSString *s = [NSString stringWithUTF8String:c];
sqlite3_result_int(context, [s hasPrefix:@"h"]);
}
}
else {
NSLog(@"Unknown formart for StringStartsWithH (%d) %s:%d", sqlite3_value_type(aargv[0]), __FUNCTION__, __LINE__);
sqlite3_result_null(context);
}
}];
int rowCount = 0;
FMResultSet *ars = [adb executeQuery:@"select * from ftest where StringStartsWithH(foo)"];
while ([ars next]) {
rowCount++;
NSLog(@"Does %@ start with 'h'?", [rs stringForColumnIndex:0]);
}
FMDBQuickCheck(rowCount == 2);
}];
@param name Name of function
@param count Maximum number of parameters
@param block The block of code for the function
@see [sqlite3_create_function()](http://sqlite.org/c3ref/create_function.html)
*/
- (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(sqlite3_context *context, int argc, sqlite3_value **argv))block;
///---------------------
/// @name Date formatter
///---------------------
/** Generate an `NSDateFormatter` that won't be broken by permutations of timezones or locales.
Use this method to generate values to set the dateFormat property.
Example:
myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"];
@param format A valid NSDateFormatter format string.
@return A `NSDateFormatter` that can be used for converting dates to strings and vice versa.
@see hasDateFormatter
@see setDateFormat:
@see dateFromString:
@see stringFromDate:
@see storeableDateFormat:
@warning Note that `NSDateFormatter` is not thread-safe, so the formatter generated by this method should be assigned to only one FMDB instance and should not be used for other purposes.
*/
+ (NSDateFormatter *)storeableDateFormat:(NSString *)format;
/** Test whether the database has a date formatter assigned.
@return `YES` if there is a date formatter; `NO` if not.
@see hasDateFormatter
@see setDateFormat:
@see dateFromString:
@see stringFromDate:
@see storeableDateFormat:
*/
- (BOOL)hasDateFormatter;
/** Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps.
@param format Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using FMDatabase::storeableDateFormat.
@see hasDateFormatter
@see setDateFormat:
@see dateFromString:
@see stringFromDate:
@see storeableDateFormat:
@warning Note there is no direct getter for the `NSDateFormatter`, and you should not use the formatter you pass to FMDB for other purposes, as `NSDateFormatter` is not thread-safe.
*/
- (void)setDateFormat:(NSDateFormatter *)format;
/** Convert the supplied NSString to NSDate, using the current database formatter.
@param s `NSString` to convert to `NSDate`.
@return The `NSDate` object; or `nil` if no formatter is set.
@see hasDateFormatter
@see setDateFormat:
@see dateFromString:
@see stringFromDate:
@see storeableDateFormat:
*/
- (NSDate *)dateFromString:(NSString *)s;
/** Convert the supplied NSDate to NSString, using the current database formatter.
@param date `NSDate` of date to convert to `NSString`.
@return The `NSString` representation of the date; `nil` if no formatter is set.
@see hasDateFormatter
@see setDateFormat:
@see dateFromString:
@see stringFromDate:
@see storeableDateFormat:
*/
- (NSString *)stringFromDate:(NSDate *)date;
@end
/** Objective-C wrapper for `sqlite3_stmt`
This is a wrapper for a SQLite `sqlite3_stmt`. Generally when using FMDB you will not need to interact directly with `FMStatement`, but rather with `<FMDatabase>` and `<FMResultSet>` only.
### See also
- `<FMDatabase>`
- `<FMResultSet>`
- [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html)
*/
@interface FMStatement : NSObject {
sqlite3_stmt *_statement;
NSString *_query;
long _useCount;
BOOL _inUse;
}
///-----------------
/// @name Properties
///-----------------
/** Usage count */
@property (atomic, assign) long useCount;
/** SQL statement */
@property (atomic, retain) NSString *query;
/** SQLite sqlite3_stmt
@see [`sqlite3_stmt`](http://www.sqlite.org/c3ref/stmt.html)
*/
@property (atomic, assign) sqlite3_stmt *statement;
/** Indication of whether the statement is in use */
@property (atomic, assign) BOOL inUse;
///----------------------------
/// @name Closing and Resetting
///----------------------------
/** Close statement */
- (void)close;
/** Reset statement */
- (void)reset;
@end
#pragma clang diagnostic pop
#import "FMDatabase.h"
#import "unistd.h"
#import <objc/runtime.h>
@interface FMDatabase ()
- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args;
- (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args;
@end
@implementation FMDatabase
@synthesize cachedStatements=_cachedStatements;
@synthesize logsErrors=_logsErrors;
@synthesize crashOnErrors=_crashOnErrors;
@synthesize checkedOut=_checkedOut;
@synthesize traceExecution=_traceExecution;
#pragma mark FMDatabase instantiation and deallocation
+ (instancetype)databaseWithPath:(NSString*)aPath {
return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]);
}
- (instancetype)init {
return [self initWithPath:nil];
}
- (instancetype)initWithPath:(NSString*)aPath {
assert(sqlite3_threadsafe()); // whoa there big boy- gotta make sure sqlite it happy with what we're going to do.
self = [super init];
if (self) {
_databasePath = [aPath copy];
_openResultSets = [[NSMutableSet alloc] init];
_db = nil;
_logsErrors = YES;
_crashOnErrors = NO;
_maxBusyRetryTimeInterval = 2;
}
return self;
}
- (void)finalize {
[self close];
[super finalize];
}
- (void)dealloc {
[self close];
FMDBRelease(_openResultSets);
FMDBRelease(_cachedStatements);
FMDBRelease(_dateFormat);
FMDBRelease(_databasePath);
FMDBRelease(_openFunctions);
#if ! __has_feature(objc_arc)
[super dealloc];
#endif
}
- (NSString *)databasePath {
return _databasePath;
}
+ (NSString*)FMDBUserVersion {
return @"2.5";
}
// returns 0x0240 for version 2.4. This makes it super easy to do things like:
// /* need to make sure to do X with FMDB version 2.4 or later */
// if ([FMDatabase FMDBVersion] >= 0x0240) { … }
+ (SInt32)FMDBVersion {
// we go through these hoops so that we only have to change the version number in a single spot.
static dispatch_once_t once;
static SInt32 FMDBVersionVal = 0;
dispatch_once(&once, ^{
NSString *prodVersion = [self FMDBUserVersion];
if ([[prodVersion componentsSeparatedByString:@"."] count] < 3) {
prodVersion = [prodVersion stringByAppendingString:@".0"];
}
NSString *junk = [prodVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
char *e = nil;
FMDBVersionVal = (int) strtoul([junk UTF8String], &e, 16);
});
return FMDBVersionVal;
}
#pragma mark SQLite information
+ (NSString*)sqliteLibVersion {
return [NSString stringWithFormat:@"%s", sqlite3_libversion()];
}
+ (BOOL)isSQLiteThreadSafe {
// make sure to read the sqlite headers on this guy!
return sqlite3_threadsafe() != 0;
}
- (sqlite3*)sqliteHandle {
return _db;
}
- (const char*)sqlitePath {
if (!_databasePath) {
return ":memory:";
}
if ([_databasePath length] == 0) {
return ""; // this creates a temporary database (it's an sqlite thing).
}
return [_databasePath fileSystemRepresentation];
}
#pragma mark Open and close database
- (BOOL)open {
if (_db) {
return YES;
}
int err = sqlite3_open([self sqlitePath], &_db );
if(err != SQLITE_OK) {
NSLog(@"error opening!: %d", err);
return NO;
}
if (_maxBusyRetryTimeInterval > 0.0) {
// set the handler
[self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval];
}
return YES;
}
#if SQLITE_VERSION_NUMBER >= 3005000
- (BOOL)openWithFlags:(int)flags {
if (_db) {
return YES;
}
int err = sqlite3_open_v2([self sqlitePath], &_db, flags, NULL /* Name of VFS module to use */);
if(err != SQLITE_OK) {
NSLog(@"error opening!: %d", err);
return NO;
}
if (_maxBusyRetryTimeInterval > 0.0) {
// set the handler
[self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval];
}
return YES;
}
#endif
- (BOOL)close {
[self clearCachedStatements];
[self closeOpenResultSets];
if (!_db) {
return YES;
}
int rc;
BOOL retry;
BOOL triedFinalizingOpenStatements = NO;
do {
retry = NO;
rc = sqlite3_close(_db);
if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
if (!triedFinalizingOpenStatements) {
triedFinalizingOpenStatements = YES;
sqlite3_stmt *pStmt;
while ((pStmt = sqlite3_next_stmt(_db, nil)) !=0) {
NSLog(@"Closing leaked statement");
sqlite3_finalize(pStmt);
retry = YES;
}
}
}
else if (SQLITE_OK != rc) {
NSLog(@"error closing!: %d", rc);
}
}
while (retry);
_db = nil;
return YES;
}
#pragma mark Busy handler routines
// NOTE: appledoc seems to choke on this function for some reason;
// so when generating documentation, you might want to ignore the
// .m files so that it only documents the public interfaces outlined
// in the .h files.
//
// This is a known appledoc bug that it has problems with C functions
// within a class implementation, but for some reason, only this
// C function causes problems; the rest don't. Anyway, ignoring the .m
// files with appledoc will prevent this problem from occurring.
static int FMDBDatabaseBusyHandler(void *f, int count) {
FMDatabase *self = (__bridge FMDatabase*)f;
if (count == 0) {
self->_startBusyRetryTime = [NSDate timeIntervalSinceReferenceDate];
return 1;
}
NSTimeInterval delta = [NSDate timeIntervalSinceReferenceDate] - (self->_startBusyRetryTime);
if (delta < [self maxBusyRetryTimeInterval]) {
int requestedSleepInMillseconds = (int) arc4random_uniform(50) + 50;
int actualSleepInMilliseconds = sqlite3_sleep(requestedSleepInMillseconds);
if (actualSleepInMilliseconds != requestedSleepInMillseconds) {
NSLog(@"WARNING: Requested sleep of %i milliseconds, but SQLite returned %i. Maybe SQLite wasn't built with HAVE_USLEEP=1?", requestedSleepInMillseconds, actualSleepInMilliseconds);
}
return 1;
}
return 0;
}
- (void)setMaxBusyRetryTimeInterval:(NSTimeInterval)timeout {
_maxBusyRetryTimeInterval = timeout;
if (!_db) {
return;
}
if (timeout > 0) {
sqlite3_busy_handler(_db, &FMDBDatabaseBusyHandler, (__bridge void *)(self));
}
else {
// turn it off otherwise
sqlite3_busy_handler(_db, nil, nil);
}
}
- (NSTimeInterval)maxBusyRetryTimeInterval {
return _maxBusyRetryTimeInterval;
}
// we no longer make busyRetryTimeout public
// but for folks who don't bother noticing that the interface to FMDatabase changed,
// we'll still implement the method so they don't get suprise crashes
- (int)busyRetryTimeout {
NSLog(@"%s:%d", __FUNCTION__, __LINE__);
NSLog(@"FMDB: busyRetryTimeout no longer works, please use maxBusyRetryTimeInterval");
return -1;
}
- (void)setBusyRetryTimeout:(int)i {
NSLog(@"%s:%d", __FUNCTION__, __LINE__);
NSLog(@"FMDB: setBusyRetryTimeout does nothing, please use setMaxBusyRetryTimeInterval:");
}
#pragma mark Result set functions
- (BOOL)hasOpenResultSets {
return [_openResultSets count] > 0;
}
- (void)closeOpenResultSets {
//Copy the set so we don't get mutation errors
NSSet *openSetCopy = FMDBReturnAutoreleased([_openResultSets copy]);
for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) {
FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue];
[rs setParentDB:nil];
[rs close];
[_openResultSets removeObject:rsInWrappedInATastyValueMeal];
}
}
- (void)resultSetDidClose:(FMResultSet *)resultSet {
NSValue *setValue = [NSValue valueWithNonretainedObject:resultSet];
[_openResultSets removeObject:setValue];
}
#pragma mark Cached statements
- (void)clearCachedStatements {
for (NSMutableSet *statements in [_cachedStatements objectEnumerator]) {
[statements makeObjectsPerformSelector:@selector(close)];
}
[_cachedStatements removeAllObjects];
}
- (FMStatement*)cachedStatementForQuery:(NSString*)query {
NSMutableSet* statements = [_cachedStatements objectForKey:query];
return [[statements objectsPassingTest:^BOOL(FMStatement* statement, BOOL *stop) {
*stop = ![statement inUse];
return *stop;
}] anyObject];
}
- (void)setCachedStatement:(FMStatement*)statement forQuery:(NSString*)query {
query = [query copy]; // in case we got handed in a mutable string...
[statement setQuery:query];
NSMutableSet* statements = [_cachedStatements objectForKey:query];
if (!statements) {
statements = [NSMutableSet set];
}
[statements addObject:statement];
[_cachedStatements setObject:statements forKey:query];
FMDBRelease(query);
}
#pragma mark Key routines
- (BOOL)rekey:(NSString*)key {
NSData *keyData = [NSData dataWithBytes:(void *)[key UTF8String] length:(NSUInteger)strlen([key UTF8String])];
return [self rekeyWithData:keyData];
}
- (BOOL)rekeyWithData:(NSData *)keyData {
#ifdef SQLITE_HAS_CODEC
if (!keyData) {
return NO;
}
int rc = sqlite3_rekey(_db, [keyData bytes], (int)[keyData length]);
if (rc != SQLITE_OK) {
NSLog(@"error on rekey: %d", rc);
NSLog(@"%@", [self lastErrorMessage]);
}
return (rc == SQLITE_OK);
#else
return NO;
#endif
}
- (BOOL)setKey:(NSString*)key {
NSData *keyData = [NSData dataWithBytes:[key UTF8String] length:(NSUInteger)strlen([key UTF8String])];
return [self setKeyWithData:keyData];
}
- (BOOL)setKeyWithData:(NSData *)keyData {
#ifdef SQLITE_HAS_CODEC
if (!keyData) {
return NO;
}
int rc = sqlite3_key(_db, [keyData bytes], (int)[keyData length]);
return (rc == SQLITE_OK);
#else
return NO;
#endif
}
#pragma mark Date routines
+ (NSDateFormatter *)storeableDateFormat:(NSString *)format {
NSDateFormatter *result = FMDBReturnAutoreleased([[NSDateFormatter alloc] init]);
result.dateFormat = format;
result.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
result.locale = FMDBReturnAutoreleased([[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]);
return result;
}
- (BOOL)hasDateFormatter {
return _dateFormat != nil;
}
- (void)setDateFormat:(NSDateFormatter *)format {
FMDBAutorelease(_dateFormat);
_dateFormat = FMDBReturnRetained(format);
}
- (NSDate *)dateFromString:(NSString *)s {
return [_dateFormat dateFromString:s];
}
- (NSString *)stringFromDate:(NSDate *)date {
return [_dateFormat stringFromDate:date];
}
#pragma mark State of database
- (BOOL)goodConnection {
if (!_db) {
return NO;
}
FMResultSet *rs = [self executeQuery:@"select name from sqlite_master where type='table'"];
if (rs) {
[rs close];
return YES;
}
return NO;
}
- (void)warnInUse {
NSLog(@"The FMDatabase %@ is currently in use.", self);
#ifndef NS_BLOCK_ASSERTIONS
if (_crashOnErrors) {
NSAssert(false, @"The FMDatabase %@ is currently in use.", self);
abort();
}
#endif
}
- (BOOL)databaseExists {
if (!_db) {
NSLog(@"The FMDatabase %@ is not open.", self);
#ifndef NS_BLOCK_ASSERTIONS
if (_crashOnErrors) {
NSAssert(false, @"The FMDatabase %@ is not open.", self);
abort();
}
#endif
return NO;
}
return YES;
}
#pragma mark Error routines
- (NSString*)lastErrorMessage {
return [NSString stringWithUTF8String:sqlite3_errmsg(_db)];
}
- (BOOL)hadError {
int lastErrCode = [self lastErrorCode];
return (lastErrCode > SQLITE_OK && lastErrCode < SQLITE_ROW);
}
- (int)lastErrorCode {
return sqlite3_errcode(_db);
}
- (NSError*)errorWithMessage:(NSString*)message {
NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:message forKey:NSLocalizedDescriptionKey];
return [NSError errorWithDomain:@"FMDatabase" code:sqlite3_errcode(_db) userInfo:errorMessage];
}
- (NSError*)lastError {
return [self errorWithMessage:[self lastErrorMessage]];
}
#pragma mark Update information routines
- (sqlite_int64)lastInsertRowId {
if (_isExecutingStatement) {
[self warnInUse];
return NO;
}
_isExecutingStatement = YES;
sqlite_int64 ret = sqlite3_last_insert_rowid(_db);
_isExecutingStatement = NO;
return ret;
}
- (int)changes {
if (_isExecutingStatement) {
[self warnInUse];
return 0;
}
_isExecutingStatement = YES;
int ret = sqlite3_changes(_db);
_isExecutingStatement = NO;
return ret;
}
#pragma mark SQL manipulation
- (void)bindObject:(id)obj toColumn:(int)idx inStatement:(sqlite3_stmt*)pStmt {
if ((!obj) || ((NSNull *)obj == [NSNull null])) {
sqlite3_bind_null(pStmt, idx);
}
// FIXME - someday check the return codes on these binds.
else if ([obj isKindOfClass:[NSData class]]) {
const void *bytes = [obj bytes];
if (!bytes) {
// it's an empty NSData object, aka [NSData data].
// Don't pass a NULL pointer, or sqlite will bind a SQL null instead of a blob.
bytes = "";
}
sqlite3_bind_blob(pStmt, idx, bytes, (int)[obj length], SQLITE_STATIC);
}
else if ([obj isKindOfClass:[NSDate class]]) {
if (self.hasDateFormatter)
sqlite3_bind_text(pStmt, idx, [[self stringFromDate:obj] UTF8String], -1, SQLITE_STATIC);
else
sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]);
}
else if ([obj isKindOfClass:[NSNumber class]]) {
if (strcmp([obj objCType], @encode(char)) == 0) {
sqlite3_bind_int(pStmt, idx, [obj charValue]);
}
else if (strcmp([obj objCType], @encode(unsigned char)) == 0) {
sqlite3_bind_int(pStmt, idx, [obj unsignedCharValue]);
}
else if (strcmp([obj objCType], @encode(short)) == 0) {
sqlite3_bind_int(pStmt, idx, [obj shortValue]);
}
else if (strcmp([obj objCType], @encode(unsigned short)) == 0) {
sqlite3_bind_int(pStmt, idx, [obj unsignedShortValue]);
}
else if (strcmp([obj objCType], @encode(int)) == 0) {
sqlite3_bind_int(pStmt, idx, [obj intValue]);
}
else if (strcmp([obj objCType], @encode(unsigned int)) == 0) {
sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedIntValue]);
}
else if (strcmp([obj objCType], @encode(long)) == 0) {
sqlite3_bind_int64(pStmt, idx, [obj longValue]);
}
else if (strcmp([obj objCType], @encode(unsigned long)) == 0) {
sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongValue]);
}
else if (strcmp([obj objCType], @encode(long long)) == 0) {
sqlite3_bind_int64(pStmt, idx, [obj longLongValue]);
}
else if (strcmp([obj objCType], @encode(unsigned long long)) == 0) {
sqlite3_bind_int64(pStmt, idx, (long long)[obj unsignedLongLongValue]);
}
else if (strcmp([obj objCType], @encode(float)) == 0) {
sqlite3_bind_double(pStmt, idx, [obj floatValue]);
}
else if (strcmp([obj objCType], @encode(double)) == 0) {
sqlite3_bind_double(pStmt, idx, [obj doubleValue]);
}
else if (strcmp([obj objCType], @encode(BOOL)) == 0) {
sqlite3_bind_int(pStmt, idx, ([obj boolValue] ? 1 : 0));
}
else {
sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
}
}
else {
sqlite3_bind_text(pStmt, idx, [[obj description] UTF8String], -1, SQLITE_STATIC);
}
}
- (void)extractSQL:(NSString *)sql argumentsList:(va_list)args intoString:(NSMutableString *)cleanedSQL arguments:(NSMutableArray *)arguments {
NSUInteger length = [sql length];
unichar last = '\0';
for (NSUInteger i = 0; i < length; ++i) {
id arg = nil;
unichar current = [sql characterAtIndex:i];
unichar add = current;
if (last == '%') {
switch (current) {
case '@':
arg = va_arg(args, id);
break;
case 'c':
// warning: second argument to 'va_arg' is of promotable type 'char'; this va_arg has undefined behavior because arguments will be promoted to 'int'
arg = [NSString stringWithFormat:@"%c", va_arg(args, int)];
break;
case 's':
arg = [NSString stringWithUTF8String:va_arg(args, char*)];
break;
case 'd':
case 'D':
case 'i':
arg = [NSNumber numberWithInt:va_arg(args, int)];
break;
case 'u':
case 'U':
arg = [NSNumber numberWithUnsignedInt:va_arg(args, unsigned int)];
break;
case 'h':
i++;
if (i < length && [sql characterAtIndex:i] == 'i') {
// warning: second argument to 'va_arg' is of promotable type 'short'; this va_arg has undefined behavior because arguments will be promoted to 'int'
arg = [NSNumber numberWithShort:(short)(va_arg(args, int))];
}
else if (i < length && [sql characterAtIndex:i] == 'u') {
// warning: second argument to 'va_arg' is of promotable type 'unsigned short'; this va_arg has undefined behavior because arguments will be promoted to 'int'
arg = [NSNumber numberWithUnsignedShort:(unsigned short)(va_arg(args, uint))];
}
else {
i--;
}
break;
case 'q':
i++;
if (i < length && [sql characterAtIndex:i] == 'i') {
arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
}
else if (i < length && [sql characterAtIndex:i] == 'u') {
arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
}
else {
i--;
}
break;
case 'f':
arg = [NSNumber numberWithDouble:va_arg(args, double)];
break;
case 'g':
// warning: second argument to 'va_arg' is of promotable type 'float'; this va_arg has undefined behavior because arguments will be promoted to 'double'
arg = [NSNumber numberWithFloat:(float)(va_arg(args, double))];
break;
case 'l':
i++;
if (i < length) {
unichar next = [sql characterAtIndex:i];
if (next == 'l') {
i++;
if (i < length && [sql characterAtIndex:i] == 'd') {
//%lld
arg = [NSNumber numberWithLongLong:va_arg(args, long long)];
}
else if (i < length && [sql characterAtIndex:i] == 'u') {
//%llu
arg = [NSNumber numberWithUnsignedLongLong:va_arg(args, unsigned long long)];
}
else {
i--;
}
}
else if (next == 'd') {
//%ld
arg = [NSNumber numberWithLong:va_arg(args, long)];
}
else if (next == 'u') {
//%lu
arg = [NSNumber numberWithUnsignedLong:va_arg(args, unsigned long)];
}
else {
i--;
}
}
else {
i--;
}
break;
default:
// something else that we can't interpret. just pass it on through like normal
break;
}
}
else if (current == '%') {
// percent sign; skip this character
add = '\0';
}
if (arg != nil) {
[cleanedSQL appendString:@"?"];
[arguments addObject:arg];
}
else if (add == (unichar)'@' && last == (unichar) '%') {
[cleanedSQL appendFormat:@"NULL"];
}
else if (add != '\0') {
[cleanedSQL appendFormat:@"%C", add];
}
last = current;
}
}
#pragma mark Execute queries
- (FMResultSet *)executeQuery:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments {
return [self executeQuery:sql withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
}
- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args {
if (![self databaseExists]) {
return 0x00;
}
if (_isExecutingStatement) {
[self warnInUse];
return 0x00;
}
_isExecutingStatement = YES;
int rc = 0x00;
sqlite3_stmt *pStmt = 0x00;
FMStatement *statement = 0x00;
FMResultSet *rs = 0x00;
if (_traceExecution && sql) {
NSLog(@"%@ executeQuery: %@", self, sql);
}
if (_shouldCacheStatements) {
statement = [self cachedStatementForQuery:sql];
pStmt = statement ? [statement statement] : 0x00;
[statement reset];
}
if (!pStmt) {
rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
if (SQLITE_OK != rc) {
if (_logsErrors) {
NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
NSLog(@"DB Query: %@", sql);
NSLog(@"DB Path: %@", _databasePath);
}
if (_crashOnErrors) {
NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
abort();
}
sqlite3_finalize(pStmt);
_isExecutingStatement = NO;
return nil;
}
}
id obj;
int idx = 0;
int queryCount = sqlite3_bind_parameter_count(pStmt); // pointed out by Dominic Yu (thanks!)
// If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
if (dictionaryArgs) {
for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
// Prefix the key with a colon.
NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
if (_traceExecution) {
NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]);
}
// Get the index for the parameter name.
int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
FMDBRelease(parameterName);
if (namedIdx > 0) {
// Standard binding from here.
[self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
// increment the binding count, so our check below works out
idx++;
}
else {
NSLog(@"Could not find index for %@", dictionaryKey);
}
}
}
else {
while (idx < queryCount) {
if (arrayArgs && idx < (int)[arrayArgs count]) {
obj = [arrayArgs objectAtIndex:(NSUInteger)idx];
}
else if (args) {
obj = va_arg(args, id);
}
else {
//We ran out of arguments
break;
}
if (_traceExecution) {
if ([obj isKindOfClass:[NSData class]]) {
NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]);
}
else {
NSLog(@"obj: %@", obj);
}
}
idx++;
[self bindObject:obj toColumn:idx inStatement:pStmt];
}
}
if (idx != queryCount) {
NSLog(@"Error: the bind count is not correct for the # of variables (executeQuery)");
sqlite3_finalize(pStmt);
_isExecutingStatement = NO;
return nil;
}
FMDBRetain(statement); // to balance the release below
if (!statement) {
statement = [[FMStatement alloc] init];
[statement setStatement:pStmt];
if (_shouldCacheStatements && sql) {
[self setCachedStatement:statement forQuery:sql];
}
}
// the statement gets closed in rs's dealloc or [rs close];
rs = [FMResultSet resultSetWithStatement:statement usingParentDatabase:self];
[rs setQuery:sql];
NSValue *openResultSet = [NSValue valueWithNonretainedObject:rs];
[_openResultSets addObject:openResultSet];
[statement setUseCount:[statement useCount] + 1];
FMDBRelease(statement);
_isExecutingStatement = NO;
return rs;
}
- (FMResultSet *)executeQuery:(NSString*)sql, ... {
va_list args;
va_start(args, sql);
id result = [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args];
va_end(args);
return result;
}
- (FMResultSet *)executeQueryWithFormat:(NSString*)format, ... {
va_list args;
va_start(args, format);
NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
NSMutableArray *arguments = [NSMutableArray array];
[self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
va_end(args);
return [self executeQuery:sql withArgumentsInArray:arguments];
}
- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray *)arguments {
return [self executeQuery:sql withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
}
- (FMResultSet *)executeQuery:(NSString*)sql withVAList:(va_list)args {
return [self executeQuery:sql withArgumentsInArray:nil orDictionary:nil orVAList:args];
}
#pragma mark Execute updates
- (BOOL)executeUpdate:(NSString*)sql error:(NSError**)outErr withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args {
if (![self databaseExists]) {
return NO;
}
if (_isExecutingStatement) {
[self warnInUse];
return NO;
}
_isExecutingStatement = YES;
int rc = 0x00;
sqlite3_stmt *pStmt = 0x00;
FMStatement *cachedStmt = 0x00;
if (_traceExecution && sql) {
NSLog(@"%@ executeUpdate: %@", self, sql);
}
if (_shouldCacheStatements) {
cachedStmt = [self cachedStatementForQuery:sql];
pStmt = cachedStmt ? [cachedStmt statement] : 0x00;
[cachedStmt reset];
}
if (!pStmt) {
rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
if (SQLITE_OK != rc) {
if (_logsErrors) {
NSLog(@"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
NSLog(@"DB Query: %@", sql);
NSLog(@"DB Path: %@", _databasePath);
}
if (_crashOnErrors) {
NSAssert(false, @"DB Error: %d \"%@\"", [self lastErrorCode], [self lastErrorMessage]);
abort();
}
sqlite3_finalize(pStmt);
if (outErr) {
*outErr = [self errorWithMessage:[NSString stringWithUTF8String:sqlite3_errmsg(_db)]];
}
_isExecutingStatement = NO;
return NO;
}
}
id obj;
int idx = 0;
int queryCount = sqlite3_bind_parameter_count(pStmt);
// If dictionaryArgs is passed in, that means we are using sqlite's named parameter support
if (dictionaryArgs) {
for (NSString *dictionaryKey in [dictionaryArgs allKeys]) {
// Prefix the key with a colon.
NSString *parameterName = [[NSString alloc] initWithFormat:@":%@", dictionaryKey];
if (_traceExecution) {
NSLog(@"%@ = %@", parameterName, [dictionaryArgs objectForKey:dictionaryKey]);
}
// Get the index for the parameter name.
int namedIdx = sqlite3_bind_parameter_index(pStmt, [parameterName UTF8String]);
FMDBRelease(parameterName);
if (namedIdx > 0) {
// Standard binding from here.
[self bindObject:[dictionaryArgs objectForKey:dictionaryKey] toColumn:namedIdx inStatement:pStmt];
// increment the binding count, so our check below works out
idx++;
}
else {
NSLog(@"Could not find index for %@", dictionaryKey);
}
}
}
else {
while (idx < queryCount) {
if (arrayArgs && idx < (int)[arrayArgs count]) {
obj = [arrayArgs objectAtIndex:(NSUInteger)idx];
}
else if (args) {
obj = va_arg(args, id);
}
else {
//We ran out of arguments
break;
}
if (_traceExecution) {
if ([obj isKindOfClass:[NSData class]]) {
NSLog(@"data: %ld bytes", (unsigned long)[(NSData*)obj length]);
}
else {
NSLog(@"obj: %@", obj);
}
}
idx++;
[self bindObject:obj toColumn:idx inStatement:pStmt];
}
}
if (idx != queryCount) {
NSLog(@"Error: the bind count (%d) is not correct for the # of variables in the query (%d) (%@) (executeUpdate)", idx, queryCount, sql);
sqlite3_finalize(pStmt);
_isExecutingStatement = NO;
return NO;
}
/* Call sqlite3_step() to run the virtual machine. Since the SQL being
** executed is not a SELECT statement, we assume no data will be returned.
*/
rc = sqlite3_step(pStmt);
if (SQLITE_DONE == rc) {
// all is well, let's return.
}
else if (SQLITE_ERROR == rc) {
if (_logsErrors) {
NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_ERROR", rc, sqlite3_errmsg(_db));
NSLog(@"DB Query: %@", sql);
}
}
else if (SQLITE_MISUSE == rc) {
// uh oh.
if (_logsErrors) {
NSLog(@"Error calling sqlite3_step (%d: %s) SQLITE_MISUSE", rc, sqlite3_errmsg(_db));
NSLog(@"DB Query: %@", sql);
}
}
else {
// wtf?
if (_logsErrors) {
NSLog(@"Unknown error calling sqlite3_step (%d: %s) eu", rc, sqlite3_errmsg(_db));
NSLog(@"DB Query: %@", sql);
}
}
if (rc == SQLITE_ROW) {
NSAssert(NO, @"A executeUpdate is being called with a query string '%@'", sql);
}
if (_shouldCacheStatements && !cachedStmt) {
cachedStmt = [[FMStatement alloc] init];
[cachedStmt setStatement:pStmt];
[self setCachedStatement:cachedStmt forQuery:sql];
FMDBRelease(cachedStmt);
}
int closeErrorCode;
if (cachedStmt) {
[cachedStmt setUseCount:[cachedStmt useCount] + 1];
closeErrorCode = sqlite3_reset(pStmt);
}
else {
/* Finalize the virtual machine. This releases all memory and other
** resources allocated by the sqlite3_prepare() call above.
*/
closeErrorCode = sqlite3_finalize(pStmt);
}
if (closeErrorCode != SQLITE_OK) {
if (_logsErrors) {
NSLog(@"Unknown error finalizing or resetting statement (%d: %s)", closeErrorCode, sqlite3_errmsg(_db));
NSLog(@"DB Query: %@", sql);
}
}
_isExecutingStatement = NO;
return (rc == SQLITE_DONE || rc == SQLITE_OK);
}
- (BOOL)executeUpdate:(NSString*)sql, ... {
va_list args;
va_start(args, sql);
BOOL result = [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args];
va_end(args);
return result;
}
- (BOOL)executeUpdate:(NSString*)sql withArgumentsInArray:(NSArray *)arguments {
return [self executeUpdate:sql error:nil withArgumentsInArray:arguments orDictionary:nil orVAList:nil];
}
- (BOOL)executeUpdate:(NSString*)sql withParameterDictionary:(NSDictionary *)arguments {
return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:arguments orVAList:nil];
}
- (BOOL)executeUpdate:(NSString*)sql withVAList:(va_list)args {
return [self executeUpdate:sql error:nil withArgumentsInArray:nil orDictionary:nil orVAList:args];
}
- (BOOL)executeUpdateWithFormat:(NSString*)format, ... {
va_list args;
va_start(args, format);
NSMutableString *sql = [NSMutableString stringWithCapacity:[format length]];
NSMutableArray *arguments = [NSMutableArray array];
[self extractSQL:format argumentsList:args intoString:sql arguments:arguments];
va_end(args);
return [self executeUpdate:sql withArgumentsInArray:arguments];
}
int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names); // shhh clang.
int FMDBExecuteBulkSQLCallback(void *theBlockAsVoid, int columns, char **values, char **names) {
if (!theBlockAsVoid) {
return SQLITE_OK;
}
int (^execCallbackBlock)(NSDictionary *resultsDictionary) = (__bridge int (^)(NSDictionary *__strong))(theBlockAsVoid);
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:(NSUInteger)columns];
for (NSInteger i = 0; i < columns; i++) {
NSString *key = [NSString stringWithUTF8String:names[i]];
id value = values[i] ? [NSString stringWithUTF8String:values[i]] : [NSNull null];
[dictionary setObject:value forKey:key];
}
return execCallbackBlock(dictionary);
}
- (BOOL)executeStatements:(NSString *)sql {
return [self executeStatements:sql withResultBlock:nil];
}
- (BOOL)executeStatements:(NSString *)sql withResultBlock:(FMDBExecuteStatementsCallbackBlock)block {
int rc;
char *errmsg = nil;
rc = sqlite3_exec([self sqliteHandle], [sql UTF8String], block ? FMDBExecuteBulkSQLCallback : nil, (__bridge void *)(block), &errmsg);
if (errmsg && [self logsErrors]) {
NSLog(@"Error inserting batch: %s", errmsg);
sqlite3_free(errmsg);
}
return (rc == SQLITE_OK);
}
- (BOOL)executeUpdate:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... {
va_list args;
va_start(args, outErr);
BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args];
va_end(args);
return result;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
- (BOOL)update:(NSString*)sql withErrorAndBindings:(NSError**)outErr, ... {
va_list args;
va_start(args, outErr);
BOOL result = [self executeUpdate:sql error:outErr withArgumentsInArray:nil orDictionary:nil orVAList:args];
va_end(args);
return result;
}
#pragma clang diagnostic pop
#pragma mark Transactions
- (BOOL)rollback {
BOOL b = [self executeUpdate:@"rollback transaction"];
if (b) {
_inTransaction = NO;
}
return b;
}
- (BOOL)commit {
BOOL b = [self executeUpdate:@"commit transaction"];
if (b) {
_inTransaction = NO;
}
return b;
}
- (BOOL)beginDeferredTransaction {
BOOL b = [self executeUpdate:@"begin deferred transaction"];
if (b) {
_inTransaction = YES;
}
return b;
}
- (BOOL)beginTransaction {
BOOL b = [self executeUpdate:@"begin exclusive transaction"];
if (b) {
_inTransaction = YES;
}
return b;
}
- (BOOL)inTransaction {
return _inTransaction;
}
#if SQLITE_VERSION_NUMBER >= 3007000
static NSString *FMDBEscapeSavePointName(NSString *savepointName) {
return [savepointName stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
}
- (BOOL)startSavePointWithName:(NSString*)name error:(NSError**)outErr {
NSParameterAssert(name);
NSString *sql = [NSString stringWithFormat:@"savepoint '%@';", FMDBEscapeSavePointName(name)];
if (![self executeUpdate:sql]) {
if (outErr) {
*outErr = [self lastError];
}
return NO;
}
return YES;
}
- (BOOL)releaseSavePointWithName:(NSString*)name error:(NSError**)outErr {
NSParameterAssert(name);
NSString *sql = [NSString stringWithFormat:@"release savepoint '%@';", FMDBEscapeSavePointName(name)];
BOOL worked = [self executeUpdate:sql];
if (!worked && outErr) {
*outErr = [self lastError];
}
return worked;
}
- (BOOL)rollbackToSavePointWithName:(NSString*)name error:(NSError**)outErr {
NSParameterAssert(name);
NSString *sql = [NSString stringWithFormat:@"rollback transaction to savepoint '%@';", FMDBEscapeSavePointName(name)];
BOOL worked = [self executeUpdate:sql];
if (!worked && outErr) {
*outErr = [self lastError];
}
return worked;
}
- (NSError*)inSavePoint:(void (^)(BOOL *rollback))block {
static unsigned long savePointIdx = 0;
NSString *name = [NSString stringWithFormat:@"dbSavePoint%ld", savePointIdx++];
BOOL shouldRollback = NO;
NSError *err = 0x00;
if (![self startSavePointWithName:name error:&err]) {
return err;
}
block(&shouldRollback);
if (shouldRollback) {
// We need to rollback and release this savepoint to remove it
[self rollbackToSavePointWithName:name error:&err];
}
[self releaseSavePointWithName:name error:&err];
return err;
}
#endif
#pragma mark Cache statements
- (BOOL)shouldCacheStatements {
return _shouldCacheStatements;
}
- (void)setShouldCacheStatements:(BOOL)value {
_shouldCacheStatements = value;
if (_shouldCacheStatements && !_cachedStatements) {
[self setCachedStatements:[NSMutableDictionary dictionary]];
}
if (!_shouldCacheStatements) {
[self setCachedStatements:nil];
}
}
#pragma mark Callback function
void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv); // -Wmissing-prototypes
void FMDBBlockSQLiteCallBackFunction(sqlite3_context *context, int argc, sqlite3_value **argv) {
#if ! __has_feature(objc_arc)
void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (id)sqlite3_user_data(context);
#else
void (^block)(sqlite3_context *context, int argc, sqlite3_value **argv) = (__bridge id)sqlite3_user_data(context);
#endif
block(context, argc, argv);
}
- (void)makeFunctionNamed:(NSString*)name maximumArguments:(int)count withBlock:(void (^)(sqlite3_context *context, int argc, sqlite3_value **argv))block {
if (!_openFunctions) {
_openFunctions = [NSMutableSet new];
}
id b = FMDBReturnAutoreleased([block copy]);
[_openFunctions addObject:b];
/* I tried adding custom functions to release the block when the connection is destroyed- but they seemed to never be called, so we use _openFunctions to store the values instead. */
#if ! __has_feature(objc_arc)
sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
#else
sqlite3_create_function([self sqliteHandle], [name UTF8String], count, SQLITE_UTF8, (__bridge void*)b, &FMDBBlockSQLiteCallBackFunction, 0x00, 0x00);
#endif
}
@end
@implementation FMStatement
@synthesize statement=_statement;
@synthesize query=_query;
@synthesize useCount=_useCount;
@synthesize inUse=_inUse;
- (void)finalize {
[self close];
[super finalize];
}
- (void)dealloc {
[self close];
FMDBRelease(_query);
#if ! __has_feature(objc_arc)
[super dealloc];
#endif
}
- (void)close {
if (_statement) {
sqlite3_finalize(_statement);
_statement = 0x00;
}
_inUse = NO;
}
- (void)reset {
if (_statement) {
sqlite3_reset(_statement);
}
_inUse = NO;
}
- (NSString*)description {
return [NSString stringWithFormat:@"%@ %ld hit(s) for query %@", [super description], _useCount, _query];
}
@end
//
// FMDatabaseAdditions.h
// fmdb
//
// Created by August Mueller on 10/30/05.
// Copyright 2005 Flying Meat Inc.. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "FMDatabase.h"
/** Category of additions for `<FMDatabase>` class.
### See also
- `<FMDatabase>`
*/
@interface FMDatabase (FMDatabaseAdditions)
///----------------------------------------
/// @name Return results of SQL to variable
///----------------------------------------
/** Return `int` value for query
@param query The SQL query to be performed.
@param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
@return `int` value.
@note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project.
*/
- (int)intForQuery:(NSString*)query, ...;
/** Return `long` value for query
@param query The SQL query to be performed.
@param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
@return `long` value.
@note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project.
*/
- (long)longForQuery:(NSString*)query, ...;
/** Return `BOOL` value for query
@param query The SQL query to be performed.
@param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
@return `BOOL` value.
@note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project.
*/
- (BOOL)boolForQuery:(NSString*)query, ...;
/** Return `double` value for query
@param query The SQL query to be performed.
@param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
@return `double` value.
@note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project.
*/
- (double)doubleForQuery:(NSString*)query, ...;
/** Return `NSString` value for query
@param query The SQL query to be performed.
@param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
@return `NSString` value.
@note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project.
*/
- (NSString*)stringForQuery:(NSString*)query, ...;
/** Return `NSData` value for query
@param query The SQL query to be performed.
@param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
@return `NSData` value.
@note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project.
*/
- (NSData*)dataForQuery:(NSString*)query, ...;
/** Return `NSDate` value for query
@param query The SQL query to be performed.
@param ... A list of parameters that will be bound to the `?` placeholders in the SQL query.
@return `NSDate` value.
@note To use this method from Swift, you must include `FMDatabaseAdditionsVariadic.swift` in your project.
*/
- (NSDate*)dateForQuery:(NSString*)query, ...;
// Notice that there's no dataNoCopyForQuery:.
// That would be a bad idea, because we close out the result set, and then what
// happens to the data that we just didn't copy? Who knows, not I.
///--------------------------------
/// @name Schema related operations
///--------------------------------
/** Does table exist in database?
@param tableName The name of the table being looked for.
@return `YES` if table found; `NO` if not found.
*/
- (BOOL)tableExists:(NSString*)tableName;
/** The schema of the database.
This will be the schema for the entire database. For each entity, each row of the result set will include the following fields:
- `type` - The type of entity (e.g. table, index, view, or trigger)
- `name` - The name of the object
- `tbl_name` - The name of the table to which the object references
- `rootpage` - The page number of the root b-tree page for tables and indices
- `sql` - The SQL that created the entity
@return `FMResultSet` of schema; `nil` on error.
@see [SQLite File Format](http://www.sqlite.org/fileformat.html)
*/
- (FMResultSet*)getSchema;
/** The schema of the database.
This will be the schema for a particular table as report by SQLite `PRAGMA`, for example:
PRAGMA table_info('employees')
This will report:
- `cid` - The column ID number
- `name` - The name of the column
- `type` - The data type specified for the column
- `notnull` - whether the field is defined as NOT NULL (i.e. values required)
- `dflt_value` - The default value for the column
- `pk` - Whether the field is part of the primary key of the table
@param tableName The name of the table for whom the schema will be returned.
@return `FMResultSet` of schema; `nil` on error.
@see [table_info](http://www.sqlite.org/pragma.html#pragma_table_info)
*/
- (FMResultSet*)getTableSchema:(NSString*)tableName;
/** Test to see if particular column exists for particular table in database
@param columnName The name of the column.
@param tableName The name of the table.
@return `YES` if column exists in table in question; `NO` otherwise.
*/
- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName;
/** Test to see if particular column exists for particular table in database
@param columnName The name of the column.
@param tableName The name of the table.
@return `YES` if column exists in table in question; `NO` otherwise.
@see columnExists:inTableWithName:
@warning Deprecated - use `<columnExists:inTableWithName:>` instead.
*/
- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated));
/** Validate SQL statement
This validates SQL statement by performing `sqlite3_prepare_v2`, but not returning the results, but instead immediately calling `sqlite3_finalize`.
@param sql The SQL statement being validated.
@param error This is a pointer to a `NSError` object that will receive the autoreleased `NSError` object if there was any error. If this is `nil`, no `NSError` result will be returned.
@return `YES` if validation succeeded without incident; `NO` otherwise.
*/
- (BOOL)validateSQL:(NSString*)sql error:(NSError**)error;
#if SQLITE_VERSION_NUMBER >= 3007017
///-----------------------------------
/// @name Application identifier tasks
///-----------------------------------
/** Retrieve application ID
@return The `uint32_t` numeric value of the application ID.
@see setApplicationID:
*/
- (uint32_t)applicationID;
/** Set the application ID
@param appID The `uint32_t` numeric value of the application ID.
@see applicationID
*/
- (void)setApplicationID:(uint32_t)appID;
#if TARGET_OS_MAC && !TARGET_OS_IPHONE
/** Retrieve application ID string
@return The `NSString` value of the application ID.
@see setApplicationIDString:
*/
- (NSString*)applicationIDString;
/** Set the application ID string
@param string The `NSString` value of the application ID.
@see applicationIDString
*/
- (void)setApplicationIDString:(NSString*)string;
#endif
#endif
///-----------------------------------
/// @name user version identifier tasks
///-----------------------------------
/** Retrieve user version
@return The `uint32_t` numeric value of the user version.
@see setUserVersion:
*/
- (uint32_t)userVersion;
/** Set the user-version
@param version The `uint32_t` numeric value of the user version.
@see userVersion
*/
- (void)setUserVersion:(uint32_t)version;
@end
//
// FMDatabaseAdditions.m
// fmdb
//
// Created by August Mueller on 10/30/05.
// Copyright 2005 Flying Meat Inc.. All rights reserved.
//
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
#import "TargetConditionals.h"
@interface FMDatabase (PrivateStuff)
- (FMResultSet *)executeQuery:(NSString *)sql withArgumentsInArray:(NSArray*)arrayArgs orDictionary:(NSDictionary *)dictionaryArgs orVAList:(va_list)args;
@end
@implementation FMDatabase (FMDatabaseAdditions)
#define RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(type, sel) \
va_list args; \
va_start(args, query); \
FMResultSet *resultSet = [self executeQuery:query withArgumentsInArray:0x00 orDictionary:0x00 orVAList:args]; \
va_end(args); \
if (![resultSet next]) { return (type)0; } \
type ret = [resultSet sel:0]; \
[resultSet close]; \
[resultSet setParentDB:nil]; \
return ret;
- (NSString*)stringForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSString *, stringForColumnIndex);
}
- (int)intForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(int, intForColumnIndex);
}
- (long)longForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(long, longForColumnIndex);
}
- (BOOL)boolForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(BOOL, boolForColumnIndex);
}
- (double)doubleForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(double, doubleForColumnIndex);
}
- (NSData*)dataForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSData *, dataForColumnIndex);
}
- (NSDate*)dateForQuery:(NSString*)query, ... {
RETURN_RESULT_FOR_QUERY_WITH_SELECTOR(NSDate *, dateForColumnIndex);
}
- (BOOL)tableExists:(NSString*)tableName {
tableName = [tableName lowercaseString];
FMResultSet *rs = [self executeQuery:@"select [sql] from sqlite_master where [type] = 'table' and lower(name) = ?", tableName];
//if at least one next exists, table exists
BOOL returnBool = [rs next];
//close and free object
[rs close];
return returnBool;
}
/*
get table with list of tables: result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING]
check if table exist in database (patch from OZLB)
*/
- (FMResultSet*)getSchema {
//result colums: type[STRING], name[STRING],tbl_name[STRING],rootpage[INTEGER],sql[STRING]
FMResultSet *rs = [self executeQuery:@"SELECT type, name, tbl_name, rootpage, sql FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type != 'meta' AND name NOT LIKE 'sqlite_%' ORDER BY tbl_name, type DESC, name"];
return rs;
}
/*
get table schema: result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER]
*/
- (FMResultSet*)getTableSchema:(NSString*)tableName {
//result colums: cid[INTEGER], name,type [STRING], notnull[INTEGER], dflt_value[],pk[INTEGER]
FMResultSet *rs = [self executeQuery:[NSString stringWithFormat: @"pragma table_info('%@')", tableName]];
return rs;
}
- (BOOL)columnExists:(NSString*)columnName inTableWithName:(NSString*)tableName {
BOOL returnBool = NO;
tableName = [tableName lowercaseString];
columnName = [columnName lowercaseString];
FMResultSet *rs = [self getTableSchema:tableName];
//check if column is present in table schema
while ([rs next]) {
if ([[[rs stringForColumn:@"name"] lowercaseString] isEqualToString:columnName]) {
returnBool = YES;
break;
}
}
//If this is not done FMDatabase instance stays out of pool
[rs close];
return returnBool;
}
#if SQLITE_VERSION_NUMBER >= 3007017
- (uint32_t)applicationID {
uint32_t r = 0;
FMResultSet *rs = [self executeQuery:@"pragma application_id"];
if ([rs next]) {
r = (uint32_t)[rs longLongIntForColumnIndex:0];
}
[rs close];
return r;
}
- (void)setApplicationID:(uint32_t)appID {
NSString *query = [NSString stringWithFormat:@"pragma application_id=%d", appID];
FMResultSet *rs = [self executeQuery:query];
[rs next];
[rs close];
}
#if TARGET_OS_MAC && !TARGET_OS_IPHONE
- (NSString*)applicationIDString {
NSString *s = NSFileTypeForHFSTypeCode([self applicationID]);
assert([s length] == 6);
s = [s substringWithRange:NSMakeRange(1, 4)];
return s;
}
- (void)setApplicationIDString:(NSString*)s {
if ([s length] != 4) {
NSLog(@"setApplicationIDString: string passed is not exactly 4 chars long. (was %ld)", [s length]);
}
[self setApplicationID:NSHFSTypeCodeFromFileType([NSString stringWithFormat:@"'%@'", s])];
}
#endif
#endif
- (uint32_t)userVersion {
uint32_t r = 0;
FMResultSet *rs = [self executeQuery:@"pragma user_version"];
if ([rs next]) {
r = (uint32_t)[rs longLongIntForColumnIndex:0];
}
[rs close];
return r;
}
- (void)setUserVersion:(uint32_t)version {
NSString *query = [NSString stringWithFormat:@"pragma user_version = %d", version];
FMResultSet *rs = [self executeQuery:query];
[rs next];
[rs close];
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
- (BOOL)columnExists:(NSString*)tableName columnName:(NSString*)columnName __attribute__ ((deprecated)) {
return [self columnExists:columnName inTableWithName:tableName];
}
#pragma clang diagnostic pop
- (BOOL)validateSQL:(NSString*)sql error:(NSError**)error {
sqlite3_stmt *pStmt = NULL;
BOOL validationSucceeded = YES;
int rc = sqlite3_prepare_v2(_db, [sql UTF8String], -1, &pStmt, 0);
if (rc != SQLITE_OK) {
validationSucceeded = NO;
if (error) {
*error = [NSError errorWithDomain:NSCocoaErrorDomain
code:[self lastErrorCode]
userInfo:[NSDictionary dictionaryWithObject:[self lastErrorMessage]
forKey:NSLocalizedDescriptionKey]];
}
}
sqlite3_finalize(pStmt);
return validationSucceeded;
}
@end
//
// FMDatabasePool.h
// fmdb
//
// Created by August Mueller on 6/22/11.
// Copyright 2011 Flying Meat Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "sqlite3.h"
@class FMDatabase;
/** Pool of `<FMDatabase>` objects.
### See also
- `<FMDatabaseQueue>`
- `<FMDatabase>`
@warning Before using `FMDatabasePool`, please consider using `<FMDatabaseQueue>` instead.
If you really really really know what you're doing and `FMDatabasePool` is what
you really really need (ie, you're using a read only database), OK you can use
it. But just be careful not to deadlock!
For an example on deadlocking, search for:
`ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD`
in the main.m file.
*/
@interface FMDatabasePool : NSObject {
NSString *_path;
dispatch_queue_t _lockQueue;
NSMutableArray *_databaseInPool;
NSMutableArray *_databaseOutPool;
__unsafe_unretained id _delegate;
NSUInteger _maximumNumberOfDatabasesToCreate;
int _openFlags;
}
/** Database path */
@property (atomic, retain) NSString *path;
/** Delegate object */
@property (atomic, assign) id delegate;
/** Maximum number of databases to create */
@property (atomic, assign) NSUInteger maximumNumberOfDatabasesToCreate;
/** Open flags */
@property (atomic, readonly) int openFlags;
///---------------------
/// @name Initialization
///---------------------
/** Create pool using path.
@param aPath The file path of the database.
@return The `FMDatabasePool` object. `nil` on error.
*/
+ (instancetype)databasePoolWithPath:(NSString*)aPath;
/** Create pool using path and specified flags
@param aPath The file path of the database.
@param openFlags Flags passed to the openWithFlags method of the database
@return The `FMDatabasePool` object. `nil` on error.
*/
+ (instancetype)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags;
/** Create pool using path.
@param aPath The file path of the database.
@return The `FMDatabasePool` object. `nil` on error.
*/
- (instancetype)initWithPath:(NSString*)aPath;
/** Create pool using path and specified flags.
@param aPath The file path of the database.
@param openFlags Flags passed to the openWithFlags method of the database
@return The `FMDatabasePool` object. `nil` on error.
*/
- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags;
///------------------------------------------------
/// @name Keeping track of checked in/out databases
///------------------------------------------------
/** Number of checked-in databases in pool
@returns Number of databases
*/
- (NSUInteger)countOfCheckedInDatabases;
/** Number of checked-out databases in pool
@returns Number of databases
*/
- (NSUInteger)countOfCheckedOutDatabases;
/** Total number of databases in pool
@returns Number of databases
*/
- (NSUInteger)countOfOpenDatabases;
/** Release all databases in pool */
- (void)releaseAllDatabases;
///------------------------------------------
/// @name Perform database operations in pool
///------------------------------------------
/** Synchronously perform database operations in pool.
@param block The code to be run on the `FMDatabasePool` pool.
*/
- (void)inDatabase:(void (^)(FMDatabase *db))block;
/** Synchronously perform database operations in pool using transaction.
@param block The code to be run on the `FMDatabasePool` pool.
*/
- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block;
/** Synchronously perform database operations in pool using deferred transaction.
@param block The code to be run on the `FMDatabasePool` pool.
*/
- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block;
#if SQLITE_VERSION_NUMBER >= 3007000
/** Synchronously perform database operations in pool using save point.
@param block The code to be run on the `FMDatabasePool` pool.
@return `NSError` object if error; `nil` if successful.
@warning You can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. If you need to nest, use `<[FMDatabase startSavePointWithName:error:]>` instead.
*/
- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block;
#endif
@end
/** FMDatabasePool delegate category
This is a category that defines the protocol for the FMDatabasePool delegate
*/
@interface NSObject (FMDatabasePoolDelegate)
/** Asks the delegate whether database should be added to the pool.
@param pool The `FMDatabasePool` object.
@param database The `FMDatabase` object.
@return `YES` if it should add database to pool; `NO` if not.
*/
- (BOOL)databasePool:(FMDatabasePool*)pool shouldAddDatabaseToPool:(FMDatabase*)database;
/** Tells the delegate that database was added to the pool.
@param pool The `FMDatabasePool` object.
@param database The `FMDatabase` object.
*/
- (void)databasePool:(FMDatabasePool*)pool didAddDatabase:(FMDatabase*)database;
@end
//
// FMDatabasePool.m
// fmdb
//
// Created by August Mueller on 6/22/11.
// Copyright 2011 Flying Meat Inc. All rights reserved.
//
#import "FMDatabasePool.h"
#import "FMDatabase.h"
@interface FMDatabasePool()
- (void)pushDatabaseBackInPool:(FMDatabase*)db;
- (FMDatabase*)db;
@end
@implementation FMDatabasePool
@synthesize path=_path;
@synthesize delegate=_delegate;
@synthesize maximumNumberOfDatabasesToCreate=_maximumNumberOfDatabasesToCreate;
@synthesize openFlags=_openFlags;
+ (instancetype)databasePoolWithPath:(NSString*)aPath {
return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath]);
}
+ (instancetype)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags {
return FMDBReturnAutoreleased([[self alloc] initWithPath:aPath flags:openFlags]);
}
- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags {
self = [super init];
if (self != nil) {
_path = [aPath copy];
_lockQueue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL);
_databaseInPool = FMDBReturnRetained([NSMutableArray array]);
_databaseOutPool = FMDBReturnRetained([NSMutableArray array]);
_openFlags = openFlags;
}
return self;
}
- (instancetype)initWithPath:(NSString*)aPath
{
// default flags for sqlite3_open
return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE];
}
- (instancetype)init {
return [self initWithPath:nil];
}
- (void)dealloc {
_delegate = 0x00;
FMDBRelease(_path);
FMDBRelease(_databaseInPool);
FMDBRelease(_databaseOutPool);
if (_lockQueue) {
FMDBDispatchQueueRelease(_lockQueue);
_lockQueue = 0x00;
}
#if ! __has_feature(objc_arc)
[super dealloc];
#endif
}
- (void)executeLocked:(void (^)(void))aBlock {
dispatch_sync(_lockQueue, aBlock);
}
- (void)pushDatabaseBackInPool:(FMDatabase*)db {
if (!db) { // db can be null if we set an upper bound on the # of databases to create.
return;
}
[self executeLocked:^() {
if ([self->_databaseInPool containsObject:db]) {
[[NSException exceptionWithName:@"Database already in pool" reason:@"The FMDatabase being put back into the pool is already present in the pool" userInfo:nil] raise];
}
[self->_databaseInPool addObject:db];
[self->_databaseOutPool removeObject:db];
}];
}
- (FMDatabase*)db {
__block FMDatabase *db;
[self executeLocked:^() {
db = [self->_databaseInPool lastObject];
BOOL shouldNotifyDelegate = NO;
if (db) {
[self->_databaseOutPool addObject:db];
[self->_databaseInPool removeLastObject];
}
else {
if (self->_maximumNumberOfDatabasesToCreate) {
NSUInteger currentCount = [self->_databaseOutPool count] + [self->_databaseInPool count];
if (currentCount >= self->_maximumNumberOfDatabasesToCreate) {
NSLog(@"Maximum number of databases (%ld) has already been reached!", (long)currentCount);
return;
}
}
db = [FMDatabase databaseWithPath:self->_path];
shouldNotifyDelegate = YES;
}
//This ensures that the db is opened before returning
#if SQLITE_VERSION_NUMBER >= 3005000
BOOL success = [db openWithFlags:self->_openFlags];
#else
BOOL success = [db open];
#endif
if (success) {
if ([self->_delegate respondsToSelector:@selector(databasePool:shouldAddDatabaseToPool:)] && ![self->_delegate databasePool:self shouldAddDatabaseToPool:db]) {
[db close];
db = 0x00;
}
else {
//It should not get added in the pool twice if lastObject was found
if (![self->_databaseOutPool containsObject:db]) {
[self->_databaseOutPool addObject:db];
if (shouldNotifyDelegate && [self->_delegate respondsToSelector:@selector(databasePool:didAddDatabase:)]) {
[self->_delegate databasePool:self didAddDatabase:db];
}
}
}
}
else {
NSLog(@"Could not open up the database at path %@", self->_path);
db = 0x00;
}
}];
return db;
}
- (NSUInteger)countOfCheckedInDatabases {
__block NSUInteger count;
[self executeLocked:^() {
count = [self->_databaseInPool count];
}];
return count;
}
- (NSUInteger)countOfCheckedOutDatabases {
__block NSUInteger count;
[self executeLocked:^() {
count = [self->_databaseOutPool count];
}];
return count;
}
- (NSUInteger)countOfOpenDatabases {
__block NSUInteger count;
[self executeLocked:^() {
count = [self->_databaseOutPool count] + [self->_databaseInPool count];
}];
return count;
}
- (void)releaseAllDatabases {
[self executeLocked:^() {
[self->_databaseOutPool removeAllObjects];
[self->_databaseInPool removeAllObjects];
}];
}
- (void)inDatabase:(void (^)(FMDatabase *db))block {
FMDatabase *db = [self db];
block(db);
[self pushDatabaseBackInPool:db];
}
- (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block {
BOOL shouldRollback = NO;
FMDatabase *db = [self db];
if (useDeferred) {
[db beginDeferredTransaction];
}
else {
[db beginTransaction];
}
block(db, &shouldRollback);
if (shouldRollback) {
[db rollback];
}
else {
[db commit];
}
[self pushDatabaseBackInPool:db];
}
- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block {
[self beginTransaction:YES withBlock:block];
}
- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block {
[self beginTransaction:NO withBlock:block];
}
#if SQLITE_VERSION_NUMBER >= 3007000
- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block {
static unsigned long savePointIdx = 0;
NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++];
BOOL shouldRollback = NO;
FMDatabase *db = [self db];
NSError *err = 0x00;
if (![db startSavePointWithName:name error:&err]) {
[self pushDatabaseBackInPool:db];
return err;
}
block(db, &shouldRollback);
if (shouldRollback) {
// We need to rollback and release this savepoint to remove it
[db rollbackToSavePointWithName:name error:&err];
}
[db releaseSavePointWithName:name error:&err];
[self pushDatabaseBackInPool:db];
return err;
}
#endif
@end
//
// FMDatabaseQueue.h
// fmdb
//
// Created by August Mueller on 6/22/11.
// Copyright 2011 Flying Meat Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "sqlite3.h"
@class FMDatabase;
/** To perform queries and updates on multiple threads, you'll want to use `FMDatabaseQueue`.
Using a single instance of `<FMDatabase>` from multiple threads at once is a bad idea. It has always been OK to make a `<FMDatabase>` object *per thread*. Just don't share a single instance across threads, and definitely not across multiple threads at the same time.
Instead, use `FMDatabaseQueue`. Here's how to use it:
First, make your queue.
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:aPath];
Then use it like so:
[queue inDatabase:^(FMDatabase *db) {
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];
FMResultSet *rs = [db executeQuery:@"select * from foo"];
while ([rs next]) {
//…
}
}];
An easy way to wrap things up in a transaction can be done like this:
[queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:1]];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:2]];
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];
if (whoopsSomethingWrongHappened) {
*rollback = YES;
return;
}
// etc…
[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:4]];
}];
`FMDatabaseQueue` will run the blocks on a serialized queue (hence the name of the class). So if you call `FMDatabaseQueue`'s methods from multiple threads at the same time, they will be executed in the order they are received. This way queries and updates won't step on each other's toes, and every one is happy.
### See also
- `<FMDatabase>`
@warning Do not instantiate a single `<FMDatabase>` object and use it across multiple threads. Use `FMDatabaseQueue` instead.
@warning The calls to `FMDatabaseQueue`'s methods are blocking. So even though you are passing along blocks, they will **not** be run on another thread.
*/
@interface FMDatabaseQueue : NSObject {
NSString *_path;
dispatch_queue_t _queue;
FMDatabase *_db;
int _openFlags;
}
/** Path of database */
@property (atomic, retain) NSString *path;
/** Open flags */
@property (atomic, readonly) int openFlags;
///----------------------------------------------------
/// @name Initialization, opening, and closing of queue
///----------------------------------------------------
/** Create queue using path.
@param aPath The file path of the database.
@return The `FMDatabaseQueue` object. `nil` on error.
*/
+ (instancetype)databaseQueueWithPath:(NSString*)aPath;
/** Create queue using path and specified flags.
@param aPath The file path of the database.
@param openFlags Flags passed to the openWithFlags method of the database
@return The `FMDatabaseQueue` object. `nil` on error.
*/
+ (instancetype)databaseQueueWithPath:(NSString*)aPath flags:(int)openFlags;
/** Create queue using path.
@param aPath The file path of the database.
@return The `FMDatabaseQueue` object. `nil` on error.
*/
- (instancetype)initWithPath:(NSString*)aPath;
/** Create queue using path and specified flags.
@param aPath The file path of the database.
@param openFlags Flags passed to the openWithFlags method of the database
@return The `FMDatabaseQueue` object. `nil` on error.
*/
- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags;
/** Returns the Class of 'FMDatabase' subclass, that will be used to instantiate database object.
Subclasses can override this method to return specified Class of 'FMDatabase' subclass.
@return The Class of 'FMDatabase' subclass, that will be used to instantiate database object.
*/
+ (Class)databaseClass;
/** Close database used by queue. */
- (void)close;
///-----------------------------------------------
/// @name Dispatching database operations to queue
///-----------------------------------------------
/** Synchronously perform database operations on queue.
@param block The code to be run on the queue of `FMDatabaseQueue`
*/
- (void)inDatabase:(void (^)(FMDatabase *db))block;
/** Synchronously perform database operations on queue, using transactions.
@param block The code to be run on the queue of `FMDatabaseQueue`
*/
- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block;
/** Synchronously perform database operations on queue, using deferred transactions.
@param block The code to be run on the queue of `FMDatabaseQueue`
*/
- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block;
///-----------------------------------------------
/// @name Dispatching database operations to queue
///-----------------------------------------------
/** Synchronously perform database operations using save point.
@param block The code to be run on the queue of `FMDatabaseQueue`
*/
#if SQLITE_VERSION_NUMBER >= 3007000
// NOTE: you can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock.
// If you need to nest, use FMDatabase's startSavePointWithName:error: instead.
- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block;
#endif
@end
//
// FMDatabaseQueue.m
// fmdb
//
// Created by August Mueller on 6/22/11.
// Copyright 2011 Flying Meat Inc. All rights reserved.
//
#import "FMDatabaseQueue.h"
#import "FMDatabase.h"
/*
Note: we call [self retain]; before using dispatch_sync, just incase
FMDatabaseQueue is released on another thread and we're in the middle of doing
something in dispatch_sync
*/
/*
* A key used to associate the FMDatabaseQueue object with the dispatch_queue_t it uses.
* This in turn is used for deadlock detection by seeing if inDatabase: is called on
* the queue's dispatch queue, which should not happen and causes a deadlock.
*/
static const void * const kDispatchQueueSpecificKey = &kDispatchQueueSpecificKey;
@implementation FMDatabaseQueue
@synthesize path = _path;
@synthesize openFlags = _openFlags;
+ (instancetype)databaseQueueWithPath:(NSString*)aPath {
FMDatabaseQueue *q = [[self alloc] initWithPath:aPath];
FMDBAutorelease(q);
return q;
}
+ (instancetype)databaseQueueWithPath:(NSString*)aPath flags:(int)openFlags {
FMDatabaseQueue *q = [[self alloc] initWithPath:aPath flags:openFlags];
FMDBAutorelease(q);
return q;
}
+ (Class)databaseClass {
return [FMDatabase class];
}
- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags {
self = [super init];
if (self != nil) {
_db = [[[self class] databaseClass] databaseWithPath:aPath];
FMDBRetain(_db);
#if SQLITE_VERSION_NUMBER >= 3005000
BOOL success = [_db openWithFlags:openFlags];
#else
BOOL success = [_db open];
#endif
if (!success) {
NSLog(@"Could not create database queue for path %@", aPath);
FMDBRelease(self);
return 0x00;
}
_path = FMDBReturnRetained(aPath);
_queue = dispatch_queue_create([[NSString stringWithFormat:@"fmdb.%@", self] UTF8String], NULL);
dispatch_queue_set_specific(_queue, kDispatchQueueSpecificKey, (__bridge void *)self, NULL);
_openFlags = openFlags;
}
return self;
}
- (instancetype)initWithPath:(NSString*)aPath {
// default flags for sqlite3_open
return [self initWithPath:aPath flags:SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE];
}
- (instancetype)init {
return [self initWithPath:nil];
}
- (void)dealloc {
FMDBRelease(_db);
FMDBRelease(_path);
if (_queue) {
FMDBDispatchQueueRelease(_queue);
_queue = 0x00;
}
#if ! __has_feature(objc_arc)
[super dealloc];
#endif
}
- (void)close {
FMDBRetain(self);
dispatch_sync(_queue, ^() {
[self->_db close];
FMDBRelease(_db);
self->_db = 0x00;
});
FMDBRelease(self);
}
- (FMDatabase*)database {
if (!_db) {
_db = FMDBReturnRetained([FMDatabase databaseWithPath:_path]);
#if SQLITE_VERSION_NUMBER >= 3005000
BOOL success = [_db openWithFlags:_openFlags];
#else
BOOL success = [_db open];
#endif
if (!success) {
NSLog(@"FMDatabaseQueue could not reopen database for path %@", _path);
FMDBRelease(_db);
_db = 0x00;
return 0x00;
}
}
return _db;
}
- (void)inDatabase:(void (^)(FMDatabase *db))block {
/* Get the currently executing queue (which should probably be nil, but in theory could be another DB queue
* and then check it against self to make sure we're not about to deadlock. */
FMDatabaseQueue *currentSyncQueue = (__bridge id)dispatch_get_specific(kDispatchQueueSpecificKey);
assert(currentSyncQueue != self && "inDatabase: was called reentrantly on the same queue, which would lead to a deadlock");
FMDBRetain(self);
dispatch_sync(_queue, ^() {
FMDatabase *db = [self database];
block(db);
if ([db hasOpenResultSets]) {
NSLog(@"Warning: there is at least one open result set around after performing [FMDatabaseQueue inDatabase:]");
#if defined(DEBUG) && DEBUG
NSSet *openSetCopy = FMDBReturnAutoreleased([[db valueForKey:@"_openResultSets"] copy]);
for (NSValue *rsInWrappedInATastyValueMeal in openSetCopy) {
FMResultSet *rs = (FMResultSet *)[rsInWrappedInATastyValueMeal pointerValue];
NSLog(@"query: '%@'", [rs query]);
}
#endif
}
});
FMDBRelease(self);
}
- (void)beginTransaction:(BOOL)useDeferred withBlock:(void (^)(FMDatabase *db, BOOL *rollback))block {
FMDBRetain(self);
dispatch_sync(_queue, ^() {
BOOL shouldRollback = NO;
if (useDeferred) {
[[self database] beginDeferredTransaction];
}
else {
[[self database] beginTransaction];
}
block([self database], &shouldRollback);
if (shouldRollback) {
[[self database] rollback];
}
else {
[[self database] commit];
}
});
FMDBRelease(self);
}
- (void)inDeferredTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block {
[self beginTransaction:YES withBlock:block];
}
- (void)inTransaction:(void (^)(FMDatabase *db, BOOL *rollback))block {
[self beginTransaction:NO withBlock:block];
}
#if SQLITE_VERSION_NUMBER >= 3007000
- (NSError*)inSavePoint:(void (^)(FMDatabase *db, BOOL *rollback))block {
static unsigned long savePointIdx = 0;
__block NSError *err = 0x00;
FMDBRetain(self);
dispatch_sync(_queue, ^() {
NSString *name = [NSString stringWithFormat:@"savePoint%ld", savePointIdx++];
BOOL shouldRollback = NO;
if ([[self database] startSavePointWithName:name error:&err]) {
block([self database], &shouldRollback);
if (shouldRollback) {
// We need to rollback and release this savepoint to remove it
[[self database] rollbackToSavePointWithName:name error:&err];
}
[[self database] releaseSavePointWithName:name error:&err];
}
});
FMDBRelease(self);
return err;
}
#endif
@end
#import <Foundation/Foundation.h>
#import "sqlite3.h"
#ifndef __has_feature // Optional.
#define __has_feature(x) 0 // Compatibility with non-clang compilers.
#endif
#ifndef NS_RETURNS_NOT_RETAINED
#if __has_feature(attribute_ns_returns_not_retained)
#define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained))
#else
#define NS_RETURNS_NOT_RETAINED
#endif
#endif
@class FMDatabase;
@class FMStatement;
/** Represents the results of executing a query on an `<FMDatabase>`.
### See also
- `<FMDatabase>`
*/
@interface FMResultSet : NSObject {
FMDatabase *_parentDB;
FMStatement *_statement;
NSString *_query;
NSMutableDictionary *_columnNameToIndexMap;
}
///-----------------
/// @name Properties
///-----------------
/** Executed query */
@property (atomic, retain) NSString *query;
/** `NSMutableDictionary` mapping column names to numeric index */
@property (readonly) NSMutableDictionary *columnNameToIndexMap;
/** `FMStatement` used by result set. */
@property (atomic, retain) FMStatement *statement;
///------------------------------------
/// @name Creating and closing database
///------------------------------------
/** Create result set from `<FMStatement>`
@param statement A `<FMStatement>` to be performed
@param aDB A `<FMDatabase>` to be used
@return A `FMResultSet` on success; `nil` on failure
*/
+ (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB;
/** Close result set */
- (void)close;
- (void)setParentDB:(FMDatabase *)newDb;
///---------------------------------------
/// @name Iterating through the result set
///---------------------------------------
/** Retrieve next row for result set.
You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one.
@return `YES` if row successfully retrieved; `NO` if end of result set reached
@see hasAnotherRow
*/
- (BOOL)next;
/** Retrieve next row for result set.
You must always invoke `next` or `nextWithError` before attempting to access the values returned in a query, even if you're only expecting one.
@param outErr A 'NSError' object to receive any error object (if any).
@return 'YES' if row successfully retrieved; 'NO' if end of result set reached
@see hasAnotherRow
*/
- (BOOL)nextWithError:(NSError **)outErr;
/** Did the last call to `<next>` succeed in retrieving another row?
@return `YES` if the last call to `<next>` succeeded in retrieving another record; `NO` if not.
@see next
@warning The `hasAnotherRow` method must follow a call to `<next>`. If the previous database interaction was something other than a call to `next`, then this method may return `NO`, whether there is another row of data or not.
*/
- (BOOL)hasAnotherRow;
///---------------------------------------------
/// @name Retrieving information from result set
///---------------------------------------------
/** How many columns in result set
@return Integer value of the number of columns.
*/
- (int)columnCount;
/** Column index for column name
@param columnName `NSString` value of the name of the column.
@return Zero-based index for column.
*/
- (int)columnIndexForName:(NSString*)columnName;
/** Column name for column index
@param columnIdx Zero-based index for column.
@return columnName `NSString` value of the name of the column.
*/
- (NSString*)columnNameForIndex:(int)columnIdx;
/** Result set integer value for column.
@param columnName `NSString` value of the name of the column.
@return `int` value of the result set's column.
*/
- (int)intForColumn:(NSString*)columnName;
/** Result set integer value for column.
@param columnIdx Zero-based index for column.
@return `int` value of the result set's column.
*/
- (int)intForColumnIndex:(int)columnIdx;
/** Result set `long` value for column.
@param columnName `NSString` value of the name of the column.
@return `long` value of the result set's column.
*/
- (long)longForColumn:(NSString*)columnName;
/** Result set long value for column.
@param columnIdx Zero-based index for column.
@return `long` value of the result set's column.
*/
- (long)longForColumnIndex:(int)columnIdx;
/** Result set `long long int` value for column.
@param columnName `NSString` value of the name of the column.
@return `long long int` value of the result set's column.
*/
- (long long int)longLongIntForColumn:(NSString*)columnName;
/** Result set `long long int` value for column.
@param columnIdx Zero-based index for column.
@return `long long int` value of the result set's column.
*/
- (long long int)longLongIntForColumnIndex:(int)columnIdx;
/** Result set `unsigned long long int` value for column.
@param columnName `NSString` value of the name of the column.
@return `unsigned long long int` value of the result set's column.
*/
- (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName;
/** Result set `unsigned long long int` value for column.
@param columnIdx Zero-based index for column.
@return `unsigned long long int` value of the result set's column.
*/
- (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx;
/** Result set `BOOL` value for column.
@param columnName `NSString` value of the name of the column.
@return `BOOL` value of the result set's column.
*/
- (BOOL)boolForColumn:(NSString*)columnName;
/** Result set `BOOL` value for column.
@param columnIdx Zero-based index for column.
@return `BOOL` value of the result set's column.
*/
- (BOOL)boolForColumnIndex:(int)columnIdx;
/** Result set `double` value for column.
@param columnName `NSString` value of the name of the column.
@return `double` value of the result set's column.
*/
- (double)doubleForColumn:(NSString*)columnName;
/** Result set `double` value for column.
@param columnIdx Zero-based index for column.
@return `double` value of the result set's column.
*/
- (double)doubleForColumnIndex:(int)columnIdx;
/** Result set `NSString` value for column.
@param columnName `NSString` value of the name of the column.
@return `NSString` value of the result set's column.
*/
- (NSString*)stringForColumn:(NSString*)columnName;
/** Result set `NSString` value for column.
@param columnIdx Zero-based index for column.
@return `NSString` value of the result set's column.
*/
- (NSString*)stringForColumnIndex:(int)columnIdx;
/** Result set `NSDate` value for column.
@param columnName `NSString` value of the name of the column.
@return `NSDate` value of the result set's column.
*/
- (NSDate*)dateForColumn:(NSString*)columnName;
/** Result set `NSDate` value for column.
@param columnIdx Zero-based index for column.
@return `NSDate` value of the result set's column.
*/
- (NSDate*)dateForColumnIndex:(int)columnIdx;
/** Result set `NSData` value for column.
This is useful when storing binary data in table (such as image or the like).
@param columnName `NSString` value of the name of the column.
@return `NSData` value of the result set's column.
*/
- (NSData*)dataForColumn:(NSString*)columnName;
/** Result set `NSData` value for column.
@param columnIdx Zero-based index for column.
@return `NSData` value of the result set's column.
*/
- (NSData*)dataForColumnIndex:(int)columnIdx;
/** Result set `(const unsigned char *)` value for column.
@param columnName `NSString` value of the name of the column.
@return `(const unsigned char *)` value of the result set's column.
*/
- (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName;
/** Result set `(const unsigned char *)` value for column.
@param columnIdx Zero-based index for column.
@return `(const unsigned char *)` value of the result set's column.
*/
- (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx;
/** Result set object for column.
@param columnName `NSString` value of the name of the column.
@return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object.
@see objectForKeyedSubscript:
*/
- (id)objectForColumnName:(NSString*)columnName;
/** Result set object for column.
@param columnIdx Zero-based index for column.
@return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object.
@see objectAtIndexedSubscript:
*/
- (id)objectForColumnIndex:(int)columnIdx;
/** Result set object for column.
This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported:
id result = rs[@"employee_name"];
This simplified syntax is equivalent to calling:
id result = [rs objectForKeyedSubscript:@"employee_name"];
which is, it turns out, equivalent to calling:
id result = [rs objectForColumnName:@"employee_name"];
@param columnName `NSString` value of the name of the column.
@return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object.
*/
- (id)objectForKeyedSubscript:(NSString *)columnName;
/** Result set object for column.
This method allows the use of the "boxed" syntax supported in Modern Objective-C. For example, by defining this method, the following syntax is now supported:
id result = rs[0];
This simplified syntax is equivalent to calling:
id result = [rs objectForKeyedSubscript:0];
which is, it turns out, equivalent to calling:
id result = [rs objectForColumnName:0];
@param columnIdx Zero-based index for column.
@return Either `NSNumber`, `NSString`, `NSData`, or `NSNull`. If the column was `NULL`, this returns `[NSNull null]` object.
*/
- (id)objectAtIndexedSubscript:(int)columnIdx;
/** Result set `NSData` value for column.
@param columnName `NSString` value of the name of the column.
@return `NSData` value of the result set's column.
@warning If you are going to use this data after you iterate over the next row, or after you close the
result set, make sure to make a copy of the data first (or just use `<dataForColumn:>`/`<dataForColumnIndex:>`)
If you don't, you're going to be in a world of hurt when you try and use the data.
*/
- (NSData*)dataNoCopyForColumn:(NSString*)columnName NS_RETURNS_NOT_RETAINED;
/** Result set `NSData` value for column.
@param columnIdx Zero-based index for column.
@return `NSData` value of the result set's column.
@warning If you are going to use this data after you iterate over the next row, or after you close the
result set, make sure to make a copy of the data first (or just use `<dataForColumn:>`/`<dataForColumnIndex:>`)
If you don't, you're going to be in a world of hurt when you try and use the data.
*/
- (NSData*)dataNoCopyForColumnIndex:(int)columnIdx NS_RETURNS_NOT_RETAINED;
/** Is the column `NULL`?
@param columnIdx Zero-based index for column.
@return `YES` if column is `NULL`; `NO` if not `NULL`.
*/
- (BOOL)columnIndexIsNull:(int)columnIdx;
/** Is the column `NULL`?
@param columnName `NSString` value of the name of the column.
@return `YES` if column is `NULL`; `NO` if not `NULL`.
*/
- (BOOL)columnIsNull:(NSString*)columnName;
/** Returns a dictionary of the row results mapped to case sensitive keys of the column names.
@returns `NSDictionary` of the row results.
@warning The keys to the dictionary are case sensitive of the column names.
*/
- (NSDictionary*)resultDictionary;
/** Returns a dictionary of the row results
@see resultDictionary
@warning **Deprecated**: Please use `<resultDictionary>` instead. Also, beware that `<resultDictionary>` is case sensitive!
*/
- (NSDictionary*)resultDict __attribute__ ((deprecated));
///-----------------------------
/// @name Key value coding magic
///-----------------------------
/** Performs `setValue` to yield support for key value observing.
@param object The object for which the values will be set. This is the key-value-coding compliant object that you might, for example, observe.
*/
- (void)kvcMagic:(id)object;
@end
#import "FMResultSet.h"
#import "FMDatabase.h"
#import "unistd.h"
@interface FMDatabase ()
- (void)resultSetDidClose:(FMResultSet *)resultSet;
@end
@implementation FMResultSet
@synthesize query=_query;
@synthesize statement=_statement;
+ (instancetype)resultSetWithStatement:(FMStatement *)statement usingParentDatabase:(FMDatabase*)aDB {
FMResultSet *rs = [[FMResultSet alloc] init];
[rs setStatement:statement];
[rs setParentDB:aDB];
NSParameterAssert(![statement inUse]);
[statement setInUse:YES]; // weak reference
return FMDBReturnAutoreleased(rs);
}
- (void)finalize {
[self close];
[super finalize];
}
- (void)dealloc {
[self close];
FMDBRelease(_query);
_query = nil;
FMDBRelease(_columnNameToIndexMap);
_columnNameToIndexMap = nil;
#if ! __has_feature(objc_arc)
[super dealloc];
#endif
}
- (void)close {
[_statement reset];
FMDBRelease(_statement);
_statement = nil;
// we don't need this anymore... (i think)
//[_parentDB setInUse:NO];
[_parentDB resultSetDidClose:self];
_parentDB = nil;
}
- (int)columnCount {
return sqlite3_column_count([_statement statement]);
}
- (NSMutableDictionary *)columnNameToIndexMap {
if (!_columnNameToIndexMap) {
int columnCount = sqlite3_column_count([_statement statement]);
_columnNameToIndexMap = [[NSMutableDictionary alloc] initWithCapacity:(NSUInteger)columnCount];
int columnIdx = 0;
for (columnIdx = 0; columnIdx < columnCount; columnIdx++) {
[_columnNameToIndexMap setObject:[NSNumber numberWithInt:columnIdx]
forKey:[[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)] lowercaseString]];
}
}
return _columnNameToIndexMap;
}
- (void)kvcMagic:(id)object {
int columnCount = sqlite3_column_count([_statement statement]);
int columnIdx = 0;
for (columnIdx = 0; columnIdx < columnCount; columnIdx++) {
const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx);
// check for a null row
if (c) {
NSString *s = [NSString stringWithUTF8String:c];
[object setValue:s forKey:[NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)]];
}
}
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
- (NSDictionary*)resultDict {
NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]);
if (num_cols > 0) {
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols];
NSEnumerator *columnNames = [[self columnNameToIndexMap] keyEnumerator];
NSString *columnName = nil;
while ((columnName = [columnNames nextObject])) {
id objectValue = [self objectForColumnName:columnName];
[dict setObject:objectValue forKey:columnName];
}
return FMDBReturnAutoreleased([dict copy]);
}
else {
NSLog(@"Warning: There seem to be no columns in this set.");
}
return nil;
}
#pragma clang diagnostic pop
- (NSDictionary*)resultDictionary {
NSUInteger num_cols = (NSUInteger)sqlite3_data_count([_statement statement]);
if (num_cols > 0) {
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:num_cols];
int columnCount = sqlite3_column_count([_statement statement]);
int columnIdx = 0;
for (columnIdx = 0; columnIdx < columnCount; columnIdx++) {
NSString *columnName = [NSString stringWithUTF8String:sqlite3_column_name([_statement statement], columnIdx)];
id objectValue = [self objectForColumnIndex:columnIdx];
[dict setObject:objectValue forKey:columnName];
}
return dict;
}
else {
NSLog(@"Warning: There seem to be no columns in this set.");
}
return nil;
}
- (BOOL)next {
return [self nextWithError:nil];
}
- (BOOL)nextWithError:(NSError **)outErr {
int rc = sqlite3_step([_statement statement]);
if (SQLITE_BUSY == rc || SQLITE_LOCKED == rc) {
NSLog(@"%s:%d Database busy (%@)", __FUNCTION__, __LINE__, [_parentDB databasePath]);
NSLog(@"Database busy");
if (outErr) {
*outErr = [_parentDB lastError];
}
}
else if (SQLITE_DONE == rc || SQLITE_ROW == rc) {
// all is well, let's return.
}
else if (SQLITE_ERROR == rc) {
NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle]));
if (outErr) {
*outErr = [_parentDB lastError];
}
}
else if (SQLITE_MISUSE == rc) {
// uh oh.
NSLog(@"Error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle]));
if (outErr) {
if (_parentDB) {
*outErr = [_parentDB lastError];
}
else {
// If 'next' or 'nextWithError' is called after the result set is closed,
// we need to return the appropriate error.
NSDictionary* errorMessage = [NSDictionary dictionaryWithObject:@"parentDB does not exist" forKey:NSLocalizedDescriptionKey];
*outErr = [NSError errorWithDomain:@"FMDatabase" code:SQLITE_MISUSE userInfo:errorMessage];
}
}
}
else {
// wtf?
NSLog(@"Unknown error calling sqlite3_step (%d: %s) rs", rc, sqlite3_errmsg([_parentDB sqliteHandle]));
if (outErr) {
*outErr = [_parentDB lastError];
}
}
if (rc != SQLITE_ROW) {
[self close];
}
return (rc == SQLITE_ROW);
}
- (BOOL)hasAnotherRow {
return sqlite3_errcode([_parentDB sqliteHandle]) == SQLITE_ROW;
}
- (int)columnIndexForName:(NSString*)columnName {
columnName = [columnName lowercaseString];
NSNumber *n = [[self columnNameToIndexMap] objectForKey:columnName];
if (n) {
return [n intValue];
}
NSLog(@"Warning: I could not find the column named '%@'.", columnName);
return -1;
}
- (int)intForColumn:(NSString*)columnName {
return [self intForColumnIndex:[self columnIndexForName:columnName]];
}
- (int)intForColumnIndex:(int)columnIdx {
return sqlite3_column_int([_statement statement], columnIdx);
}
- (long)longForColumn:(NSString*)columnName {
return [self longForColumnIndex:[self columnIndexForName:columnName]];
}
- (long)longForColumnIndex:(int)columnIdx {
return (long)sqlite3_column_int64([_statement statement], columnIdx);
}
- (long long int)longLongIntForColumn:(NSString*)columnName {
return [self longLongIntForColumnIndex:[self columnIndexForName:columnName]];
}
- (long long int)longLongIntForColumnIndex:(int)columnIdx {
return sqlite3_column_int64([_statement statement], columnIdx);
}
- (unsigned long long int)unsignedLongLongIntForColumn:(NSString*)columnName {
return [self unsignedLongLongIntForColumnIndex:[self columnIndexForName:columnName]];
}
- (unsigned long long int)unsignedLongLongIntForColumnIndex:(int)columnIdx {
return (unsigned long long int)[self longLongIntForColumnIndex:columnIdx];
}
- (BOOL)boolForColumn:(NSString*)columnName {
return [self boolForColumnIndex:[self columnIndexForName:columnName]];
}
- (BOOL)boolForColumnIndex:(int)columnIdx {
return ([self intForColumnIndex:columnIdx] != 0);
}
- (double)doubleForColumn:(NSString*)columnName {
return [self doubleForColumnIndex:[self columnIndexForName:columnName]];
}
- (double)doubleForColumnIndex:(int)columnIdx {
return sqlite3_column_double([_statement statement], columnIdx);
}
- (NSString*)stringForColumnIndex:(int)columnIdx {
if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) {
return nil;
}
const char *c = (const char *)sqlite3_column_text([_statement statement], columnIdx);
if (!c) {
// null row.
return nil;
}
return [NSString stringWithUTF8String:c];
}
- (NSString*)stringForColumn:(NSString*)columnName {
return [self stringForColumnIndex:[self columnIndexForName:columnName]];
}
- (NSDate*)dateForColumn:(NSString*)columnName {
return [self dateForColumnIndex:[self columnIndexForName:columnName]];
}
- (NSDate*)dateForColumnIndex:(int)columnIdx {
if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) {
return nil;
}
return [_parentDB hasDateFormatter] ? [_parentDB dateFromString:[self stringForColumnIndex:columnIdx]] : [NSDate dateWithTimeIntervalSince1970:[self doubleForColumnIndex:columnIdx]];
}
- (NSData*)dataForColumn:(NSString*)columnName {
return [self dataForColumnIndex:[self columnIndexForName:columnName]];
}
- (NSData*)dataForColumnIndex:(int)columnIdx {
if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) {
return nil;
}
const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx);
int dataSize = sqlite3_column_bytes([_statement statement], columnIdx);
if (dataBuffer == NULL) {
return nil;
}
return [NSData dataWithBytes:(const void *)dataBuffer length:(NSUInteger)dataSize];
}
- (NSData*)dataNoCopyForColumn:(NSString*)columnName {
return [self dataNoCopyForColumnIndex:[self columnIndexForName:columnName]];
}
- (NSData*)dataNoCopyForColumnIndex:(int)columnIdx {
if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) {
return nil;
}
const char *dataBuffer = sqlite3_column_blob([_statement statement], columnIdx);
int dataSize = sqlite3_column_bytes([_statement statement], columnIdx);
NSData *data = [NSData dataWithBytesNoCopy:(void *)dataBuffer length:(NSUInteger)dataSize freeWhenDone:NO];
return data;
}
- (BOOL)columnIndexIsNull:(int)columnIdx {
return sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL;
}
- (BOOL)columnIsNull:(NSString*)columnName {
return [self columnIndexIsNull:[self columnIndexForName:columnName]];
}
- (const unsigned char *)UTF8StringForColumnIndex:(int)columnIdx {
if (sqlite3_column_type([_statement statement], columnIdx) == SQLITE_NULL || (columnIdx < 0)) {
return nil;
}
return sqlite3_column_text([_statement statement], columnIdx);
}
- (const unsigned char *)UTF8StringForColumnName:(NSString*)columnName {
return [self UTF8StringForColumnIndex:[self columnIndexForName:columnName]];
}
- (id)objectForColumnIndex:(int)columnIdx {
int columnType = sqlite3_column_type([_statement statement], columnIdx);
id returnValue = nil;
if (columnType == SQLITE_INTEGER) {
returnValue = [NSNumber numberWithLongLong:[self longLongIntForColumnIndex:columnIdx]];
}
else if (columnType == SQLITE_FLOAT) {
returnValue = [NSNumber numberWithDouble:[self doubleForColumnIndex:columnIdx]];
}
else if (columnType == SQLITE_BLOB) {
returnValue = [self dataForColumnIndex:columnIdx];
}
else {
//default to a string for everything else
returnValue = [self stringForColumnIndex:columnIdx];
}
if (returnValue == nil) {
returnValue = [NSNull null];
}
return returnValue;
}
- (id)objectForColumnName:(NSString*)columnName {
return [self objectForColumnIndex:[self columnIndexForName:columnName]];
}
// returns autoreleased NSString containing the name of the column in the result set
- (NSString*)columnNameForIndex:(int)columnIdx {
return [NSString stringWithUTF8String: sqlite3_column_name([_statement statement], columnIdx)];
}
- (void)setParentDB:(FMDatabase *)newDb {
_parentDB = newDb;
}
- (id)objectAtIndexedSubscript:(int)columnIdx {
return [self objectForColumnIndex:columnIdx];
}
- (id)objectForKeyedSubscript:(NSString *)columnName {
return [self objectForColumnName:columnName];
}
@end
//
// NSData+SSToolkitAdditions.h
// SSToolkit
//
// Created by Sam Soffes on 9/29/08.
// Copyright 2008-2011 Sam Soffes. All rights reserved.
//
/**
Provides extensions to `NSData` for various common tasks.
*/
@import UIKit;
@interface NSData (SSToolkitAdditions)
///--------------
/// @name Hashing
///--------------
/**
Returns a string of the MD5 sum of the receiver.
@return The string of the MD5 sum of the receiver.
*/
- (NSString *)MD5Sum;
/**
Returns a string of the SHA1 sum of the receiver.
@return The string of the SHA1 sum of the receiver.
*/
- (NSString *)SHA1Sum;
/**
Returns a string of the SHA256 sum of the receiver.
@return The string of the SHA256 sum of the receiver.
*/
- (NSString *)SHA256Sum;
///-----------------------------------
/// @name Base64 Encoding and Decoding
///-----------------------------------
/**
Returns a string representation of the receiver Base64 encoded.
@return A Base64 encoded string
*/
- (NSString *)base64EncodedString;
/**
Returns a new data contained in the Base64 encoded string.
@param base64String A Base64 encoded string
@return Data contained in `base64String`
*/
+ (NSData *)dataWithBase64String:(NSString *)base64String;
@end
\ No newline at end of file
//
// NSData+SSToolkitAdditions.m
// SSToolkit
//
// Created by Sam Soffes on 9/29/08.
// Copyright 2008-2011 Sam Soffes. All rights reserved.
//
#import "NSData+SSToolkitAdditions.h"
#include <CommonCrypto/CommonDigest.h>
static const char _base64EncodingTable[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const short _base64DecodingTable[256] = {
-2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -2, -1, -1, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, -2, -2, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2, -2, -2, -2, -2,
-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -2, -2, -2, -2, -2,
-2, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
-2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2
};
@implementation NSData (SSToolkitAdditions)
- (NSString *)MD5Sum {
unsigned char digest[CC_MD5_DIGEST_LENGTH], i;
CC_MD5(self.bytes, (CC_LONG)self.length, digest);
NSMutableString *ms = [NSMutableString string];
for (i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
[ms appendFormat: @"%02x", (int)(digest[i])];
}
return [ms copy];
}
- (NSString *)SHA1Sum {
NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
uint8_t digest[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(self.bytes, (CC_LONG)self.length, digest);
for (NSInteger i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
[output appendFormat:@"%02x", digest[i]];
}
return output;
}
- (NSString *)SHA256Sum {
NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
uint8_t digest[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(self.bytes, (CC_LONG)self.length, digest);
for (NSInteger i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
[output appendFormat:@"%02x", digest[i]];
}
return output;
}
// Adapted from http://www.cocoadev.com/index.pl?BaseSixtyFour
- (NSString *)base64EncodedString {
const uint8_t *input = self.bytes;
NSInteger length = self.length;
NSMutableData *data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t *output = (uint8_t *)data.mutableBytes;
for (NSInteger i = 0; i < length; i += 3) {
NSInteger value = 0;
for (NSInteger j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
NSInteger index = (i / 3) * 4;
output[index + 0] = _base64EncodingTable[(value >> 18) & 0x3F];
output[index + 1] = _base64EncodingTable[(value >> 12) & 0x3F];
output[index + 2] = (i + 1) < length ? _base64EncodingTable[(value >> 6) & 0x3F] : '=';
output[index + 3] = (i + 2) < length ? _base64EncodingTable[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}
// Adapted from http://www.cocoadev.com/index.pl?BaseSixtyFour
+ (NSData *)dataWithBase64String:(NSString *)base64String {
const char *string = [base64String cStringUsingEncoding:NSASCIIStringEncoding];
NSInteger inputLength = base64String.length;
if (string == NULL/* || inputLength % 4 != 0*/) {
return nil;
}
while (inputLength > 0 && string[inputLength - 1] == '=') {
inputLength--;
}
NSInteger outputLength = inputLength * 3 / 4;
NSMutableData* data = [NSMutableData dataWithLength:outputLength];
uint8_t *output = data.mutableBytes;
NSInteger inputPoint = 0;
NSInteger outputPoint = 0;
while (inputPoint < inputLength) {
char i0 = string[inputPoint++];
char i1 = string[inputPoint++];
char i2 = inputPoint < inputLength ? string[inputPoint++] : 'A'; /* 'A' will decode to \0 */
char i3 = inputPoint < inputLength ? string[inputPoint++] : 'A';
output[outputPoint++] = (_base64DecodingTable[i0] << 2) | (_base64DecodingTable[i1] >> 4);
if (outputPoint < outputLength) {
output[outputPoint++] = ((_base64DecodingTable[i1] & 0xf) << 4) | (_base64DecodingTable[i2] >> 2);
}
if (outputPoint < outputLength) {
output[outputPoint++] = ((_base64DecodingTable[i2] & 0x3) << 6) | _base64DecodingTable[i3];
}
}
return data;
}
@end
\ No newline at end of file
//
// NSString+SSToolkitAdditions.h
// SSToolkit
//
// Created by Sam Soffes on 6/22/09.
// Copyright 2009-2011 Sam Soffes. All rights reserved.
//
/**
Provides extensions to `NSString` for various common tasks.
*/
@import UIKit;
@interface NSString (SSToolkitAdditions)
///------------------------
/// @name Checking Contents
///------------------------
/**
Returns a Boolean if the receiver contains the given `string`.
@param string A string to test the the receiver for
@return A Boolean if the receiver contains the given `string`
*/
- (BOOL)containsString:(NSString *)string;
///--------------
/// @name Hashing
///--------------
/**
Returns a string of the MD5 sum of the receiver.
@return The string of the MD5 sum of the receiver.
*/
- (NSString *)MD5Sum;
/**
Returns a string of the SHA1 sum of the receiver.
@return The string of the SHA1 sum of the receiver.
*/
- (NSString *)SHA1Sum;
/**
Returns a string of the SHA256 sum of the receiver.
@return The string of the SHA256 sum of the receiver.
*/
- (NSString *)SHA256Sum;
///-------------------------
/// @name Comparing Versions
///-------------------------
/**
Returns a comparison result for the receiver and a given `version`.
Examples:
<pre><code>[@"10.4" compareToVersionString:@"10.3"]; // NSOrderedDescending
[@"10.5" compareToVersionString:@"10.5.0"]; // NSOrderedSame
[@"10.4 Build 8L127" compareToVersionString:@"10.4 Build 8P135"]; // NSOrderedAscending</code></pre>
@param version A version string to compare to the receiver
@return A comparison result for the receiver and a given `version`
*/
- (NSComparisonResult)compareToVersionString:(NSString *)version;
///-----------------------------------
/// @name HTML Escaping and Unescaping
///-----------------------------------
/**
Returns a new string with any HTML escaped.
@return A new string with any HTML escaped.
@see unescapeHTML
*/
- (NSString *)escapeHTML;
/**
Returns a new string with any HTML unescaped.
@return A new string with any HTML unescaped.
@see escapeHTML
*/
- (NSString *)unescapeHTML;
///----------------------------------
/// @name URL Escaping and Unescaping
///----------------------------------
/**
Returns a new string escaped for a URL query parameter.
The following characters are escaped: `\n\r:/=,!$&'()*+;[]@#?%`. Spaces are escaped to the `+` character. (`+` is
escaped to `%2B`).
@return A new string escaped for a URL query parameter.
@see stringByUnescapingFromURLQuery
*/
- (NSString *)stringByEscapingForURLQuery;
/**
Returns a new string unescaped from a URL query parameter.
`+` characters are unescaped to spaces.
@return A new string escaped for a URL query parameter.
@see stringByEscapingForURLQuery
*/
- (NSString *)stringByUnescapingFromURLQuery;
///-----------------------------------------------
/// @name URL Encoding and Unencoding (Deprecated)
///-----------------------------------------------
/**
Returns a new string encoded for a URL. (Deprecated)
The following characters are encoded: `:/=,!$&'()*+;[]@#?%`.
@return A new string escaped for a URL.
*/
- (NSString *)URLEncodedString;
/**
Returns a new string encoded for a URL parameter. (Deprecated)
The following characters are encoded: `:/=,!$&'()*+;[]@#?`.
@return A new string escaped for a URL parameter.
*/
- (NSString *)URLEncodedParameterString;
/**
Returns a new string decoded from a URL.
@return A new string decoded from a URL.
*/
- (NSString *)URLDecodedString;
///----------------------
/// @name Base64 Encoding
///----------------------
/**
Returns a string representation of the receiver Base64 encoded.
@return A Base64 encoded string
*/
- (NSString *)base64EncodedString;
/**
Returns a new string contained in the Base64 encoded string.
This uses `NSData`'s `dataWithBase64String:` method to do the conversion then initializes a string with the resulting
`NSData` object using `NSUTF8StringEncoding`.
@param base64String A Base64 encoded string
@return String contained in `base64String`
*/
+ (NSString *)stringWithBase64String:(NSString *)base64String;
///------------------------
/// @name Generating a UUID
///------------------------
/**
Returns a new string containing a Universally Unique Identifier.
*/
+ (NSString *)stringWithUUID;
///---------------
/// @name Trimming
///---------------
/**
Returns a new string by trimming leading and trailing characters in a given `NSCharacterSet`.
@param characterSet Character set to trim characters
@return A new string by trimming leading and trailing characters in `characterSet`
*/
- (NSString *)stringByTrimmingLeadingAndTrailingCharactersInSet:(NSCharacterSet *)characterSet;
/**
Returns a new string by trimming leading and trailing whitespace and newline characters.
@return A new string by trimming leading and trailing whitespace and newline characters
*/
- (NSString *)stringByTrimmingLeadingAndTrailingWhitespaceAndNewlineCharacters;
/**
Returns a new string by trimming leading characters in a given `NSCharacterSet`.
@param characterSet Character set to trim characters
@return A new string by trimming leading characters in `characterSet`
*/
- (NSString *)stringByTrimmingLeadingCharactersInSet:(NSCharacterSet *)characterSet;
/**
Returns a new string by trimming leading whitespace and newline characters.
@return A new string by trimming leading whitespace and newline characters
*/
- (NSString *)stringByTrimmingLeadingWhitespaceAndNewlineCharacters;
/**
Returns a new string by trimming trailing characters in a given `NSCharacterSet`.
@param characterSet Character set to trim characters
@return A new string by trimming trailing characters in `characterSet`
*/
- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet;
/**
Returns a new string by trimming trailing whitespace and newline characters.
@return A new string by trimming trailing whitespace and newline characters
*/
- (NSString *)stringByTrimmingTrailingWhitespaceAndNewlineCharacters;
@end
\ No newline at end of file
//
// NSString+SSToolkitAdditions.m
// SSToolkit
//
// Created by Sam Soffes on 6/22/09.
// Copyright 2009-2011 Sam Soffes. All rights reserved.
//
#import "NSString+SSToolkitAdditions.h"
#import "NSData+SSToolkitAdditions.h"
#import <CommonCrypto/CommonDigest.h>
@implementation NSString (SSToolkitAdditions)
- (BOOL)containsString:(NSString *)string {
return !NSEqualRanges([self rangeOfString:string], NSMakeRange(NSNotFound, 0));
}
- (NSString *)MD5Sum {
const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:self.length];
return [data MD5Sum];
}
- (NSString *)SHA1Sum {
const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:self.length];
return [data SHA1Sum];
}
- (NSString *)SHA256Sum {
const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:self.length];
return [data SHA256Sum];
}
// Adapted from http://snipplr.com/view/2771/compare-two-version-strings
- (NSComparisonResult)compareToVersionString:(NSString *)version {
// Break version into fields (separated by '.')
NSMutableArray *leftFields = [[NSMutableArray alloc] initWithArray:[self componentsSeparatedByString:@"."]];
NSMutableArray *rightFields = [[NSMutableArray alloc] initWithArray:[version componentsSeparatedByString:@"."]];
// Implict ".0" in case version doesn't have the same number of '.'
if ([leftFields count] < [rightFields count]) {
while ([leftFields count] != [rightFields count]) {
[leftFields addObject:@"0"];
}
} else if ([leftFields count] > [rightFields count]) {
while ([leftFields count] != [rightFields count]) {
[rightFields addObject:@"0"];
}
}
// Do a numeric comparison on each field
for (NSUInteger i = 0; i < [leftFields count]; i++) {
NSComparisonResult result = [[leftFields objectAtIndex:i] compare:[rightFields objectAtIndex:i] options:NSNumericSearch];
if (result != NSOrderedSame) {
return result;
}
}
return NSOrderedSame;
}
#pragma mark - HTML Methods
- (NSString *)escapeHTML {
NSMutableString *s = [NSMutableString string];
NSUInteger start = 0;
NSUInteger len = [self length];
NSCharacterSet *chs = [NSCharacterSet characterSetWithCharactersInString:@"<>&\""];
while (start < len) {
NSRange r = [self rangeOfCharacterFromSet:chs options:0 range:NSMakeRange(start, len-start)];
if (r.location == NSNotFound) {
[s appendString:[self substringFromIndex:start]];
break;
}
if (start < r.location) {
[s appendString:[self substringWithRange:NSMakeRange(start, r.location-start)]];
}
switch ([self characterAtIndex:r.location]) {
case '<':
[s appendString:@"&lt;"];
break;
case '>':
[s appendString:@"&gt;"];
break;
case '"':
[s appendString:@"&quot;"];
break;
// case '…':
// [s appendString:@"&hellip;"];
// break;
case '&':
[s appendString:@"&amp;"];
break;
}
start = r.location + 1;
}
return s;
}
- (NSString *)unescapeHTML {
NSMutableString *s = [NSMutableString string];
NSMutableString *target = [self mutableCopy];
NSCharacterSet *chs = [NSCharacterSet characterSetWithCharactersInString:@"&"];
while ([target length] > 0) {
NSRange r = [target rangeOfCharacterFromSet:chs];
if (r.location == NSNotFound) {
[s appendString:target];
break;
}
if (r.location > 0) {
[s appendString:[target substringToIndex:r.location]];
[target deleteCharactersInRange:NSMakeRange(0, r.location)];
}
if ([target hasPrefix:@"&lt;"]) {
[s appendString:@"<"];
[target deleteCharactersInRange:NSMakeRange(0, 4)];
} else if ([target hasPrefix:@"&gt;"]) {
[s appendString:@">"];
[target deleteCharactersInRange:NSMakeRange(0, 4)];
} else if ([target hasPrefix:@"&quot;"]) {
[s appendString:@"\""];
[target deleteCharactersInRange:NSMakeRange(0, 6)];
} else if ([target hasPrefix:@"&#39;"]) {
[s appendString:@"'"];
[target deleteCharactersInRange:NSMakeRange(0, 5)];
} else if ([target hasPrefix:@"&amp;"]) {
[s appendString:@"&"];
[target deleteCharactersInRange:NSMakeRange(0, 5)];
} else if ([target hasPrefix:@"&hellip;"]) {
[s appendString:@"…"];
[target deleteCharactersInRange:NSMakeRange(0, 8)];
} else {
[s appendString:@"&"];
[target deleteCharactersInRange:NSMakeRange(0, 1)];
}
}
return s;
}
#pragma mark - URL Escaping and Unescaping
- (NSString *)stringByEscapingForURLQuery {
NSString *result = self;
static CFStringRef leaveAlone = CFSTR(" ");
static CFStringRef toEscape = CFSTR("\n\r:/=,!$&'()*+;[]@#?%");
CFStringRef escapedStr = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)self, leaveAlone,
toEscape, kCFStringEncodingUTF8);
if (escapedStr) {
NSMutableString *mutable = [NSMutableString stringWithString:(__bridge NSString *)escapedStr];
CFRelease(escapedStr);
[mutable replaceOccurrencesOfString:@" " withString:@"+" options:0 range:NSMakeRange(0, [mutable length])];
result = mutable;
}
return result;
}
- (NSString *)stringByUnescapingFromURLQuery {
NSString *deplussed = [self stringByReplacingOccurrencesOfString:@"+" withString:@" "];
return [deplussed stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
#pragma mark - URL Encoding and Unencoding (Deprecated)
- (NSString *)URLEncodedString {
static CFStringRef toEscape = CFSTR(":/=,!$&'()*+;[]@#?%");
return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(__bridge CFStringRef)self,
NULL,
toEscape,
kCFStringEncodingUTF8);
}
- (NSString *)URLEncodedParameterString {
static CFStringRef toEscape = CFSTR(":/=,!$&'()*+;[]@#?%");
return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(__bridge CFStringRef)self,
NULL,
toEscape,
kCFStringEncodingUTF8);
}
- (NSString *)URLDecodedString {
return (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
(__bridge CFStringRef)self,
CFSTR(""),
kCFStringEncodingUTF8);
}
#pragma mark - Base64 Encoding
- (NSString *)base64EncodedString {
if ([self length] == 0) {
return nil;
}
return [[self dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
}
+ (NSString *)stringWithBase64String:(NSString *)base64String {
return [[NSString alloc] initWithData:[NSData dataWithBase64String:base64String] encoding:NSUTF8StringEncoding];
}
#pragma mark - Generating a UUID
+ (NSString *)stringWithUUID {
CFUUIDRef uuid = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, uuid);
CFRelease(uuid);
return (__bridge_transfer NSString *)string;
}
#pragma mark - Trimming
- (NSString *)stringByTrimmingLeadingAndTrailingCharactersInSet:(NSCharacterSet *)characterSet {
return [[self stringByTrimmingLeadingCharactersInSet:characterSet]
stringByTrimmingTrailingCharactersInSet:characterSet];
}
- (NSString *)stringByTrimmingLeadingAndTrailingWhitespaceAndNewlineCharacters {
return [[self stringByTrimmingLeadingWhitespaceAndNewlineCharacters]
stringByTrimmingTrailingWhitespaceAndNewlineCharacters];
}
- (NSString *)stringByTrimmingLeadingCharactersInSet:(NSCharacterSet *)characterSet {
NSRange rangeOfFirstWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]];
if (rangeOfFirstWantedCharacter.location == NSNotFound) {
return @"";
}
return [self substringFromIndex:rangeOfFirstWantedCharacter.location];
}
- (NSString *)stringByTrimmingLeadingWhitespaceAndNewlineCharacters {
return [self stringByTrimmingLeadingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
NSRange rangeOfLastWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]
options:NSBackwardsSearch];
if (rangeOfLastWantedCharacter.location == NSNotFound) {
return @"";
}
return [self substringToIndex:rangeOfLastWantedCharacter.location + 1]; // Non-inclusive
}
- (NSString *)stringByTrimmingTrailingWhitespaceAndNewlineCharacters {
return [self stringByTrimmingTrailingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <UIKit/UIKit.h>
@interface UIViewController (WLAdditions)
- (UIViewController *)topModalViewController;
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "UIViewController+WLAdditions.h"
@implementation UIViewController (WLAdditions)
#pragma mark - Public Methods
///////////////////////////////////////////////////////////////////////////////
- (UIViewController *)topModalViewController
{
return [self topModalViewControllerOfController:self];
}
#pragma mark - Private Methods
///////////////////////////////////////////////////////////////////////////////
- (UIViewController *)topModalViewControllerOfController:(UIViewController *)controller
{
UIViewController *presentedVC = [controller presentedViewController];
if (presentedVC != nil)
return [self topModalViewControllerOfController:presentedVC];
return controller;
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <UIKit/UIKit.h>
#define IFPGA_NAMESTRING @"iFPGA"
#define IPHONE_1_NAMESTRING @"iPhone 1"
#define IPHONE_3G_NAMESTRING @"iPhone 3G"
#define IPHONE_3GS_NAMESTRING @"iPhone 3GS"
#define IPHONE_4_NAMESTRING @"iPhone 4"
#define IPHONE_4S_NAMESTRING @"iPhone 4S"
#define IPHONE_5_NAMESTRING @"iPhone 5"
#define IPHONE_5C_NAMESTRING @"iPhone 5C"
#define IPHONE_5S_NAMESTRING @"iPhone 5S"
#define IPHONE_UNKNOWN_NAMESTRING @"Unknown iPhone"
#define IPOD_1_NAMESTRING @"iPod touch 1"
#define IPOD_2_NAMESTRING @"iPod touch 2"
#define IPOD_3_NAMESTRING @"iPod touch 3"
#define IPOD_4_NAMESTRING @"iPod touch 4"
#define IPOD_5_NAMESTRING @"iPod touch 5"
#define IPOD_UNKNOWN_NAMESTRING @"Unknown iPod"
#define IPAD_1_NAMESTRING @"iPad 1"
#define IPAD_2_NAMESTRING @"iPad 2"
#define THE_NEW_IPAD_NAMESTRING @"The new iPad"
#define IPAD_4G_NAMESTRING @"iPad 4G"
#define IPAD_AIR_NAMESTRING @"iPad Air (WiFi)"
#define IPAD_AIR_LTE_NAMESTRING @"iPad Air (LTE)"
#define IPAD_MINI_NAMESTRING @"iPad mini"
#define IPAD_UNKNOWN_NAMESTRING @"Unknown iPad"
#define APPLETV_2G_NAMESTRING @"Apple TV 2"
#define APPLETV_3G_NAMESTRING @"Apple TV 3"
#define APPLETV_4G_NAMESTRING @"Apple TV 4"
#define APPLETV_UNKNOWN_NAMESTRING @"Unknown Apple TV"
#define IOS_FAMILY_UNKNOWN_DEVICE @"Unknown iOS device"
#define IPHONE_SIMULATOR_NAMESTRING @"iPhone Simulator"
#define IPHONE_SIMULATOR_IPHONE_NAMESTRING @"iPhone Simulator"
#define IPHONE_SIMULATOR_IPAD_NAMESTRING @"iPad Simulator"
#define SIMULATOR_APPLETV_NAMESTRING @"Apple TV Simulator"
typedef enum {
UIDeviceUnknown,
UIDeviceiPhoneSimulator,
UIDeviceiPhoneSimulatoriPhone, // both regular and iPhone 4 devices
UIDeviceiPhoneSimulatoriPad,
UIDeviceSimulatorAppleTV,
UIDeviceiPhone1,
UIDeviceiPhone3G,
UIDeviceiPhone3GS,
UIDeviceiPhone4,
UIDeviceiPhone4GSM,
UIDeviceiPhone4GSMRevA,
UIDeviceiPhone4CDMA,
UIDeviceiPhone4S,
UIDeviceiPhone5,
UIDeviceiPhone5GSM,
UIDeviceiPhone5CDMA,
UIDeviceiPhone5CGSM,
UIDeviceiPhone5CGSMCDMA,
UIDeviceiPhone5SGSM,
UIDeviceiPhone5SGSMCDMA,
UIDeviceiPod1,
UIDeviceiPod2,
UIDeviceiPod3,
UIDeviceiPod4,
UIDeviceiPod5,
UIDeviceiPad1,
UIDeviceiPad2,
UIDeviceTheNewiPad,
UIDeviceiPad4G,
UIDeviceiPadAir,
UIDeviceiPadAirLTE,
UIDeviceiPadMini,
UIDeviceAppleTV2,
UIDeviceAppleTV3,
UIDeviceAppleTV4,
UIDeviceUnknowniPhone,
UIDeviceUnknowniPod,
UIDeviceUnknowniPad,
UIDeviceUnknownAppleTV,
UIDeviceIFPGA,
} UIDevicePlatform;
typedef enum {
UIDeviceFamilyiPhone,
UIDeviceFamilyiPod,
UIDeviceFamilyiPad,
UIDeviceFamilyAppleTV,
UIDeviceFamilyUnknown,
} UIDeviceFamily;
@interface UIDevice (Hardware)
- (NSString *)platform;
- (NSString *)platformString;
- (NSString *)deviceFamilyString;
@end
@interface WLKeychain : NSObject
+ (BOOL)setString:(NSString *)string forKey:(NSString *)key;
+ (NSString *)getStringForKey:(NSString *)key;
+ (void)deleteStringForKey:(NSString *)key;
@end
\ No newline at end of file
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "WLUtils.h"
#import "WLGlobals.h"
#import <Security/Security.h>
#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
@implementation UIDevice (Hardware)
/*
Platforms
iFPGA -> ??
iPhone1,1 -> iPhone 1, M68
iPhone1,2 -> iPhone 3G, N82
iPhone2,1 -> iPhone 3GS, N88
iPhone3,1 -> iPhone 4/GSM, N89
iPhone3,2 -> iPhone 4/GSM Rev A, N90
iPhone3,3 -> iPhone 4/CDMA, N92
iPhone4,1 -> iPhone 4S/GSM+CDMA, N94
iPhone5,1 -> iPhone 5/GSM, N41
iPhone5,2 -> iPhone 5/GSM+CDMA, N42
iPhone5,3 -> iPhone 5C/GSM, N48
iPhone5,4 -> iPhone 5C/GSM+CDMA, N49
iPhone6,1 -> iPhone 5S/GSM, N51
iPhone6,2 -> iPhone 5S/GSM+CDMA, N53
iPod1,1 -> iPod touch 1, N45
iPod2,1 -> iPod touch 2, N72
iPod2,2 -> iPod touch 3, Prototype
iPod3,1 -> iPod touch 3, N18
iPod4,1 -> iPod touch 4, N81
// Thanks NSForge
ipad0,1 -> iPad, Prototype
iPad1,1 -> iPad 1, WiFi and 3G, K48
iPad2,1 -> iPad 2, WiFi, K93
iPad2,2 -> iPad 2, GSM 3G, K94
iPad2,3 -> iPad 2, CDMA 3G, K95
iPad2,4 -> iPad 2, WiFi R2, K93A
iPad3,1 -> The new iPad, WiFi
iPad3,2 -> The new iPad, CDMA
iPad3,3 -> The new iPad
iPad4,1 -> (iPad 4G, WiFi)
iPad4,2 -> (iPad 4G, GSM)
iPad4,3 -> (iPad 4G, CDMA)
iProd2,1 -> AppleTV 2, Prototype
AppleTV2,1 -> AppleTV 2, K66
AppleTV3,1 -> AppleTV 3, ??
i386, x86_64 -> iPhone Simulator
*/
#pragma mark sysctlbyname utils
////////////////////////////////////////////////////////////////////////////////
- (NSString *) getSysInfoByName:(char *)typeSpecifier
{
size_t size;
sysctlbyname(typeSpecifier, NULL, &size, NULL, 0);
char *answer = malloc(size);
sysctlbyname(typeSpecifier, answer, &size, NULL, 0);
NSString *results = [NSString stringWithCString:answer encoding: NSUTF8StringEncoding];
free(answer);
return results;
}
////////////////////////////////////////////////////////////////////////////////
- (NSString *) platform
{
return [self getSysInfoByName:"hw.machine"];
}
#pragma mark sysctl utils
////////////////////////////////////////////////////////////////////////////////
- (NSUInteger) getSysInfo: (uint) typeSpecifier
{
size_t size = sizeof(int);
int results;
int mib[2] = {CTL_HW, typeSpecifier};
sysctl(mib, 2, &results, &size, NULL, 0);
return (NSUInteger) results;
}
#pragma mark platform type and name utils
////////////////////////////////////////////////////////////////////////////////
- (NSUInteger) platformType
{
return [UIDevice platformTypeForString:[self platform]];
}
////////////////////////////////////////////////////////////////////////////////
- (NSString *) platformString
{
return [UIDevice platformStringForType:[self platformType]];
}
////////////////////////////////////////////////////////////////////////////////
+ (NSUInteger) platformTypeForString:(NSString *)platform
{
// The ever mysterious iFPGA
if ([platform isEqualToString:@"iFPGA"]) return UIDeviceIFPGA;
// iPhone
if ([platform isEqualToString:@"iPhone1,1"]) return UIDeviceiPhone1;
if ([platform isEqualToString:@"iPhone1,2"]) return UIDeviceiPhone3G;
if ([platform hasPrefix:@"iPhone2"]) return UIDeviceiPhone3GS;
if ([platform isEqualToString:@"iPhone3,1"]) return UIDeviceiPhone4GSM;
if ([platform isEqualToString:@"iPhone3,2"]) return UIDeviceiPhone4GSMRevA;
if ([platform isEqualToString:@"iPhone3,3"]) return UIDeviceiPhone4CDMA;
if ([platform hasPrefix:@"iPhone4"]) return UIDeviceiPhone4S;
if ([platform isEqualToString:@"iPhone5,1"]) return UIDeviceiPhone5GSM;
if ([platform isEqualToString:@"iPhone5,2"]) return UIDeviceiPhone5CDMA;
if ([platform isEqualToString:@"iPhone5,3"]) return UIDeviceiPhone5CGSM;
if ([platform isEqualToString:@"iPhone5,4"]) return UIDeviceiPhone5CGSMCDMA;
if ([platform isEqualToString:@"iPhone6,1"]) return UIDeviceiPhone5SGSM;
if ([platform isEqualToString:@"iPhone6,2"]) return UIDeviceiPhone5SGSMCDMA;
// iPod
if ([platform hasPrefix:@"iPod1"]) return UIDeviceiPod1;
if ([platform isEqualToString:@"iPod2,2"]) return UIDeviceiPod3;
if ([platform hasPrefix:@"iPod2"]) return UIDeviceiPod2;
if ([platform hasPrefix:@"iPod3"]) return UIDeviceiPod3;
if ([platform hasPrefix:@"iPod4"]) return UIDeviceiPod4;
if ([platform hasPrefix:@"iPod5"]) return UIDeviceiPod5;
// iPad
if ([platform hasPrefix:@"iPad1"]) return UIDeviceiPad1;
if ([platform hasPrefix:@"iPad2"])
{
NSInteger submodel = [ UIDevice getSubmodel:platform ];
if ( submodel <= 4 )
{
return UIDeviceiPad2;
} else
{
return UIDeviceiPadMini;
}
}
if ([platform hasPrefix:@"iPad3"])
{
NSInteger submodel = [ UIDevice getSubmodel:platform ];
if ( submodel <= 3 )
{
return UIDeviceTheNewiPad;
} else
{
return UIDeviceiPad4G;
}
}
if ([platform isEqualToString:@"iPad4,1"]) return UIDeviceiPadAir;
if ([platform isEqualToString:@"iPad4,2"]) return UIDeviceiPadAirLTE;
// Apple TV
if ([platform hasPrefix:@"AppleTV2"]) return UIDeviceAppleTV2;
if ([platform hasPrefix:@"AppleTV3"]) return UIDeviceAppleTV3;
if ([platform hasPrefix:@"iPhone"]) return UIDeviceUnknowniPhone;
if ([platform hasPrefix:@"iPod"]) return UIDeviceUnknowniPod;
if ([platform hasPrefix:@"iPad"]) return UIDeviceUnknowniPad;
if ([platform hasPrefix:@"AppleTV"]) return UIDeviceUnknownAppleTV;
// Simulator thanks Jordan Breeding
if ([platform hasSuffix:@"86"] || [platform isEqual:@"x86_64"])
{
BOOL smallerScreen = [[UIScreen mainScreen] bounds].size.width < 768;
return smallerScreen ? UIDeviceiPhoneSimulatoriPhone : UIDeviceiPhoneSimulatoriPad;
}
return UIDeviceUnknown;
}
////////////////////////////////////////////////////////////////////////////////
+( NSInteger )getSubmodel:( NSString* )platform
{
NSInteger submodel = -1;
NSArray* components = [ platform componentsSeparatedByString:@"," ];
if ( [ components count ] >= 2 )
{
submodel = [ [ components objectAtIndex:1 ] intValue ];
}
return submodel;
}
////////////////////////////////////////////////////////////////////////////////
+ (NSString *) platformStringForType:(NSUInteger)platformType
{
switch (platformType)
{
case UIDeviceiPhone1: return IPHONE_1_NAMESTRING;
case UIDeviceiPhone3G: return IPHONE_3G_NAMESTRING;
case UIDeviceiPhone3GS: return IPHONE_3GS_NAMESTRING;
case UIDeviceiPhone4GSM: return IPHONE_4_NAMESTRING;
case UIDeviceiPhone4GSMRevA: return IPHONE_4_NAMESTRING;
case UIDeviceiPhone4CDMA: return IPHONE_4_NAMESTRING;
case UIDeviceiPhone4S: return IPHONE_4S_NAMESTRING;
case UIDeviceiPhone5GSM: return IPHONE_5_NAMESTRING;
case UIDeviceiPhone5CDMA: return IPHONE_5_NAMESTRING;
case UIDeviceiPhone5CGSM: return IPHONE_5C_NAMESTRING;
case UIDeviceiPhone5CGSMCDMA: return IPHONE_5C_NAMESTRING;
case UIDeviceiPhone5SGSM: return IPHONE_5S_NAMESTRING;
case UIDeviceiPhone5SGSMCDMA: return IPHONE_5S_NAMESTRING;
case UIDeviceUnknowniPhone: return IPHONE_UNKNOWN_NAMESTRING;
case UIDeviceiPod1: return IPOD_1_NAMESTRING;
case UIDeviceiPod2: return IPOD_2_NAMESTRING;
case UIDeviceiPod3: return IPOD_3_NAMESTRING;
case UIDeviceiPod4: return IPOD_4_NAMESTRING;
case UIDeviceiPod5: return IPOD_5_NAMESTRING;
case UIDeviceUnknowniPod: return IPOD_UNKNOWN_NAMESTRING;
case UIDeviceiPad1 : return IPAD_1_NAMESTRING;
case UIDeviceiPad2 : return IPAD_2_NAMESTRING;
case UIDeviceTheNewiPad : return THE_NEW_IPAD_NAMESTRING;
case UIDeviceiPad4G : return IPAD_4G_NAMESTRING;
case UIDeviceiPadAir : return IPAD_AIR_NAMESTRING;
case UIDeviceiPadAirLTE : return IPAD_AIR_LTE_NAMESTRING;
case UIDeviceiPadMini : return IPAD_MINI_NAMESTRING;
case UIDeviceUnknowniPad : return IPAD_UNKNOWN_NAMESTRING;
case UIDeviceAppleTV2 : return APPLETV_2G_NAMESTRING;
case UIDeviceAppleTV3 : return APPLETV_3G_NAMESTRING;
case UIDeviceAppleTV4 : return APPLETV_4G_NAMESTRING;
case UIDeviceUnknownAppleTV: return APPLETV_UNKNOWN_NAMESTRING;
case UIDeviceiPhoneSimulator: return IPHONE_SIMULATOR_NAMESTRING;
case UIDeviceiPhoneSimulatoriPhone: return IPHONE_SIMULATOR_IPHONE_NAMESTRING;
case UIDeviceiPhoneSimulatoriPad: return IPHONE_SIMULATOR_IPAD_NAMESTRING;
case UIDeviceSimulatorAppleTV: return SIMULATOR_APPLETV_NAMESTRING;
case UIDeviceIFPGA: return IFPGA_NAMESTRING;
default: return IOS_FAMILY_UNKNOWN_DEVICE;
}
}
////////////////////////////////////////////////////////////////////////////////
+ (NSString *) platformStringForPlatform:(NSString *)platform
{
NSUInteger platformType = [UIDevice platformTypeForString:platform];
return [UIDevice platformStringForType:platformType];
}
////////////////////////////////////////////////////////////////////////////////
- (UIDeviceFamily) deviceFamily
{
NSString *platform = [self platform];
if ([platform hasPrefix:@"iPhone"]) return UIDeviceFamilyiPhone;
if ([platform hasPrefix:@"iPod"]) return UIDeviceFamilyiPod;
if ([platform hasPrefix:@"iPad"]) return UIDeviceFamilyiPad;
if ([platform hasPrefix:@"AppleTV"]) return UIDeviceFamilyAppleTV;
return UIDeviceFamilyUnknown;
}
////////////////////////////////////////////////////////////////////////////////
- (NSString *)deviceFamilyString
{
NSString *platform = [self platform];
if ([platform hasPrefix:@"iPhone"])
return @"iPhone";
if ([platform hasPrefix:@"iPod"])
return @"iPod";
if ([platform hasPrefix:@"iPad"])
return @"iPad";
if ([platform hasPrefix:@"AppleTV"])
return @"AppleTV";
return @"Unknown";
}
@end
@implementation WLKeychain
////////////////////////////////////////////////////////////////////////////////
+ (NSString *)appName
{
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
// Attempt to find a name for this application
NSString *appName = [bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
if (appName != nil)
appName = [bundle objectForInfoDictionaryKey:@"CFBundleName"];
return appName;
}
////////////////////////////////////////////////////////////////////////////////
+ (NSString *)bundleIdentifier
{
return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
}
////////////////////////////////////////////////////////////////////////////////
+ (BOOL)setString:(NSString *)string forKey:(NSString *)key
{
if (string == nil || key == nil)
return NO;
key = [NSString stringWithFormat:@"%@.%@", [WLKeychain bundleIdentifier], key];
// First check if it already exists, by creating a search dictionary and requesting that
// nothing be returned, and performing the search anyway.
NSMutableDictionary *existsQueryDictionary = [NSMutableDictionary dictionary];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
[existsQueryDictionary setObject:(__bridge id)(kSecClassGenericPassword) forKey:(__bridge id)(kSecClass)];
// Add the keys to the search dict
[existsQueryDictionary setObject:key forKey:(__bridge id)(kSecAttrAccount)];
[existsQueryDictionary setObject:@"service" forKey:(__bridge id)(kSecAttrService)];
[existsQueryDictionary setObject:(__bridge id)(kSecAttrAccessibleWhenUnlocked) forKey:(__bridge id)(kSecAttrAccessible)];
OSStatus res = SecItemCopyMatching((__bridge CFDictionaryRef)(existsQueryDictionary), NULL);
if (res == errSecItemNotFound) {
if (string != nil) {
NSMutableDictionary *addDict = existsQueryDictionary;
[addDict setObject:data forKey:(__bridge id)(kSecValueData)];
res = SecItemAdd((__bridge CFDictionaryRef)(addDict), NULL);
NSAssert1(res == errSecSuccess, @"Received %d from SecItemAdd!", (int)res);
}
}
else if (res == errSecSuccess) {
// Modify an existing one
// Actually pull it now of the keychain at this point.
NSDictionary *attributeDict = [NSDictionary dictionaryWithObject:data forKey:(__bridge id)(kSecValueData)];
res = SecItemUpdate((__bridge CFDictionaryRef)(existsQueryDictionary), (__bridge CFDictionaryRef)(attributeDict));
NSAssert1(res == errSecSuccess, @"SecItemUpdated returned %d!", (int)res);
}
else
NSAssert1(NO, @"Received %d from SecItemCopyMatching!", (int)res);
return YES;
}
////////////////////////////////////////////////////////////////////////////////
+ (NSString*)getStringForKey:(NSString *)key
{
key = [NSString stringWithFormat:@"%@.%@", [WLKeychain bundleIdentifier], key];
NSMutableDictionary *existsQueryDictionary = [NSMutableDictionary dictionary];
[existsQueryDictionary setObject:(id)CFBridgingRelease(kSecClassGenericPassword) forKey:(id)CFBridgingRelease(kSecClass)];
// Add the keys to the search dict
[existsQueryDictionary setObject:@"service" forKey:(id)CFBridgingRelease(kSecAttrService)];
[existsQueryDictionary setObject:key forKey:(id)CFBridgingRelease(kSecAttrAccount)];
[existsQueryDictionary setObject:(id)CFBridgingRelease(kSecAttrAccessibleWhenUnlocked) forKey:(id)CFBridgingRelease(kSecAttrAccessible)];
// We want the data back!
NSData *data = nil;
[existsQueryDictionary setObject:(id)kCFBooleanTrue forKey:(__bridge id)(kSecReturnData)];
OSStatus res = SecItemCopyMatching((__bridge CFDictionaryRef)(existsQueryDictionary), (CFTypeRef *)(void *)&data);
if (res == errSecSuccess) {
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return string;
}
else
NSAssert1(res == errSecItemNotFound, @"SecItemCopyMatching returned %d!", (int)res);
return nil;
}
////////////////////////////////////////////////////////////////////////////////
+ (void)deleteStringForKey:(NSString *)key
{
key = [NSString stringWithFormat:@"%@.%@", [WLKeychain bundleIdentifier], key];
NSMutableDictionary *existsQueryDictionary = [NSMutableDictionary dictionary];
[existsQueryDictionary setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
// Add the keys to the search dict
[existsQueryDictionary setObject:@"service" forKey:(__bridge id)kSecAttrService];
[existsQueryDictionary setObject:key forKey:(__bridge id)kSecAttrAccount];
[existsQueryDictionary setObject:(__bridge id)kSecAttrAccessibleWhenUnlocked forKey:(__bridge id)kSecAttrAccessible];
SecItemDelete((__bridge CFDictionaryRef)existsQueryDictionary);
}
@end
\ No newline at end of file
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLAPSItem.h
The WLAPSItem object is used to model the parameters of the received Remote
Notification (Push) on how to notify user, in a structured way.
@copyright Warply Inc.
*/
#import <Foundation/Foundation.h>
/*!
@class WLAPSItem
@discussion This object contains the parameters for the received Remote Notification
(Push), on how to notify the user, such as badge number and both alert text and sound.
*/
@interface WLAPSItem : NSObject
{
@private
NSUInteger _badge;
NSString *_alert;
NSString *_sound;
}
/*!
@property badge
@abstract The number that will be shown as notification badge.
*/
@property (nonatomic) NSUInteger badge;
/*!
@property alert
@abstract A string object of the alert text
*/
@property (nonatomic, copy) NSString *alert;
/*!
@property sound
@abstract A string object of the file for the alert sound.
*/
@property (nonatomic, copy) NSString *sound;
/*!
@methodgroup Initializing a WLAPSItem Object
*/
/*!
@abstract Initialise a WLAPSItem object.
@discussion Initializes and returns a newly allocated WLAPSItem object with the specified
attributes.
@param attributes A dictionary object which contains remote notification attributes.
@return Returns WLAPSItem object.
*/
- (id)initWithAttributes:(NSDictionary *)attributes;
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "WLAPSItem.h"
#import "WLGlobals.h"
@implementation WLAPSItem
@synthesize badge = _badge;
@synthesize alert = _alert;
@synthesize sound = _sound;
#pragma mark - Initialization
///////////////////////////////////////////////////////////////////////////////
- (id)initWithAttributes:(NSDictionary *)attributes
{
self = [super init];
if (self) {
NSObject *idx = nil;
for (NSString *key in [attributes allKeys]) {
idx = [attributes objectForKey:key];
@try {
if ([idx isKindOfClass:[NSNull class]] )
continue;
[self setValue:idx forKey:key];
}
@catch (NSException *e) { WLLOG(@"%@: UnKnown Key:%@ - Value:%@", [e name], key, idx); }
@finally { }
}
}
return self;
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLBaseItem.h
The WLAPSItem object is used to model the attributes for the received Remote
Notification (Push) in a structured way.
@copyright Warply Inc.
*/
#import <Foundation/Foundation.h>
#import "WLAPSItem.h"
/*!
@class WLBaseItem
@discussion This object contains the attributes for the received Remote Notification
(Push) such as message, custom data, action etc.
*/
@interface WLBaseItem : NSObject
{
@private
NSInteger _action;
NSString *_session_uuid;
NSString *_trace;
NSString *_message;
WLAPSItem *_apsItem;
NSDictionary *_customData;
}
/*!
@property action
@abstract An integer id for the action need to be executed for the received
remote notification (push).
*/
@property (nonatomic) NSInteger action;
/*!
@property openedCount
@abstract An integer counter of the times the offer html has been loaded by the user.
*/
@property (nonatomic) NSInteger openedCount;
/*!
@property session_uuid
@abstract A string object with unique identification of the received remote
notification (push).
*/
@property (nonatomic, copy) NSString *session_uuid;
/*!
@property trace
@abstract A string object with a tracing identification of the received remote
notification (push).
*/
@property (nonatomic, copy) NSString *trace;
/*!
@property message
@abstract A string object with a message of the received remote notification
(push).
*/
@property (nonatomic, copy) NSString *message;
/*!
@property apsItem
@abstract A WLAPSItem object with a user notification parameters of the
received remote notification (push).
@seealso //apple_ref/occ/cl/WLAPSItem WLAPSItem
*/
@property (nonatomic, strong) WLAPSItem *apsItem;
/*!
@property customData
@abstract A dictionary object with key-value arbitrary data contained inside the
received remote notification (push).
*/
@property (nonatomic, strong) NSDictionary *customData;
/*!
@methodgroup Initializing a WLBaseItem Object
*/
/*!
@abstract Initialise a WLBaseItem Object.
@discussion Initializes and returns a newly allocated WLAPSItem object with the
specified attributes.
@param attributes A dictionary object which contains remote notification attributes.
@return Returns WLBaseItem object.
*/
- (id)initWithAttributes:(NSDictionary *)attributes;
/*!
@methodgroup Getting WLBaseItem URLs
*/
/*!
@abstract Get Remote Notification (Push) page url.
@discussion Returns the url for the web page of the offer related to the received
Remote Notification (push).
@return Returns a string object with offer web page url.
*/
- (NSString *)getPageURL;
/*!
@abstract Get Remote Notification (Push) image url.
@discussion Returns the url for the placeholder image of the offer related to the
received Remote Notification (push).
@return Returns a string object with the offer placeholder url.
*/
- (NSString *)getImageURL;
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "WLBaseItem.h"
#import "WLGlobals.h"
#import "Warply.h"
@implementation WLBaseItem
@synthesize action = _action;
@synthesize session_uuid = _session_uuid;
@synthesize trace = _trace;
@synthesize message = _message;
@synthesize apsItem = _apsItem;
@synthesize customData = _customData;
#pragma mark - Initialization
///////////////////////////////////////////////////////////////////////////////
- (id)initWithAttributes:(NSDictionary *)attributes
{
self = [super init];
if (self) {
self.customData = [NSMutableDictionary dictionary];
NSObject *idx = nil;
for (NSString *key in [attributes allKeys]) {
idx = [attributes objectForKey:key];
@try {
if ([idx isKindOfClass:[NSNull class]] )
continue;
if ([key isEqualToString:@"_a"])
[self setValue:idx forKey:@"action"];
else if ([key isEqualToString:@"aps"])
_apsItem = [[WLAPSItem alloc] initWithAttributes:(NSDictionary*)idx];
else
[self setValue:idx forKey:key];
}
@catch (NSException *e) {
[_customData setValue:idx forKey:key];
WLLOG(@"%@: UnKnown Key:%@ - Value:%@", [e name], key, idx); }
@finally { }
}
}
return self;
}
#pragma mark - Properties
///////////////////////////////////////////////////////////////////////////////
- (NSString*)message
{
if (_apsItem != nil)
return _apsItem.alert;
return _message;
}
#pragma mark - Public Methods
///////////////////////////////////////////////////////////////////////////////
- (NSString *)getPageURL
{
return [NSString stringWithFormat:WARP_PAGE_URL_FORMAT, [[Warply sharedService] baseURL], _session_uuid];
}
///////////////////////////////////////////////////////////////////////////////
- (NSString *)getImageURL
{
return [NSString stringWithFormat:WARP_IMAGE_URL_FORMAT, [[Warply sharedService] baseURL], _session_uuid];
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLBeacon.h
The WLBeacon object is used to model the parameters of the iBeacon device
that the Service is going to monitor
@copyright Warply Inc.
*/
#import <Foundation/Foundation.h>
/*!
@class WLBeacon
@discussion This object contains the parameters for the iBeacon device
that the WLBeaconManager will monitor.
*/
@interface WLBeacon : NSObject
/*!
@property beaconIdentifier
@abstract A string identifier for an iBeacon device.
*/
@property(nonatomic, copy) NSString *beaconIdentifier;
/*!
@property beaconUUID
@abstract The UUID string that is bounded with an iBeacon device.
*/
@property(nonatomic, strong) NSUUID *beaconUUID;
/*!
@methodgroup Initializing a WLBeacon Object
*/
/*!
@abstract Initialise a WLBeacon object.
@discussion Initializes and returns a newly allocated WLBeacon object with the specified
attributes.
@param uuid A string that contains the UUID of the iBeacon device.
@param identifier A string identifier that characterizes the iBeacon device.
@return Returns WLBeacon object.
*/
- (instancetype)initWithUUID:(NSString*)uuid identifier:(NSString*)identifier;
@end
//
// WLBeaconRegion.m
// DemoApp
//
// Created by Sergey Korobyin on 09.06.15.
// Copyright (c) 2015 YC. All rights reserved.
//
#import "WLBeacon.h"
@implementation WLBeacon
- (instancetype)initWithUUID:(NSString*)uuid identifier:(NSString*)identifier{
if (self = [super init]) {
_beaconUUID = [[NSUUID alloc] initWithUUIDString:uuid];
_beaconIdentifier = identifier;
}
return self;
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLInboxItem.h
The WLInboxItem object is used to model the information related to the offer for
which the Remote Notification (Push) was sent.
@copyright Warply Inc.
*/
#import <Foundation/Foundation.h>
#import "WLBaseItem.h"
#import <CoreLocation/CoreLocation.h>
/*!
@class WLInboxItem
@discussion This object contains the information related to the offer for
which the Remote Notification (Push) was sent, such as: offer title and subtitle,
offer message, offer category, expiration date etc.
*/
@interface WLInboxItem : WLBaseItem
/*!
@property title
@abstract An string object with the offer title.
*/
@property (nonatomic, copy) NSString *title;
/*!
@property subtitle
@abstract An string object with the offer subtitle.
*/
@property (nonatomic, copy) NSString *subtitle;
/*!
@property offer_message
@abstract An string object with the offer message.
*/
@property (nonatomic, copy) NSString *offer_message;
/*!
@property offer_category
@abstract An string object with the offer category.
*/
@property (nonatomic, copy) NSString *offer_category;
/*!
@property expires
@abstract An integer object with the offer expiration date (epoch format).
*/
@property(nonatomic) NSInteger expires;
/*!
@property starts
@abstract An integer object with the offer starting date (epoch format).
*/
@property(nonatomic) NSInteger starts;
/*!
@property delivered
@abstract An integer with the time / date the offer was delivered (epoch format).
*/
@property (nonatomic) NSInteger delivered;
@property (nonatomic) NSString *extra_fields;
/*!
@property opened
@abstract An integer counting the times this offer has been opened.
*/
@property (nonatomic) NSInteger opened;
/*!
@property sorting
@abstract An NSNumber wrapping an int indicating the suggested order of the offers from the server in descending order.
*/
@property (nonatomic) NSInteger sorting;
/*!
@property is_new
@abstract A a BOOL indicating whether the item is new (it is the first time it is being presented in the inbox of the user
*/
@property (nonatomic) BOOL is_new;
/*!
@property location
@abstract This property is a CLLocation object if the inbox item is connected to a geofencing poi and nil otherwise
*/
@property (nonatomic) CLLocation *location;
/*!
@property distance
@abstract The distance from the location the getInboxItemsNearLocation:withSuccessBlock:failureBlock: call uses as a parameter or from the users current location if the getInboxItemsNearMeWithSuccessBlock:failureBlock: was used to retrieve the inbox items.
*/
@property (nonatomic) CLLocationDistance distance;
/*!
@property radius
@abstract The radius of the corresponding geofence.
@discussion If the inbox item is linked to a geofencing campaign, and the users location is inside this radius, they will get a push notification.
*/
@property (nonatomic) CLLocationDistance radius;
/*!
@property name
@abstract The alias of the item in case it is linked to a location (location != nil).
@see //apple_ref/occ/instp/WLInboxItem/location location
*/
@property (nonatomic) NSString *name;
/**
* @property display_type
@abstract This property defines the type of the native ad.
@discussion It can be full_page, half_page, list or feed.
*/
@property (nonatomic) NSString *display_type;
/*!
@property campaign_type
@abstract This property defines the type of the campaign.
@discussion It can be standard-offer, beacon, etc.
*/
@property (nonatomic) NSString *campaign_type;
/*!
@methodgroup Initializing a WLInboxItem Object
*/
/*!
@abstract Initialise a WLInboxItem Object.
@discussion Initializes and returns a newly allocated WLInboxItem object with
the specified WLBaseItem object.
@param baseItem A WLBaseItem object.
@return Returns WLInboxItem object.
@see //apple_ref/occ/cl/WLBaseItem WLBaseItem
*/
- (id)initWithItem:(WLBaseItem *)baseItem;
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "WLInboxItem.h"
#import "WLGlobals.h"
#import "Warply.h"
#import "WLBaseItem.h"
@implementation WLInboxItem
#pragma mark - Initialization
///////////////////////////////////////////////////////////////////////////////
- (id)initWithItem:(WLBaseItem *)baseItem
{
self = [super init];
if (self) {
self.action = baseItem.action;
self.session_uuid = baseItem.session_uuid;
self.trace = baseItem.trace;
self.message = baseItem.message;
self.apsItem = baseItem.apsItem;
}
return self;
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLInboxItemViewController.h
The WLInboxItemViewController is a UIWebViewController that shows modally the
web page of the selected offer (WLInboxItem).
@copyright Warply Inc.
*/
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
@class WLInboxItem;
/*!
@class WLInboxItemViewController
@discussion This controller shows up modally and renders the web page of the
selected offer (WLInboxItem). Also handles the click-to-action functionality
specified such as pre-populated sms, QR Scanner etc.
*/
@interface WLInboxItemViewController : UIViewController <UIWebViewDelegate, UIAlertViewDelegate>
/*!
@property requestedUrl
@abstract An url object with link of the request offer web page.
*/
@property (nonatomic, readonly) NSURL *requestedUrl;
/*!
@property session_uuid
@abstract An string object with a unique session identifier.
*/
@property (nonatomic, readonly) NSString *session_uuid;
/*!
@property hideNavigationArrows
@abstract A BOOL flag that determines if the navigation arrows of the toolbar that control the back / forward funtionality in the webview are hidden or not.
*/
@property (nonatomic) BOOL hideNavigationArrows;
/*!
@property webView
@abstract The UIWebView that displays the offer's html content. By default, the scalesPageToFit property of the webView is set to YES.
*/
@property (nonatomic, readonly) WKWebView *webView;
/*!
@property fromFullPage
@abstract It can be set to YES when we want to present the WLInboxViewController modally, so there is an option to close the comtroller. Default is NO and the controller assumes a push segue.
*/
@property (nonatomic) BOOL fromFullPage;
/*!
@property fromNativeAd
@abstract It can be set to YES when we want to present the WLInboxViewController modally, so there is an option to close the comtroller. Default is NO and the controller assumes a push segue.
*/
@property (nonatomic) BOOL fromNativeAd;
/*!
@methodgroup Initializing a WLInboxItem View
*/
/*!
@abstract Initialise a WLInboxItem View.
@discussion Initializes and returns a newly allocated WLInboxItem View controller
with the specified WLInboxItem object.
@param anItem A WLInboxItem object.
@return Returns WLInboxItemViewController object.
@see //apple_ref/occ/cl/WLInboxItem WLInboxItem
*/
- (id)initWithItem:(WLInboxItem*)anItem;
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "WLInboxItemViewController.h"
#import "WLGlobals.h"
#import "WLAnalyticsManager.h"
#import "Warply.h"
#import "WLInboxItem.h"
#import "WLAPPActionHandler.h"
///////////////////////////////////////////////////////////////////////////////
@interface WLInboxItemViewController ()
{
@private
//UI
WKWebView *_webView;
UIActivityIndicatorView *_activity;
UIButton *_btnBack;
UIButton *_btnForward;
NSTimer *_timer;
}
@property (nonatomic, strong) WLInboxItem *item;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) WLInboxItemViewController *inboxVC;
- (void)updateButtons;
- (void)backPressed;
- (void)forwardPressed;
- (void)closePressed;
- (void)onTimer:(NSTimer*)sender;
@end
@implementation WLInboxItemViewController
//Private
@synthesize item = _item;
@synthesize timer = _timer;
#pragma mark - Initialization
///////////////////////////////////////////////////////////////////////////////
- (id)initWithItem:(WLInboxItem *)anItem
{
self = [super init];
if (self) {
self.item = anItem;
}
return self;
}
#pragma mark - View Lifecycle
///////////////////////////////////////////////////////////////////////////////
- (void)loadView
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 480.0)];
view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
view.backgroundColor = [UIColor blackColor];
UIView *statusView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 20.0)];
statusView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
statusView.backgroundColor = [UIColor whiteColor];
[view addSubview:statusView];
WKPreferences *preferences = [[WKPreferences alloc] init];
preferences.javaScriptEnabled = YES; // Here its set
// Other things you might want to disable
preferences.javaScriptCanOpenWindowsAutomatically = YES;
//Init WebView
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0.0, 20.0, 320.0, 480.0)];
//_webView.dataDetectorTypes = UIDataDetectorTypeNone;
WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
theConfiguration.preferences = preferences;
theConfiguration.dataDetectorTypes = UIDataDetectorTypeNone;
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0.0, 20.0, 320.0, 480.0) configuration:theConfiguration];
_webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
_webView.navigationDelegate = self;
[view addSubview:_webView];
//Init ActivityView
_activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
_activity.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
_activity.center = _webView.center;
_activity.alpha = 0.0;
[view addSubview:_activity];
self.view = view;
}
-(NSString *)session_uuid
{
return _item.session_uuid;
}
///////////////////////////////////////////////////////////////////////////////
- (void)viewDidLoad
{
[super viewDidLoad];
//Back Button
_btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
[_btnBack setImage:[UIImage imageNamed:@"warp_white_back_button.png"] forState:UIControlStateNormal];
[_btnBack sizeToFit];
[_btnBack addTarget:self action:@selector(backPressed) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithCustomView:_btnBack];
//Forward Button
_btnForward = [UIButton buttonWithType:UIButtonTypeCustom];
[_btnForward setImage:[UIImage imageNamed:@"warp_white_forward_button.png"] forState:UIControlStateNormal];
[_btnForward sizeToFit];
[_btnForward addTarget:self action:@selector(forwardPressed) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *forwardBarButton = [[UIBarButtonItem alloc] initWithCustomView:_btnForward];
_btnForward.hidden = _hideNavigationArrows;
_btnBack.hidden = _hideNavigationArrows;
//Close Button
UIButton *btnClose = [[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 44.0, 44.0)];
btnClose.backgroundColor = [UIColor clearColor];
[btnClose setImage:[UIImage imageNamed:@"warp_white_close_button.png"] forState:UIControlStateNormal];
[btnClose addTarget:self action:@selector(closePressed) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *closeBarButton = [[UIBarButtonItem alloc] initWithCustomView:btnClose];
//temp close button
UIButton *tmpClose = [[UIButton alloc] initWithFrame:CGRectMake(260.0, 30.0, 44.0, 44.0)];
if ([UIScreen mainScreen].bounds.size.height < 568) {
tmpClose.frame = CGRectMake(260.0, 30.0, 44.0, 44.0);
} else if ([UIScreen mainScreen].bounds.size.height < 667) {
tmpClose.frame = CGRectMake(260.0, 30.0, 44.0, 44.0);
} else if ([UIScreen mainScreen].bounds.size.height < 736) {
tmpClose.frame = CGRectMake(315.0, 30.0, 44.0, 44.0);
} else {
tmpClose.frame = CGRectMake(354.0, 30.0, 44.0, 44.0);
}
tmpClose.backgroundColor = [UIColor colorWithRed:0.24 green:0.29 blue:0.32 alpha:0.7];
tmpClose.layer.cornerRadius = 22.0;
tmpClose.clipsToBounds = YES;
[tmpClose setImage:[UIImage imageNamed:@"warp_white_close_button.png"] forState:UIControlStateNormal];
[tmpClose addTarget:self action:@selector(closePressed) forControlEvents:UIControlEventTouchUpInside];
if (_fromFullPage || _fromNativeAd) {
[self.view addSubview:tmpClose];
[UIApplication sharedApplication].statusBarHidden = YES;
}
// [self.view addSubview:tmpClose];
//Toolbar
self.navigationController.toolbar.tintColor = [UIColor blackColor];
if ([self.navigationController.toolbar respondsToSelector:@selector(setBarTintColor:)]) {
self.navigationController.toolbar.barTintColor = [UIColor blackColor];
}
self.navigationController.toolbar.backgroundColor = [UIColor blackColor];;
self.navigationController.toolbar.translucent = NO;
UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:NULL];
UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:NULL];
space.width = 40.0f;
NSArray *items = [NSArray arrayWithObjects: backBarButton, space, forwardBarButton, flex, closeBarButton, nil];
[self setToolbarItems:items];
[self.navigationController setNavigationBarHidden:YES animated:YES];
[self.navigationController.tabBarController setHidesBottomBarWhenPushed:YES];
[_activity startAnimating];
[UIView animateWithDuration:0.5 animations:^{
_activity.alpha = 1.0;
}];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[_item getPageURL]]];
request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
[request setValue:[Warply sharedService].webId forHTTPHeaderField:@"loyalty-web-id"];
[request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
[request setValue:@"gzip" forHTTPHeaderField:@"User-Agent"];
[_webView loadRequest:request];
NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
[wkUController addUserScript:wkUScript];
WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
wkWebConfig.userContentController = wkUController;
_webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:wkWebConfig];
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
[Warply sharedService].allOffers = nil;
[[Warply sharedService] getInboxWithSuccessBlock: nil failureBlock:nil];
}
///////////////////////////////////////////////////////////////////////////////
- (void)viewDidUnload
{
[super viewDidUnload];
[_webView setUIDelegate:nil];
}
///////////////////////////////////////////////////////////////////////////////
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
return (toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
///////////////////////////////////////////////////////////////////////////////
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAllButUpsideDown;
}
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
NSLog(@"createWebViewWithConfiguration %@ %@", navigationAction, windowFeatures);
if (!navigationAction.targetFrame.isMainFrame) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[(WKWebView *)_webView loadRequest:navigationAction.request];
}
return nil;
}
#pragma mark - UIWebViewDelegater
///////////////////////////////////////////////////////////////////////////////
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//NSURL *url = [navigationAction.request.URL query];
if ([navigationAction.request.URL.scheme isEqualToString:@"tel"]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[navigationAction.request.URL.resourceSpecifier stringByReplacingOccurrencesOfString:@"/" withString:@""] message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", @"Warply") otherButtonTitles:NSLocalizedString(@"Call", @"Warply"), nil];
alert.tag = 1000;
[alert show];
}
decisionHandler(WKNavigationActionPolicyAllow);
NSString *url = navigationAction.request.URL.absoluteString;
if ([navigationAction.request.URL.absoluteString containsString:@"mobile_store"]) {
if ([[UIApplication sharedApplication] canOpenURL:navigationAction.request.URL]) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil];
[UIApplication sharedApplication].statusBarHidden = NO;
[self dismissViewControllerAnimated:YES completion:nil];
}
}
if([[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleURLTypes"]) {
NSArray *urlTypes = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleURLTypes"];
for(NSDictionary *urlType in urlTypes)
{
if(urlType[@"CFBundleURLSchemes"])
{
NSArray *urlSchemes = urlType[@"CFBundleURLSchemes"];
for(NSString *urlScheme in urlSchemes)
if ([navigationAction.request.URL.absoluteString containsString:urlScheme]) {
float seconds = 2.5;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if ([[UIApplication sharedApplication] canOpenURL:navigationAction.request.URL]) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:navigationAction.request.URL.absoluteString] options:@{} completionHandler:nil];
[UIApplication sharedApplication].statusBarHidden = NO;
[self dismissViewControllerAnimated:YES completion:nil];
}
});
}
}
}
}
if (navigationAction.navigationType == UIWebViewNavigationTypeLinkClicked) {
if ([[UIApplication sharedApplication] canOpenURL:navigationAction.request.URL]) {
[[UIApplication sharedApplication] openURL:navigationAction.request.URL options:@{} completionHandler:nil];
}
[UIApplication sharedApplication].statusBarHidden = NO;
[self dismissViewControllerAnimated:YES completion:nil];
}
}
- (BOOL)webView:(WKWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
_requestedUrl = request.URL;
if ([request.URL.scheme isEqualToString:@"tel"]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[request.URL.resourceSpecifier stringByReplacingOccurrencesOfString:@"/" withString:@""] message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", @"Warply") otherButtonTitles:NSLocalizedString(@"Call", @"Warply"), nil];
alert.tag = 1000;
[alert show];
return NO;
}
[self updateButtons];
WLLOG(@"WARPLY OFFER WEBVIEW REQUEST URL:%@",request.URL);
if ([[Warply sharedService] handleActionUrl:_requestedUrl]) {
return NO;
}
return YES;
}
///////////////////////////////////////////////////////////////////////////////
//- (void)webViewDidStartLoad:(WKWebView *)webView {
//
//}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
}
///////////////////////////////////////////////////////////////////////////////
//- (void)webViewDidFinishLoad:(WKWebView *)webView
//{
// WLLOG(@"Finished Loading Campaign.");
// [self updateButtons];
// [UIView animateWithDuration:0.5
// animations:^{
// _activity.alpha = 0.0;
// }
// completion:^(BOOL finished) {
// [_activity stopAnimating];
// }];
//}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
WLLOG(@"Finished Loading Campaign.");
[self updateButtons];
[UIView animateWithDuration:0.5
animations:^{
_activity.alpha = 0.0;
}
completion:^(BOOL finished) {
[_activity stopAnimating];
}];
}
///////////////////////////////////////////////////////////////////////////////
//- (void)webView:(WKWebView *)webView didFailLoadWithError:(NSError *)error
//{
// WLLOG(@"Error while loading page = %@", [error description]);
// [self updateButtons];
//}
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
WLLOG(@"Error while loading page = %@", [error description]);
[self updateButtons];
}
#pragma mark - Private Methods
///////////////////////////////////////////////////////////////////////////////
- (void)updateButtons
{
_btnBack.enabled = _webView.canGoBack;
_btnForward.enabled = _webView.canGoForward;
}
///////////////////////////////////////////////////////////////////////////////
- (void)backPressed
{
[_webView goBack];
}
///////////////////////////////////////////////////////////////////////////////
- (void)forwardPressed
{
[_webView goForward];
}
///////////////////////////////////////////////////////////////////////////////
- (void)closePressed
{
[UIApplication sharedApplication].statusBarHidden = NO;
[self dismissViewControllerAnimated:YES completion:nil];
}
///////////////////////////////////////////////////////////////////////////////
- (void)onTimer:(NSTimer*)sender
{
[self updateButtons];
}
///////////////////////////////////////////////////////////////////////////////
#pragma mark - Alert View Delegate
// If the alert view is a call confirmation prompt send the appropriate action analytic event
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (alertView.tag != 1000) {
return;
}
NSArray *callActions;
switch (buttonIndex) {
case 0:
callActions = @[@"call_cancelled"];
[WLAnalyticsManager logUrgentEventWithEventId:@"NB_CUSTOM_ACTION" pageId:@"TEL" actionMetadata:@{@"session_uuid":self.item.session_uuid, @"result": callActions}];
break;
default:
callActions = @[@"call_clicked"];
[WLAnalyticsManager logUrgentEventWithEventId:@"NB_CUSTOM_ACTION" pageId:@"TEL" actionMetadata:@{@"session_uuid":self.item.session_uuid, @"result": callActions}];
[[UIApplication sharedApplication] openURL:_requestedUrl];
}
}
#pragma mark - Memory Management
///////////////////////////////////////////////////////////////////////////////
- (void)dealloc
{
[_timer invalidate];
[_webView setUIDelegate:nil];
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLAnalyticsManager.h
The Analytics Manager provides a functional interface for in-app analytics.
Use the methods declared here to send in-app analytics wherever is needed within
the application.
@copyright Warply Inc.
*/
#import <Foundation/Foundation.h>
#import "WLBaseItem.h"
/*!
@class WLAnalyticsManager
@discussion This manager handles the in-app analytics functionality of Warply
service.
*/
@interface WLAnalyticsManager : NSObject
/*!
@methodgroup Sending In-App Analytics
*/
/*!
@abstract Sends an in-app analytic.
@discussion This class method sends an in-app analytic event. This event is stored
into a local DB and is sent over to Warply service when a threshold of stored
events is exceeded.
@param event_id A string object that specifies the event that happened. Developer
defined string.
@param page_id A string object that specifies where the event happened. Developer
defined string.
@param action_metadata A dictionary object with metadata related for the event.
Developer defined dictionary.
@seealso //apple_ref/occ/clm/WLAnalyticsManager/sendAnalyticsEventWithEvent_id:page_id:action_metadata: sendAnalyticsEventWithEvent_id:page_id:action_metadata:
*/
+ (void)logEventWithEventId:(NSString *)event_id pageId:(NSString *)page_id actionMetadata:(NSDictionary *)action_metadata;
/*!
@abstract Sends an Urgent in-app analytic.
@discussion This class method sends an urgent in-app analytic event. This event
is sent to Warply service immediately. It is advised to use this type of event only
in places of the application where almost real-time analytic reporting is required.
@param event_id A string object that specifies the event that happened. Developer
defined string.
@param page_id A string object that specifies where the event happened. Developer
defined string.
@param action_metadata A dictionary object with metadata related for the event.
Developer defined dictionary.
@seealso //apple_ref/occ/clm/WLAnalyticsManager/sendPriorityAnalyticsEventWithEvent_id:page_id:action_metadata: sendPriorityAnalyticsEventWithEvent_id:page_id:action_metadata:
*/
+ (void)logUrgentEventWithEventId:(NSString *)eventId pageId:(NSString *)pageId actionMetadata:(NSDictionary *)action_metadata;
/*!
@abstract Sends an in-app analytic event indicating that the user interacted with the push.
@param item The WLBaseItem representation of the push payload. You can create it like this: WLBaseItem *item = [WLBaseItem alloc] initWithAttributes:payload];
terminates.
*/
+ (void)logUserEngagedPush:(WLBaseItem *)item;
+ (void)logUserReceivedPush:(WLBaseItem *)item;
//TODO: Add documentation
+ (void)logAppDidFinishLauchingEvent;
+ (void)logAppWillEnterForegroundEvent;
+ (void)logAppWillTerminateEvent;
+ (void)logAppDidEnterBackgroundEvent;
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "WLAnalyticsManager.h"
#import "Warply.h"
@implementation WLAnalyticsManager
#pragma mark - Static Public Methods
///////////////////////////////////////////////////////////////////////////////
+ (void)logEventWithEventId:(NSString *)eventId
pageId:(NSString *)pageId
actionMetadata:(NSDictionary *)actionMetadata
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CUSTOM_ANALYTICS_ENABLED))
return;
[self internalLogEventWithEventId:eventId
pageId:pageId
actionMetadata:actionMetadata];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)logUrgentEventWithEventId:(NSString *)eventId
pageId:(NSString *)pageId
actionMetadata:(NSDictionary *)actionMetadata
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CUSTOM_ANALYTICS_ENABLED))
return;
[self internalLogUrgentEventWithEventId:eventId
pageId:pageId
actionMetadata:actionMetadata];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)logAppDidFinishLauchingEvent
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_LIFECYCLE_ANALYTICS_ENABLED))
return;
[WLAnalyticsManager internalLogEventWithEventId:@"NB_DidFinishLaunching"
pageId:@"NB_APP"
actionMetadata:nil];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)logAppWillEnterForegroundEvent
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_LIFECYCLE_ANALYTICS_ENABLED))
return;
if([[NSUserDefaults standardUserDefaults] boolForKey:WL_LIFECYCLE_ANALYTICS_ENABLED]) {
[WLAnalyticsManager internalLogEventWithEventId:@"session"
pageId:@"NB_APP"
actionMetadata:nil];
}
}
///////////////////////////////////////////////////////////////////////////////
+ (void)logAppWillTerminateEvent
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_LIFECYCLE_ANALYTICS_ENABLED))
return;
[WLAnalyticsManager internalLogEventWithEventId:@"NB_WillTerminate"
pageId:@"NB_APP"
actionMetadata:nil];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)logAppDidEnterBackgroundEvent
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_LIFECYCLE_ANALYTICS_ENABLED))
return;
[WLAnalyticsManager internalLogEventWithEventId:@"session"
pageId:@"NB_APP"
actionMetadata:nil];
}
#pragma mark - Static Private Methods
///////////////////////////////////////////////////////////////////////////////
+ (void)internalLogEventWithEventId:(NSString *)eventId
pageId:(NSString *)pageId
actionMetadata:(NSDictionary *)actionMetadata
{
NSNumber *time_submitted = [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]];
NSDictionary *inapp_event = [NSDictionary dictionaryWithObjectsAndKeys:eventId, @"event_id", pageId, @"page_id", time_submitted, @"time_submitted", actionMetadata, @"action_metadata", nil];
NSDictionary *eventContext = [NSDictionary dictionaryWithObject:inapp_event forKey:@"inapp_analytics"];
WLEventSimple *event = [[WLEventSimple alloc] initWithType:@"inapp_analytics" andContext:eventContext];
[[Warply sharedService] addEvent:event priority:NO];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)internalLogUrgentEventWithEventId:(NSString *)eventId
pageId:(NSString *)pageId
actionMetadata:(NSDictionary *)actionMetadata
{
NSNumber *time_submitted = [NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]];
NSDictionary *inapp_event = [NSDictionary dictionaryWithObjectsAndKeys:eventId, @"event_id", pageId, @"page_id", time_submitted, @"time_submitted", actionMetadata, @"action_metadata", nil];
NSDictionary *eventContext = [NSDictionary dictionaryWithObject:inapp_event forKey:@"inapp_analytics"];
WLEventSimple *event = [[WLEventSimple alloc] initWithType:@"inapp_analytics" andContext:eventContext];
[[Warply sharedService] addEvent:event priority:YES];
}
#pragma mark - Push Analytics
///////////////////////////////////////////////////////////////////////////////
+ (void)logUserEngagedPush:(WLBaseItem *)item
{
[WLAnalyticsManager internalLogUrgentEventWithEventId:@"NB_PushAck"
pageId:@"NB_APP"
actionMetadata:[NSDictionary dictionaryWithObjectsAndKeys:item.session_uuid, @"session_uuid", nil]];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)logUserReceivedPush:(WLBaseItem *)item
{
[WLAnalyticsManager internalLogUrgentEventWithEventId:@"NB_PushReceived"
pageId:@"NB_APP"
actionMetadata:[NSDictionary dictionaryWithObjectsAndKeys:item.session_uuid, @"session_uuid", nil]];
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLBeaconManager.h
The Beacon Manager provides functionality for iBeacons detection and serving advertisements related to the beacons that are scanned from the device.
@copyright Warply Inc.
*/
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@class WLInboxItem;
@class WLBaseItem;
/*!
@class WLBeaconManager
@discussion This manager handles beacon served campaigns and detecting iBeacon devices in range.
service.
*/
@interface WLBeaconManager : NSObject
/*!
@property pendingItem
@abstract The remote notification as a WLBaseItem currently stored for later use.
*/
@property (nonatomic, strong) WLBaseItem *pendingItem;
@property (strong, nonatomic) CLLocationManager *locationManager;
/*!
@methodgroup Getting Shared Instance
*/
/*!
@abstract Returns a shared instance of WLBeaconManager.
*/
+ (WLBeaconManager *)sharedInstance;
/*!
@methodgroup Launching beacon manager and beacon monitoring.
*/
/*!
@abstract Launching the Warply Beacon Manager.
@discussion This method initialises the shared instance of WLBeaconManager and passes an array of the beacon identifiers that the manager will search for.
@param devices An array of beacon UUID's and identifiers for the manager to monitor.
*/
- (void) startMonitorWithBeaconsArray:(NSArray*)devices;
/*!
@abstract Shows the campaign that was received from a beacon device.
@discussion This class method presents the campaign that is bounded with an iBeacon device after a successful retrieval of the data of the campaign.
@param item The WLInboxItem that contains all the necessary data of the campaign to be presented.
*/
+ (void)showItem:(WLInboxItem*)item;
@end
//
// WLBeaconManager.m
// DemoApp
//
// Created by Warply on 09.06.15.
// Copyright (c) 2015 YC. All rights reserved.
//
#import "WLBeaconManager.h"
#import "Warply.h"
#import <CoreLocation/CoreLocation.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#import <math.h>
#import "WLInboxItemViewController.h"
#import "UIViewController+WLAdditions.h"
#import "WLBaseItem.h"
@interface WLBeaconManager () <CLLocationManagerDelegate>
//@property (nonatomic, strong) CLLocationManager* locationManager;
@property(nonatomic, strong) NSArray *beaconRegions;
@property (nonatomic, strong) NSMutableSet* insideBeaconRegions;
@property (strong, nonatomic) NSMutableArray *alreadyCheckedBeacon;
@end
@implementation WLBeaconManager{
NSInteger currentTime;
}
+ (WLBeaconManager *)sharedInstance{
static dispatch_once_t pred;
static WLBeaconManager *shared = nil;
dispatch_once(&pred, ^{
shared = [[WLBeaconManager alloc] init];
});
return shared;
}
- (instancetype)init{
if (self = [super init]) {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.alreadyCheckedBeacon = [NSMutableArray array];
NSString *identifier = @"Warply";
NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:@"9439f6fb-8895-40e9-9849-57454fd9b228"];
// NSString *identifier = @"Place 1";
// NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:@"B9407F30-F5F8-466E-AFF9-25556B57FE6D"];
CLBeaconRegion *beacon = [[CLBeaconRegion alloc] initWithProximityUUID:uuid identifier:identifier];
beacon.notifyOnEntry = YES;
beacon.notifyOnExit = YES;
beacon.notifyEntryStateOnDisplay = YES;
if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
[self.locationManager requestAlwaysAuthorization];
}
currentTime = (NSInteger)getTickCount();
self.locationManager.pausesLocationUpdatesAutomatically = NO;
[self.locationManager startMonitoringSignificantLocationChanges];
[self.locationManager startMonitoringForRegion:beacon];
}
return self;
}
- (void) startMonitorWithBeaconsArray:(NSArray*)devices{
NSInteger timeInterval = [[NSUserDefaults standardUserDefaults] integerForKey:WL_BEACON_TIME_INTERVAL_TO_RESEND];
NSLog(@"Time interval %ld", (long)timeInterval);
NSMutableArray *tempArray = [NSMutableArray array];
for (NSDictionary *item in devices) {
NSUUID *beaconUUID = [[NSUUID alloc] initWithUUIDString:item[@"UUID"]];
NSString *beaconIdentifier = item[@"beaconIdentifier"];
CLBeaconRegion *region = [[CLBeaconRegion alloc] initWithProximityUUID:beaconUUID identifier:beaconIdentifier];
[self.locationManager startMonitoringForRegion:region];
[self.locationManager startRangingBeaconsInRegion:region];
[self.locationManager startUpdatingLocation];
}
_beaconRegions = tempArray;
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
if (status == kCLAuthorizationStatusAuthorizedAlways) {
[self.locationManager startUpdatingLocation];
} else if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
[self.locationManager startUpdatingLocation];
}else if (status == kCLAuthorizationStatusRestricted){
NSLog(@"Need Location Service Permission To Access Beacon");
} else if(status == kCLAuthorizationStatusDenied){
NSLog(@"Need Location Service Permission To Access Beacon");
} else {
NSLog(@"Need Location Service Permission To Access Beacon");
}
}
- (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLBeaconRegion *)region
{
if (state == CLRegionStateInside) {
[self.locationManager startRangingBeaconsInRegion:region];
NSLog(@"inside region %@", region.proximityUUID.UUIDString);
} else if (state == CLRegionStateOutside) {
[self.locationManager stopRangingBeaconsInRegion:region];
} else {
//unknown?
}
}
- (void)locationManager:(CLLocationManager *)manager didStartMonitoringForRegion:(CLRegion *)region {
NSLog(@"start monitoring");
[self.locationManager requestStateForRegion:region];
}
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLBeaconRegion *)region
{
NSLog(@"Enter region %@", region.proximityUUID.UUIDString);
// [self showMessage:@"Hello"];
}
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLBeaconRegion *)region
{
NSLog(@"Exit region %@", region.proximityUUID.UUIDString);
// [self showMessage:@"Bye"];
}
-(void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region {
NSLog(@"beacons count %@", beacons);
for (CLBeacon *foundBeacon in beacons) {
if (_alreadyCheckedBeacon.count == 0) {
// NSLog(@"found beacon's uuid %@\t%@\t%@", foundBeacon.proximityUUID.UUIDString, foundBeacon.major, foundBeacon.minor);
[_alreadyCheckedBeacon addObject:foundBeacon];
[self getDateFromBeacon:foundBeacon];
} else {
BOOL beaconExists = NO;
for (CLBeacon *savedBeacon in _alreadyCheckedBeacon) {
NSInteger timeInterval;
if ([[NSUserDefaults standardUserDefaults] integerForKey:WL_BEACON_TIME_INTERVAL_TO_RESEND] > 0) {
timeInterval = [[NSUserDefaults standardUserDefaults] integerForKey:WL_BEACON_TIME_INTERVAL_TO_RESEND];
} else {
timeInterval = 3600000;
}
if ([savedBeacon.proximityUUID.UUIDString.lowercaseString isEqualToString:foundBeacon.proximityUUID.UUIDString.lowercaseString] && savedBeacon.major.intValue == foundBeacon.major.intValue && savedBeacon.minor.intValue == foundBeacon.minor.intValue) {
beaconExists = YES;
if (getTickCount() - currentTime >= timeInterval) {
[self getDateFromBeacon:foundBeacon];
}
}
}
if (!beaconExists) {
// NSLog(@"found beacon's uuid %@\t%d\t%d", foundBeacon.proximityUUID.UUIDString.lowercaseString, foundBeacon.major.intValue, foundBeacon.minor.intValue);
// NSLog(@"saved beacon's uuid %@\t%d\t%d", savedBeacon.proximityUUID.UUIDString.lowercaseString, savedBeacon.major.intValue, savedBeacon.minor.intValue);
// NSLog(@"found beacons count %lu", (unsigned long)_alreadyCheckedBeacon.count);
[_alreadyCheckedBeacon addObject:foundBeacon];
[self getDateFromBeacon:foundBeacon];
}
}
}
}
-(void)getDateFromBeacon:(CLBeacon *)beacon {
NSString *uuid = beacon.proximityUUID.UUIDString;
NSString *major = [NSString stringWithFormat:@"%@", beacon.major];
NSString *minor = [NSString stringWithFormat:@"%@", beacon.minor];
// NSLog(@"beacon's uuid %@\t%@\t%@", beacon.proximityUUID.UUIDString, beacon.major, beacon.minor);
// NSLog(@"saved beacons in array %@", _alreadyCheckedBeacon);
// NSLog(@"time difference %llu", getTickCount() - currentTime);
currentTime = (NSInteger)getTickCount();
NSDictionary *postDictionary = @{@"beacon":@{@"data":@[@{@"uuid":uuid.lowercaseString, @"major":major, @"minor": minor, @"distance":@(beacon.accuracy)}], @"action": @"beacon"}};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:0 error:NULL];
[[Warply sharedService] sendContext:jsonData successBlock:^(NSDictionary *contextResponse) {
// NSLog(@"beacon response %@", contextResponse);
if ([[contextResponse valueForKey:@"MAPP_BEACON-status"] integerValue] == 1 && [contextResponse[@"MAPP_BEACON"] isKindOfClass:[NSArray class]]) {
[self sendLocalNotificationWithMessage:contextResponse];
}
} failureBlock:^(NSError *error) {
NSLog(@"Beacon error %@", error);
}];
}
-(void)sendLocalNotificationWithMessage:(NSDictionary*)message {
if (message != nil) {
self.pendingItem = [[WLBaseItem alloc] initWithAttributes:message[@"MAPP_BEACON"][0]];
UIApplicationState state = [[UIApplication sharedApplication] applicationState];
if (state == UIApplicationStateActive)
{
UIAlertView *alert = [[UIAlertView alloc] init];
[alert setTitle:message[@"MAPP_BEACON"][0][@"message"]];
[alert addButtonWithTitle:NSLocalizedString(@"Close", @"Warply")];
[alert addButtonWithTitle:NSLocalizedString(@"View", @"Warply")];
[alert setDelegate:self];
[alert show];
}else{
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.alertBody = message[@"MAPP_BEACON"][0][@"message"];
notification.userInfo = @{@"test": @"value"};
notification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
}
}
uint64_t getTickCount(void)
{
static mach_timebase_info_data_t sTimebaseInfo;
uint64_t machTime = mach_absolute_time();
NSLog(@"mach time: %llu", machTime);
// Convert to nanoseconds - if this is the first time we've run, get the timebase.
if (sTimebaseInfo.denom == 0 )
{
(void) mach_timebase_info(&sTimebaseInfo);
}
// Convert the mach time to milliseconds
uint64_t millis = ((machTime / 1000000) * sTimebaseInfo.numer) / sTimebaseInfo.denom;
return millis;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1) {
[WLAnalyticsManager logUserEngagedPush:self.pendingItem];
if (self.pendingItem == nil)
return;
WLInboxItem *inboxItem = [[WLInboxItem alloc] initWithItem:self.pendingItem];
[WLBeaconManager showItem:inboxItem];
self.pendingItem = nil;
}
}
+ (void)showItem:(WLInboxItem*)item
{
WLInboxItemViewController *itemViewController = [[WLInboxItemViewController alloc] initWithItem:item];
// itemViewController.fromFullPage = YES;
itemViewController.view.userInteractionEnabled = YES;
UINavigationController *newModalController = [[UINavigationController alloc] initWithRootViewController:itemViewController];
newModalController.navigationBarHidden = YES;
newModalController.toolbarHidden = NO;
//UIViewController *existingModalController = [UIApplication sharedApplication].delegate.window.rootViewController.navigationController.viewControllers.firstObject;
UIViewController *existingModalController = [[UIApplication sharedApplication].delegate.window.rootViewController topModalViewController];
NSLog(@"View Controller %@", [[UIApplication sharedApplication].delegate.window.rootViewController topModalViewController]);
if (existingModalController == nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"WL_Warning" message:@"You have to set the mainWindow.rootViewController in order for offer views to be presented properly." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
return;
}
[existingModalController presentViewController:newModalController animated:YES completion:nil];
}
- (void) showMessage: (NSString*) message {
NSLog(@"Show notification for region");
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.alertBody = message;
notification.soundName = UILocalNotificationDefaultSoundName;
notification.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
//
// UIApplicationState state = [[UIApplication sharedApplication] applicationState];
// if (state == UIApplicationStateBackground)
// {
// UILocalNotification *notification = [[UILocalNotification alloc] init];
// notification.alertBody = message;
// notification.soundName = UILocalNotificationDefaultSoundName;
// [[UIApplication sharedApplication] scheduleLocalNotification:notification];
//
//
// }else{
// UIAlertView *alert = [[UIAlertView alloc] init];
//// [alert setTitle:message[@"MAPP_BEACON"][0][@"message"]];
//// [alert addButtonWithTitle:NSLocalizedString(@"Close", @"Warply")];
//// [alert addButtonWithTitle:NSLocalizedString(@"View", @"Warply")];
//// [alert setDelegate:self];
// alert.title = message;
// [alert addButtonWithTitle:@"Ok"];
// [alert show];
// }
}
@end
//@interface WLBeaconManager () <CLLocationManagerDelegate>
//
//@property(nonatomic, strong) NSArray *beaconRegions;
//@property (strong, nonatomic) CLLocationManager *locationManager;
//@property (strong, nonatomic) NSMutableArray *alreadyCheckedBeacon;
//
//@end
//
//
//
//
//
//@implementation WLBeaconManager{
// NSInteger currentTime;
//}
//
//+ (WLBeaconManager *)sharedInstance{
// static dispatch_once_t pred;
// static WLBeaconManager *shared = nil;
// dispatch_once(&pred, ^{
// shared = [[WLBeaconManager alloc] init];
// });
// return shared;
//}
//
//- (instancetype)init{
// if (self = [super init]) {
// self.locationManager = [[CLLocationManager alloc] init];
// self.alreadyCheckedBeacon = [NSMutableArray array];
// if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
// [self.locationManager requestAlwaysAuthorization];
// [self.locationManager startMonitoringSignificantLocationChanges];
// self.locationManager.allowsBackgroundLocationUpdates = YES;
// currentTime = (NSInteger)getTickCount();
// }
//
// self.locationManager.delegate = self;
// }
//
// return self;
//}
//
//- (void) startMonitorWithBeaconsArray:(NSArray*)devices{
//
// NSInteger timeInterval = [[NSUserDefaults standardUserDefaults] integerForKey:WL_BEACON_TIME_INTERVAL_TO_RESEND];
// NSLog(@"Time interval %ld", (long)timeInterval);
//
// NSMutableArray *tempArray = [NSMutableArray array];
//
// for (NSDictionary *item in devices) {
// NSUUID *beaconUUID = [[NSUUID alloc] initWithUUIDString:item[@"UUID"]];
// NSString *beaconIdentifier = item[@"beaconIdentifier"];
// CLBeaconRegion *region = [[CLBeaconRegion alloc] initWithProximityUUID:beaconUUID identifier:beaconIdentifier];
// [self.locationManager startMonitoringForRegion:region];
// [self.locationManager startRangingBeaconsInRegion:region];
//
// [self.locationManager startUpdatingLocation];
// }
//
// _beaconRegions = tempArray;
//}
//
//
//
////- (void)locationManager:(CLLocationManager*)manager didEnterRegion:(CLRegion*)region
////{
//// [self.locationManager startRangingBeaconsInRegion:(CLBeaconRegion *)region];
////// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"In region" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
////// [alert show];
////}
////
////
////
////-(void)locationManager:(CLLocationManager*)manager didExitRegion:(CLRegion*)region
////{
//// [self.locationManager stopRangingBeaconsInRegion:(CLBeaconRegion *)region];
////// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Out region" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
////// [alert show];
////}
//
//
//
//-(void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region {
//
// NSLog(@"beacons count %@", beacons);
// for (CLBeacon *foundBeacon in beacons) {
//
// if (_alreadyCheckedBeacon.count == 0) {
// [_alreadyCheckedBeacon addObject:foundBeacon];
// [self getDateFromBeacon:foundBeacon];
// } else {
// for (CLBeacon *savedBeacon in _alreadyCheckedBeacon) {
// if (![savedBeacon.proximityUUID.UUIDString isEqualToString:foundBeacon.proximityUUID.UUIDString] &&
// savedBeacon.major != foundBeacon.major && savedBeacon.minor != foundBeacon.minor && (getTickCount() - currentTime >= 6000)) {
//
// [_alreadyCheckedBeacon addObject:foundBeacon];
// NSLog(@"found beacons count %lu", (unsigned long)_alreadyCheckedBeacon.count);
// [self getDateFromBeacon:foundBeacon];
// }
// }
// }
//
// }
//}
//
//
//
//-(void)getDateFromBeacon:(CLBeacon *)beacon {
//
//
// NSString *uuid = beacon.proximityUUID.UUIDString;
// NSString *major = [NSString stringWithFormat:@"%@", beacon.major];
// NSString *minor = [NSString stringWithFormat:@"%@", beacon.minor];
//
// NSLog(@"beacon's uuid %@", beacon.proximityUUID.UUIDString);
// NSLog(@"saved beacons in array %@", _alreadyCheckedBeacon);
// NSLog(@"time difference %llu", getTickCount() - currentTime);
//
// currentTime = (NSInteger)getTickCount();
//
// NSDictionary *postDictionary = @{@"beacon":@{@"data":@[@{@"uuid":uuid, @"major":major, @"minor": minor, @"distance":@(beacon.accuracy)}], @"action": @"beacon"}};
// NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:0 error:NULL];
//
//
// [[Warply sharedService] sendContext:jsonData successBlock:^(NSDictionary *contextResponse) {
//
// NSLog(@"beacon response %@", contextResponse);
// if ([[contextResponse valueForKey:@"MAPP_BEACON-status"] integerValue] == 1 && [contextResponse[@"MAPP_BEACON"] isKindOfClass:[NSArray class]]) {
// [self sendLocalNotificationWithMessage:contextResponse];
// }
//
//
// } failureBlock:^(NSError *error) {
// NSLog(@"Beacon error %@", error);
// }];
//}
//
//
//-(void)sendLocalNotificationWithMessage:(NSDictionary*)message {
//
// if (message != nil) {
//
// self.pendingItem = [[WLBaseItem alloc] initWithAttributes:message[@"MAPP_BEACON"][0]];
//
// UIApplicationState state = [[UIApplication sharedApplication] applicationState];
// if (state == UIApplicationStateActive)
// {
// UIAlertView *alert = [[UIAlertView alloc] init];
// [alert setTitle:message[@"MAPP_BEACON"][0][@"message"]];
// [alert addButtonWithTitle:NSLocalizedString(@"Close", @"Warply")];
// [alert addButtonWithTitle:NSLocalizedString(@"View", @"Warply")];
// [alert setDelegate:self];
// [alert show];
//
// }else{
// UILocalNotification *notification = [[UILocalNotification alloc] init];
// notification.alertBody = message[@"MAPP_BEACON"][0][@"message"];
// notification.userInfo = @{@"test": @"value"};
// [[UIApplication sharedApplication] scheduleLocalNotification:notification];
// }
// }
//}
//
//uint64_t getTickCount(void)
//{
// static mach_timebase_info_data_t sTimebaseInfo;
// uint64_t machTime = mach_absolute_time();
// NSLog(@"mach time: %llu", machTime);
// // Convert to nanoseconds - if this is the first time we've run, get the timebase.
// if (sTimebaseInfo.denom == 0 )
// {
// (void) mach_timebase_info(&sTimebaseInfo);
// }
//
// // Convert the mach time to milliseconds
// uint64_t millis = ((machTime / 1000000) * sTimebaseInfo.numer) / sTimebaseInfo.denom;
// return millis;
//}
//
//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
// if (buttonIndex == 1) {
// [WLAnalyticsManager logUserEngagedPush:self.pendingItem];
// if (self.pendingItem == nil)
// return;
//
// WLInboxItem *inboxItem = [[WLInboxItem alloc] initWithItem:self.pendingItem];
// [WLBeaconManager showItem:inboxItem];
// self.pendingItem = nil;
// }
//}
//
//+ (void)showItem:(WLInboxItem*)item
//{
// WLInboxItemViewController *itemViewController = [[WLInboxItemViewController alloc] initWithItem:item];
//
// UINavigationController *newModalController = [[UINavigationController alloc] initWithRootViewController:itemViewController];
//
// newModalController.navigationBarHidden = YES;
// newModalController.toolbarHidden = NO;
//
// UIViewController *existingModalController = [[UIApplication sharedApplication].delegate.window.rootViewController topModalViewController];
//
// if (existingModalController == nil) {
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"WL_Warning" message:@"You have to set the mainWindow.rootViewController in order for offer views to be presented properly." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
// [alert show];
//
// return;
// }
//
// [existingModalController presentViewController:newModalController animated:YES completion:nil];
//}
//
//@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLLocationManager.h
The Location Manager provides a functional interface to the Core Location.
Use the methods declared here to start and stop report location manually or
automatically during app lifecycle.
@copyright Warply Inc.
*/
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
@protocol WLLocationManagerDelegate;
/*!
@typedef WLLocationForegroundMode
@abstract The modes of location monitoring. These correspond to the modes of the CLLocationManager.
@field WLLocationForegroundModeOff The application does not send the server it's location.
@field WLLocationForegroundModeSignificant The application sends the device's location only on significant location changes.
@field WLLocationForegroundModeStandard The application sends the device's location at times/distances defined by the corresponding parameters.
*/
typedef enum WLLocationForegroundMode : unsigned int{
WLLocationModeOff = 0,
WLLocationModeSignificant,
WLLocationModeStandard
}WLLocationForegroundMode;
/*!
@class WLLocationManager
@discussion This manager handles the geo-location functionality of Warply service.
*/
@interface WLLocationManager : NSObject <CLLocationManagerDelegate>
/*!
@property locationManager
@abstract A CLLocationManager.
*/
@property (nonatomic, strong) CLLocationManager *locationManager;
/*!
@property locationManagerDelegate
@abstract The locationManager's delegate.
*/
@property (nonatomic, weak) NSObject <WLLocationManagerDelegate>*locationManagerDelegate;
/*!
@property foregroundMode
@abstract The mode of location monitoring while the app is on the foreground.
*/
@property (nonatomic) WLLocationForegroundMode foregroundMode;
/*!
@property backgroundMode
@abstract The mode of location monitoring while the app is on the background or not running.
*/
@property (nonatomic) WLLocationForegroundMode backgroundMode;
/*!
@property geofencingEnabled
@abstract A flag that defines if ios geofencing is being used (in conjunction with backgroundMode and/or foregroundMode) in order to provide user location tracking.
*/
@property (nonatomic) BOOL geofencingEnabled;
/*!
@methodgroup Purpose of Location Manager
*/
/*!
This method returns a string which is the Location Manager purpose.
@return Returns location manager purpose.
*/
- (NSString *)purpose;
/*!
This method sets Location Manager purpose.
@param purpose A string object with purpose of Location Manager.
*/
- (void)setPurpose:(NSString*)purpose;
/*!
@methodgroup Managing Location Reporting
*/
/*!
@methodgroup Managing AppLifecycle Location Reporting
@description These methods are called during the AppLifecycle.
*/
/*!
This method starts location reporting. It is called when application becomes
active.
*/
- (void)applicationDidBecomeActive;
- (void)sendLocation:(CLLocation *)location;
/*!
This method stops location reporting. It is called when application enters
background.
*/
- (void)applicationDidEnterBackground;
@end
@protocol WLLocationManagerDelegate <NSObject>
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation;
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region;
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "WLLocationManager.h"
#import "WLGlobals.h"
#import "WLEvent.h"
#import "Warply.h"
#include <math.h>
#define kGeofencingRadious 300
#define WLDefaultDistanceFilter 200
@interface WLLocationManager()
{
BOOL even;
double speed;
}
@end
@implementation WLLocationManager
@synthesize locationManager = _locationManager;
#pragma mark - Initialization
///////////////////////////////////////////////////////////////////////////////
- (id)init
{
self = [super init];
if (self) {
// By default we assume that the app will not go to the foreground and initialize the location manager with background values. If it becomes active we will reset those values in the applicationDidBecomeActive method
// initialize locationManager
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
[self.locationManager requestAlwaysAuthorization];
}
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:WL_IOS_LOCATION_FOREGROUND_MODE] != nil) {
// if the setting has already been set in the past, use this value
_foregroundMode = (int)[defaults integerForKey:WL_IOS_LOCATION_FOREGROUND_MODE];
}
else {
//otherwise use the default value
_foregroundMode = WLLocationModeOff;
}
if ([defaults objectForKey:WL_IOS_LOCATION_BACKGROUND_MODE] != nil) {
// if the setting has already been set in the past, use this value
_backgroundMode = (int)[defaults integerForKey:WL_IOS_LOCATION_BACKGROUND_MODE];
}
else {
//otherwise use the default value
_backgroundMode = WLLocationModeOff;
}
if ([defaults objectForKey:WL_IOS_GEOFENCING_ENABLED] != nil) {
// if the setting has already been set in the past, use this value
_geofencingEnabled = [defaults boolForKey:WL_IOS_GEOFENCING_ENABLED];
}
else {
//otherwise use the default value
_geofencingEnabled = NO;
}
if ([defaults objectForKey:WL_IOS_FOREGROUND_DISTANCE_FILTER] != nil) {
// if the setting has already been set in the past, use this value
_locationManager.distanceFilter = [defaults doubleForKey:WL_IOS_BACKGROUND_DISTANCE_FILTER];
}
else {
//otherwise use the default value
_locationManager.distanceFilter = WLDefaultDistanceFilter;
}
if ([defaults objectForKey:WL_IOS_LOCATION_BACKGROUND_DESIRED_ACCURACY] != nil) {
// if the setting has already been set in the past, use this value
_locationManager.desiredAccuracy = [defaults doubleForKey:WL_IOS_LOCATION_BACKGROUND_DESIRED_ACCURACY];
}
switch (self.backgroundMode) {
case WLLocationModeSignificant:
[_locationManager startMonitoringSignificantLocationChanges];
break;
case WLLocationModeStandard:
[_locationManager startUpdatingLocation];
break;
default:
break;
}
}
return self;
}
#pragma mark - Properties
///////////////////////////////////////////////////////////////////////////////
- (NSString*)purpose
{
if ([_locationManager respondsToSelector:@selector(purpose)]) {
return [_locationManager performSelector:@selector(purpose)];
}
return nil;
}
///////////////////////////////////////////////////////////////////////////////
- (void)setPurpose:(NSString *)purpose
{
if ((purpose != (NSString *)[NSNull null]) && (purpose.length > 0))
[_locationManager performSelector:@selector(setPurpose:) withObject:purpose];
}
#pragma mark - Application Lifecycle
///////////////////////////////////////////////////////////////////////////////
- (void)applicationDidBecomeActive
{
// When initializing we use WL_IOS_BACKGROUND_DISTANCE_FILTER and if the app becomes active we reset distanceFilter to WL_IOS_FOREGROUND_DISTANCE_FILTER
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
_locationManager.distanceFilter = [defaults doubleForKey:WL_IOS_FOREGROUND_DISTANCE_FILTER];
_locationManager.desiredAccuracy = [defaults doubleForKey:WL_IOS_LOCATION_FOREGROUND_DESIRED_ACCURACY];
switch (_foregroundMode) {
case WLLocationModeOff:
[_locationManager stopUpdatingLocation];
[_locationManager stopMonitoringSignificantLocationChanges];
break;
case WLLocationModeSignificant:
[_locationManager startMonitoringSignificantLocationChanges];
[_locationManager stopUpdatingLocation];
break;
case WLLocationModeStandard:
[_locationManager startUpdatingLocation];
[_locationManager stopMonitoringSignificantLocationChanges];
[self removeGeofences];
}
if (self.geofencingEnabled) {
[self sendLocation:_locationManager.location];
}
else [self removeGeofences];
}
///////////////////////////////////////////////////////////////////////////////
- (void)applicationDidEnterBackground
{
if (self.geofencingEnabled) {
[self sendLocation:_locationManager.location];
}
else {
[self removeGeofences];
}
switch (_backgroundMode) {
case WLLocationModeOff:
[_locationManager stopUpdatingLocation];
[_locationManager stopMonitoringSignificantLocationChanges];
break;
case WLLocationModeSignificant:
[_locationManager startMonitoringSignificantLocationChanges];
[_locationManager stopUpdatingLocation];
break;
case WLLocationModeStandard:
[_locationManager startUpdatingLocation];
_locationManager.distanceFilter = [[NSUserDefaults standardUserDefaults] doubleForKey:@"IOS_BACKGROUND_DISTANCE_FILTER"];
[_locationManager stopMonitoringSignificantLocationChanges];
[self removeGeofences];
}
}
#pragma mark - Private Methods
///////////////////////////////////////////////////////////////////////////////
- (void)sendLocation:(CLLocation *)location
{
if (location == nil) {
return;
}
if ([[NSUserDefaults standardUserDefaults] objectForKey:GEOFENCING_POIS_ENABLED] != nil) {
if ([[NSUserDefaults standardUserDefaults] boolForKey:GEOFENCING_POIS_ENABLED]) {
if (![[Warply sharedService] checkIfUserLoactionIsInPois:location])
return;
}
}
NSDictionary *geofencing = [NSDictionary dictionaryWithObjectsAndKeys:@"tracking", @"action",
[NSNumber numberWithDouble:location.coordinate.latitude], @"lat",
[NSNumber numberWithDouble:location.coordinate.longitude], @"lon",
nil];
NSDictionary *context = [NSDictionary dictionaryWithObject:geofencing forKey:@"geofencing"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:context options:0 error:NULL];
[[Warply sharedService] sendContext:jsonData successBlock:^(NSDictionary *context) {
NSArray *regionsDicts = [context valueForKey:@"MAPP_GEOFENCING"];
if (![self canUseLocation] || regionsDicts.count == 0 || _geofencingEnabled == NO)
return;
NSMutableArray *regions = [NSMutableArray array];
[self removeGeofences];
for (NSDictionary *regionDict in regionsDicts) {
CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:CLLocationCoordinate2DMake([[regionDict valueForKey:@"lat"] doubleValue], [[regionDict valueForKey:@"lon"] doubleValue])
radius:fmin(_locationManager.maximumRegionMonitoringDistance, [[regionDict valueForKey:@"radius"] doubleValue])
identifier:[regionDict valueForKey:@"name"]];
[_locationManager startMonitoringForRegion:region];
[regions addObject:region];
}
} failureBlock:nil];
}
#pragma mark - CLLocationManagerDelegate
///////////////////////////////////////////////////////////////////////////////
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status) {
case kCLAuthorizationStatusAuthorizedAlways:
break;
case kCLAuthorizationStatusNotDetermined:
break;
case kCLAuthorizationStatusDenied:
break;
case kCLAuthorizationStatusRestricted:
break;
default:
break;
}
}
///////////////////////////////////////////////////////////////////////////////
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error { }
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if (CLLocationCoordinate2DIsValid(newLocation.coordinate) == NO)
return;
// test the age of the location measurement to determine if the measurement is cached
// in most cases you will not want to rely on cached measurements
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5.0) return;
speed = newLocation.speed;
if (self.locationManagerDelegate != nil && [self.locationManagerDelegate respondsToSelector:@selector(locationManager:didUpdateToLocation:fromLocation:)]) {
NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(locationManager:didUpdateToLocation:fromLocation:)];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sgn];
[invocation setTarget:self.locationManagerDelegate];
[invocation setSelector:@selector(locationManager:didUpdateToLocation:fromLocation:)];
[invocation setArgument:&manager atIndex:2];
[invocation setArgument:&newLocation atIndex:3];
[invocation setArgument:&oldLocation atIndex:4];
[invocation invoke];
}
[self sendLocation:newLocation];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDate *lastFeaturesUpdate = [defaults objectForKey:@"lastFeaturesUpdateTimestamp"];
if ([[NSDate date] timeIntervalSinceDate:lastFeaturesUpdate] > [[defaults valueForKey:@"FEATURES_CHECK_INTERVAL"] intValue]) {
[[Warply sharedService] getAppSettingsWithSuccessBlock:nil failureBlock:nil];
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
[self.locationManagerDelegate locationManager:manager didEnterRegion:region];
[self sendLocation:[[CLLocation alloc] initWithLatitude:((CLCircularRegion *)region).center.latitude longitude:((CLCircularRegion *)region).center.longitude]];
}
- (void)locationManager:(CLLocationManager *)manager monitoringDidFailForRegion:(CLRegion *)region withError:(NSError *)error
{
WLLOG(@"geofencing error: %@", error.localizedDescription);
}
- (void)removeGeofences
{
for (CLRegion *region in _locationManager.monitoredRegions) {
[_locationManager stopMonitoringForRegion:region];
}
}
- (BOOL) canUseLocation{
CLAuthorizationStatus authStatus = [CLLocationManager authorizationStatus];
if([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
{
if ([CLLocationManager locationServicesEnabled] &&
((authStatus == kCLAuthorizationStatusAuthorizedAlways) ||
(authStatus == kCLAuthorizationStatusAuthorizedWhenInUse) ||
((authStatus == kCLAuthorizationStatusNotDetermined))))
return YES;
return NO;
}
if ([CLLocationManager locationServicesEnabled] && [self canUseLocation])
return YES;
return NO;
}
#pragma mark - Memory Management
///////////////////////////////////////////////////////////////////////////////
- (void)dealloc
{
_locationManager.delegate = nil;
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLPushManager.h
The Push Manager provides a functional interface for handling push notifications.
@copyright Warply Inc.
*/
@import UIKit;
#import <Foundation/Foundation.h>
#import "WLBaseItem.h"
#import "WLInboxItem.h"
#import <UserNotifications/UserNotifications.h>
@class Warply;
@protocol WLCustomPushHandler;
/*!
@typedef WLApplicationState
@abstract States in which the app can receive a remote push notification.
@field WLApplicationStateActive The application is running in the foreground and currently receiving events.
@field WLApplicationStateClosed The application is closed.
@field WLApplicationStateBackground The application is running in the background.
*/
typedef enum WLApplicationState : unsigned int{
WLApplicationStateActive,
WLApplicationStateClosed,
WLApplicationStateBackground
}WLApplicationState;
/*!
@class WLUserManager
@discussion This manager handles the Remote Notifications (Push) functionality
of Warply service.By default it displays remote notifications that have action == 0 by displaying the rich push content in a webview. You can chοose to handle push notifications in a custom manner. To do this, send a remote notification with action != 0 from the Warply server and set the @link //apple_ref/occ/instp/Warply/customPushHanlder customPushHandler @/link property with your custom object that conforms to the @link //apple_ref/occ/instp/Warply/WLCustomPushHandler WLCustomPushHandler @/link protocol.
*/
@interface WLPushManager : NSObject <UNUserNotificationCenterDelegate>
{
//Settings
NSString *_deviceToken;
}
/*!
@property hasSentDeviceInfo.
@abstract Returns YES if the device info/application data has been sent during this session.
*/
@property (nonatomic) BOOL hasSentDeviceInfo;
/*!
@property isMissingDeviceInfo.
@abstract Returns YES if the device info/application data has been sent during this session.
*/
@property (nonatomic) BOOL isMissingDeviceInfo;
/*!
@property deviceToken
@abstract The device token property.
*/
@property (nonatomic, readonly) NSString *deviceToken;
/*!
@property notificationTypes
@abstract A UIRemoteNotificationType property.
*/
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
@property (nonatomic, readonly) UIRemoteNotificationType notificationTypes;
#pragma clang diagnostic pop
@property (nonatomic, readonly) UNAuthorizationOptions notificationOptions;
/*!
@property pendingItem
@abstract The remote notification as a WLBaseItem currently stored for later use.
*/
@property (nonatomic, strong) WLBaseItem *pendingItem;
/*!
@property customPushHanlder
@abstract A WLConsumer Manager for handling user name,e-mail and MSISDN.
@discussion If set, this object receives a didReceiveRemoteNotification:whileAppWasInState: message when the app receives a remote notification with action != 0. If action == 0 the default push manager handles the notification by presenting the warply rich offer in a webview.
*/
@property (nonatomic, weak) id <WLCustomPushHandler> customPushHanlder;
/*!
@methodgroup Registering for Remote Notifications
*/
/*!
@abstract Types of Remote Notification.
@discussion This method informs the Warply service for which kind of notification
type the applications need to receive (ex. sound or bagde only etc).
@param types One or many UIRemoteNotificationType
@deprecated This method has been deprecated. Use registerForRemoteNotifications instead.
*/
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (void)registerForRemoteNotificationTypes:(UIRemoteNotificationType)types;
#pragma clang diagnostic pop
/*!
@discussion This method informs the Warply service for which kind of notification
type the applications need to receive (ex. sound or bagde only etc).
*/
- (void)registerForRemoteNotifications;
/*!
@abstract Device Registered for Remote Notifications.
@discussion This method notifies that the device is registered successfully with
APNS for Remote Notifications and sends its token to Warply service.
@param deviceToken The device informations in NSData format.
*/
- (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken;
/*!
@abstract Device Failed to Registered for Remote Notifications.
@discussion This method notifies that the device failed to register with APNS
for Remote Notifications and sends its token to Warply service.
@param error An NSError object that encapsulates information why registration did not succeed.
*/
- (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)error;
/*!
@methodgroup Mananging Received Pushes
*/
/*!
@abstract Application Launched due to a Remote Notification.
@discussion This method notifies the WLPushManager that application was launched
and the pass the launch options.
@param launchOptions A dictionary with the application launch options. May be
empty if application launched by user.
*/
- (void)didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
/*!
@abstract Application Received a Remote Notification
@discussion If the application is running and receives a remote notification, this method is called to process the remote notification.
@param userInfo A dictionary that contains information related to the remote notification, including a badge number for the application icon, an alert sound, an alert message to display to the user, a notification identifier, and custom data.
@param state the state that the app was in at the time it received the push notification.
@discussion The default implementation is intented to handle warply rich push offers. That is remote push notifications that "carry" the information of an offer url (@link //apple_ref/occ/instp/WLBaseItem/session_uuid session_uuid @/link) If the notification is received when the app is closed and the user taps on the alert displayed by the iOS, the app launches and warply calls the push manager's didReceiveRemoteNotification:whileAppWasInState: method which saves the payload as a pending item to be handled later, when the root view controller's view appears by using the @link //apple_ref/occ/instp/WLPushManager/handlePendingNotification handlePendingNotification @/link method. If the notification is received when the app is in the background and the user taps on the alert on the alert displayed by the iOS , the app launches and warply calls the push manager's didReceiveRemoteNotification:whileAppWasInState: which displays the offer using the @link //apple_ref/occ/instp/WLPushManager/showItem: showItem: @/link method. If the notification is received when the app is in the foreground, no alert is being displayed by the iOS. didReceiveRemoteNotification:whileAppWasInState: displays an alert to inform the user that he has a pending remote notification and to ask if he wants to see it or ignore it.
*/
- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo whileAppWasInState:(WLApplicationState)state;
/*!
@abstract Application received a Remote Notification.
@discussion This method notifies the WLPushManager that a remote notification was received and passes the data to the didReceiveRemoteNotification:whileAppWasInState: method
@param userInfo The NSDictionary data that contains the remote notification that was received.
*/
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo;
/*!
@methodgroup Mananging Notifications Badge
*/
/*!
@abstract Reset notifications badge.
@discussion This method resets the notification badge to zero.
*/
- (void)resetBadge;
/*!
@methodgroup Handling Pending Notifications
*/
/*!
@abstract Handles the pending notification item if it exists.
@discussion The default implemention calls showItem: and displays modally a mini browser with the warp offer. Returns YES if a pending notification existed at the time the method was being called, otherwise returns NO.
@seealso
*/
- (BOOL)handlePendingNotification;
/*!
@abstract Displays displays modally a mini browser with the warp offer.
@param item A WLInboxItem object representation of an offer.
*/
- (void)showItem:(WLInboxItem*)item;
/*!
@methodgroup Handling Device Information
*/
/*!
@abstract Sends the application and device information.
@discussion This function is internal and only used by Warply service.
*/
- (void)sendDeviceInfoIfNecessary;
- (void)sendDeviceInfo;
- (NSDictionary *)deviceInfo;
- (NSDictionary *)applicationData;
@end
/*!
@protocol WLCustomPushHandler
@abstract If there is a need for custom push handling the user must create an option that conforms to the WLCustomPushHandler protocol and implement the didReceiveRemoteNotification:whileAppWasInState: method.
*/
/*!
@methodgroup Handling Custom Push Notifications
*/
/*!
@abstract Handles a remote notification that is not of the default warply type (action .
@discussion The default implemention calls showItem: and displays modally a mini browser with the warp offer.
@seealso
*/
@protocol WLCustomPushHandler <NSObject>
- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo whileAppWasInState:(WLApplicationState)state;
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "WLPushManager.h"
#import "WLGlobals.h"
#import "WLEvent.h"
#import "Warply.h"
#import "WLBaseItem.h"
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import "WLInboxItem.h"
#import "WLInboxItemViewController.h"
#import <AdSupport/AdSupport.h>
#import "WLUtils.h"
#import "UIViewController+WLAdditions.h"
///////////////////////////////////////////////////////////////////////////////
@interface WLPushManager()
{
//Push
NSMutableDictionary *_actionHandlerDict;
}
@property (nonatomic) BOOL apsRegistrationError;
- (BOOL)isJailBroken;
@end
@implementation WLPushManager
@synthesize deviceToken = _deviceToken;
@synthesize notificationTypes = _notificationTypes;
@synthesize notificationOptions = _notificationOptions;
///////////////////////////////////////////////////////////////////////////////
static const char* jailbreak_apps[] =
{
"/Applications/Cydia.app",
"/Applications/limera1n.app",
"/Applications/greenpois0n.app",
"/Applications/blackra1n.app",
"/Applications/blacksn0w.app",
"/Applications/redsn0w.app",
NULL,
};
#pragma mark - Initialization
///////////////////////////////////////////////////////////////////////////////
- (id)init
{
self = [super init];
if (self) {
_actionHandlerDict = [[NSMutableDictionary alloc] init];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
_notificationTypes = UIRemoteNotificationTypeNone;
#pragma clang diagnostic pop
_apsRegistrationError = FALSE;
}
return self;
}
#pragma mark - Properties
///////////////////////////////////////////////////////////////////////////////
- (void)setDeviceToken:(NSString *)aDeviceToken
{
if ([_deviceToken isEqualToString:aDeviceToken] == YES)
return;
_deviceToken = [aDeviceToken copy];
//Save new valuetodo
if ((_deviceToken != (NSString *)[NSNull null]) && (_deviceToken.length > 0))
[WLKeychain setString:_deviceToken forKey:@"NBDeviceToken"];
else
[WLKeychain deleteStringForKey:@"NBDeviceToken"];
}
#pragma mark - Public Methods
///////////////////////////////////////////////////////////////////////////////
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (void)registerForRemoteNotificationTypes:(UIRemoteNotificationType)types
{
if (!SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
_notificationTypes = types;
if ([[UIApplication sharedApplication] respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
{
// iOS 8 Notifications
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:_notificationTypes];
#pragma clang diagnostic pop
}
}
}
#pragma clang diagnostic pop
//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
NSLog(@"User Info : %@",notification.request.content.userInfo);
WLApplicationState warplyAppState;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
warplyAppState = WLApplicationStateActive;
[self didReceiveRemoteNotification:notification.request.content.userInfo whileAppWasInState:warplyAppState];
} else {
completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
}
}
//Called to let your app know which action was selected by the user for a given notification.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
NSString *category = response.notification.request.content.userInfo[@"aps"][@"category"];
if (category != [NSNull null] && [category isEqualToString:@"shareCategory"]) {
if ([response.actionIdentifier isEqualToString:@"share_identifier"]) {
NSString *title = response.notification.request.content.userInfo[@"data"][@"text"];
NSString *url = response.notification.request.content.userInfo[@"data"][@"url"];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"SharedCategory"];
[[NSUserDefaults standardUserDefaults] setObject:title forKey:@"SharedTitle"];
[[NSUserDefaults standardUserDefaults] setObject:url forKey:@"SharedUrl"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
} else if (category != [NSNull null] && [category isEqualToString:@"favoriteCategory"]) {
if ([response.actionIdentifier isEqualToString:@"favorite_identifier"]) {
NSLog(@"favorite_identifier");
}
} else if (category != [NSNull null] && [category isEqualToString:@"bookCategory"]) {
if ([response.actionIdentifier isEqualToString:@"book_identifier"]) {
NSString *bookID = response.notification.request.content.userInfo[@"data"][@"id"];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"BookCategory"];
[[NSUserDefaults standardUserDefaults] setObject:bookID forKey:@"BookID"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
[[NSNotificationCenter defaultCenter] postNotificationName:@"DidReceiveNotificaitonWithAction" object:nil];
WLApplicationState warplyAppState;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
warplyAppState = WLApplicationStateActive;
else
warplyAppState = WLApplicationStateBackground;
[self didReceiveRemoteNotification:response.notification.request.content.userInfo whileAppWasInState:warplyAppState];
completionHandler();
}
- (void)registerForRemoteNotifications{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
_notificationOptions = UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge;
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
if(!error){
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
}];
} else {
if ([[UIApplication sharedApplication] respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
{
// iOS 8 Notifications
_notificationTypes = UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge;
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
else
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
_notificationTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert;
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:_notificationTypes];
#pragma clang diagnostic pop
}
}
}
///////////////////////////////////////////////////////////////////////////////
- (void)didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
WLLOG(@"LAUNCH OPTIONS: %@", launchOptions);
NSDictionary *payload = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (payload == nil)
return;
if ([payload valueForKey:@"_a"] == nil) {
// The push was sent from another push service
return;
}
[self didReceiveRemoteNotification:payload whileAppWasInState:WLApplicationStateClosed];
}
///////////////////////////////////////////////////////////////////////////////
- (void)didReceiveRemoteNotification:(NSDictionary *)userInfo whileAppWasInState:(WLApplicationState)state
{
if ([userInfo valueForKey:@"_a"] == nil) {
// The push was sent from another push service
return;
}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:userInfo options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
WLLOG(@"Did receive push: %@", jsonString);
WLInboxItem *inboxItem = [[WLInboxItem alloc] initWithAttributes:userInfo] ;
// [WLAnalyticsManager logUserReceivedPush:inboxItem];
if (state != WLApplicationStateActive) {
[WLAnalyticsManager logUserEngagedPush:inboxItem];
}
if (inboxItem.action != 0) {
[self.customPushHanlder didReceiveRemoteNotification:userInfo whileAppWasInState:state];
return;
}
switch (state) {
case WLApplicationStateActive:
{
UIAlertView *alert = [[UIAlertView alloc] init];
[alert setTitle:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]];
[alert addButtonWithTitle:NSLocalizedString(@"Close", @"Warply")];
[alert addButtonWithTitle:NSLocalizedString(@"View", @"Warply")];
[alert setDelegate:self];
[alert show];
self.pendingItem = inboxItem;
break;
}
case WLApplicationStateBackground:
{
[self showItem:inboxItem];
break;
}
case WLApplicationStateClosed:
self.pendingItem = inboxItem;
break;
}
}
///////////////////////////////////////////////////////////////////////////////
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
WLApplicationState warplyAppState;
if (application.applicationState == UIApplicationStateActive)
warplyAppState = WLApplicationStateActive;
else
warplyAppState = WLApplicationStateBackground;
[self didReceiveRemoteNotification:userInfo whileAppWasInState:warplyAppState];
}
///////////////////////////////////////////////////////////////////////////////
- (void)didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
WLLOG(@"DEVICE TOKEN: %@", deviceToken);
if (SYSTEM_VERSION_LESS_THAN(@"13.0")) {
self.deviceToken = [[[deviceToken.description stringByReplacingOccurrencesOfString:@"<" withString:@""]
stringByReplacingOccurrencesOfString:@">" withString:@""]
stringByReplacingOccurrencesOfString:@" " withString:@""];
} else {
NSUInteger dataLength = deviceToken.length;
const unsigned char *dataBuffer = (const unsigned char *)deviceToken.bytes;
NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (NSInteger index = 0; index < dataLength; ++index) {
[hexString appendFormat:@"%02x", dataBuffer[index]];
}
self.deviceToken = [hexString copy];
}
[self sendDeviceInfoIfNecessary];
}
///////////////////////////////////////////////////////////////////////////////
- (void)didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
WLLOG(@"DEVICE TOKEN: FAILED. Error:%@", [error localizedDescription]);
self.deviceToken = nil;
if (error.code == 3000 || error.code == 3010)
self.apsRegistrationError = TRUE;
[self sendDeviceInfoIfNecessary];
}
///////////////////////////////////////////////////////////////////////////////
- (void)resetBadge
{
UIApplication *application = [UIApplication sharedApplication];
[application setApplicationIconBadgeNumber:1];
[application setApplicationIconBadgeNumber:0];
}
///////////////////////////////////////////////////////////////////////////////
- (BOOL)handlePendingNotification
{
if (self.pendingItem == nil)
return NO;
// make sure you call this in your handler to let the server know the user
// engaged with your notification
WLInboxItem *inboxItem = [[WLInboxItem alloc] initWithItem:self.pendingItem];
[self showItem:inboxItem];
self.pendingItem = nil;
return YES;
}
///////////////////////////////////////////////////////////////////////////////
- (void)sendDeviceInfoIfNecessary
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults boolForKey:@"NBAPPUuidChanged"] == YES) {
[defaults removeObjectForKey:@"device_info"];
[defaults removeObjectForKey:WL_APPLICATION_DATA];
[defaults synchronize];
}
NSDictionary *oldDeviceInfo = [defaults objectForKey:@"device_info"];
BOOL device_info_has_changed = ![[self deviceInfo] isEqualToDictionary:oldDeviceInfo];
NSDictionary *oldApplicationData = [defaults objectForKey:WL_APPLICATION_DATA];
BOOL application_data_has_changed = ![[self applicationData] isEqualToDictionary:oldApplicationData];
if (device_info_has_changed || application_data_has_changed || _isMissingDeviceInfo) {
[self sendDeviceInfo];
}
}
///////////////////////////////////////////////////////////////////////////////
- (void)sendDeviceInfo
{
WLEventSimple *deviceInfoEvent = [[WLEventSimple alloc] initWithType:@"device_info" andContext:[NSDictionary dictionaryWithObject:[self deviceInfo] forKey:@"device_info"]];
[[Warply sharedService] addEvent:(WLEvent*)deviceInfoEvent priority:NO];
WLEventSimple *applicationDataEvent = [[WLEventSimple alloc] initWithType:WL_APPLICATION_DATA andContext:[NSDictionary dictionaryWithObject:[self applicationData] forKey:WL_APPLICATION_DATA]];
[[Warply sharedService] addEvent:(WLEvent*)applicationDataEvent priority:NO];
_hasSentDeviceInfo = YES;
_isMissingDeviceInfo = NO;
[[Warply sharedService] sendAllEventsWithCompletionBlock:^{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[self applicationData] forKey:WL_APPLICATION_DATA];
[defaults setObject:[self deviceInfo] forKey:@"device_info"];
[defaults synchronize];
} failureBlock:nil];
}
///////////////////////////////////////////////////////////////////////////////
- (void)showItem:(WLInboxItem*)item
{
WLInboxItemViewController *itemViewController = [[WLInboxItemViewController alloc] initWithItem:item];
UINavigationController *newModalController = [[UINavigationController alloc] initWithRootViewController:itemViewController];
newModalController.navigationBarHidden = YES;
newModalController.toolbarHidden = NO;
UIViewController *existingModalController = [[UIApplication sharedApplication].delegate.window.rootViewController topModalViewController];
if (existingModalController == nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"WL_Warning" message:@"You have to set the mainWindow.rootViewController in order for offer views to be presented properly." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
return;
}
[existingModalController presentViewController:newModalController animated:YES completion:nil];
}
///////////////////////////////////////////////////////////////////////////////
- (NSDictionary *)deviceInfo
{
CTTelephonyNetworkInfo *telephony = [[CTTelephonyNetworkInfo alloc] init];
CTCarrier *carrier = telephony.subscriberCellularProvider;
NSArray *prefLangs = [NSLocale preferredLanguages];
NSUInteger count = [prefLangs count];
NSString *langs = [NSString stringWithFormat:@"%@, %@, %@, %@, %@",
(count > 0)?[prefLangs objectAtIndex:0]:@"-",
(count > 1)?[prefLangs objectAtIndex:1]:@"-",
(count > 2)?[prefLangs objectAtIndex:2]:@"-",
(count > 3)?[prefLangs objectAtIndex:3]:@"-",
(count > 4)?[prefLangs objectAtIndex:4]:@"-"];
NSMutableDictionary *deviceInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#if (DEBUG == 1)
@"true" , @"development",
#else
@"false" , @"development",
#endif
nil];
if ([[[UIDevice currentDevice] systemName] length] != 0) {
[deviceInfo setValue:[[UIDevice currentDevice] systemName] forKey:@"ios_system_name"];
}
if ([[[UIDevice currentDevice] systemVersion] length] != 0) {
[deviceInfo setValue:[[UIDevice currentDevice] systemVersion] forKey:@"ios_system_version"];
}
if ([[[UIDevice currentDevice] platformString] length] != 0) {
[deviceInfo setValue:[[UIDevice currentDevice] platformString] forKey:@"ios_model"];
}
if ([[UIDevice currentDevice] platform].length != 0) {
[deviceInfo setValue:[[UIDevice currentDevice] platform] forKey:@"ios_device_model"];
}
if ([[UIDevice currentDevice] deviceFamilyString].length != 0) {
[deviceInfo setValue:[[UIDevice currentDevice] deviceFamilyString] forKey:@"device_family"];
}
if (carrier.carrierName.length != 0) {
[deviceInfo setValue:carrier.carrierName forKey:@"carrier_name"];
}
if (carrier.isoCountryCode.length != 0) {
[deviceInfo setValue:carrier.isoCountryCode forKey:@"ios_iso_country_code"];
}
if ([[[UIDevice currentDevice] localizedModel] length] != 0) {
[deviceInfo setValue:[[UIDevice currentDevice] localizedModel] forKey:@"ios_localized_model"];
}
if ([[[NSLocale currentLocale] localeIdentifier] length] != 0) {
[deviceInfo setValue:[[NSLocale currentLocale] localeIdentifier] forKey:@"ios_locale"];
}
if (langs.length != 0) {
[deviceInfo setValue:langs forKey:@"ios_languages"];
}
[deviceInfo setValue:@"apple" forKey:@"vendor"];
[deviceInfo setValue:@"ios" forKey:@"platform"];
[deviceInfo setValue:[[UIDevice currentDevice] systemVersion] forKey:@"os_version"];
[deviceInfo setValue:[[[UIDevice currentDevice] identifierForVendor] UUIDString] forKey:@"unique_device_id"];
[deviceInfo setValue:[[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString] forKey:@"advertising_id"];
[deviceInfo setValue:[NSString stringWithFormat:@"%.0fx%.0f",([UIScreen mainScreen].bounds.size.width * [[UIScreen mainScreen] scale]),([UIScreen mainScreen].bounds.size.height * [[UIScreen mainScreen] scale])] forKey:@"screen_resolution"];
#if (WARPLY_UDID_ENABLED == 1)
if ([[UIDevice currentDevice] respondsToSelector:@selector(uniqueIdentifier)]) {
[device_info setValue:[UIDevice currentDevice].uniqueIdentifier forKey:@"ios_unique_identifier"];
}
#endif
[deviceInfo setValue:[self isJailBroken]?[NSNumber numberWithBool:YES] : [NSNumber numberWithBool:NO] forKey:@"ios_is_jailbroken_phone"];
if (_deviceToken.length != 0) {
[deviceInfo setValue:_deviceToken forKey:@"device_token"];
}
[deviceInfo setValue:[NSNumber numberWithBool:!self.apsRegistrationError] forKey:@"ios_aps_entitlement_valid"];
NSUInteger rntypes;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
[deviceInfo setValue:[NSNumber numberWithInt:_notificationOptions] forKey:@"notification_types"];
} else {
[deviceInfo setValue:[NSNumber numberWithInt:_notificationTypes] forKey:@"notification_types"];
}
if (SYSTEM_VERSION_LESS_THAN(@"8.0")) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
rntypes = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
#pragma clang diagnostic pop
}else{
rntypes = [[[UIApplication sharedApplication] currentUserNotificationSettings] types];
}
[deviceInfo setValue:[NSNumber numberWithInteger:rntypes] forKey:@"user_enabled_notification_types"];
// NSMutableDictionary *apple_uuids = [NSMutableDictionary dictionaryWithCapacity:2];
[deviceInfo setValue:[NSNumber numberWithBool:[ASIdentifierManager sharedManager].advertisingTrackingEnabled] forKey:@"advertising_tracking_enabled"];
[deviceInfo setValue:[[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString] forKey:@"advertising_identifier"];
[deviceInfo setValue:[[[UIDevice currentDevice] identifierForVendor] UUIDString] forKey:@"identifier_for_vendor"];
// [deviceInfo setValue:apple_uuids forKey: @"ios_uuids"];
NSLog(@"%@", deviceInfo);
return deviceInfo;
}
///////////////////////////////////////////////////////////////////////////////
- (NSDictionary *)applicationData
{
//Application Data Hack
NSBundle *mainBundle = [NSBundle mainBundle];
NSMutableDictionary *applicationData = [NSMutableDictionary dictionaryWithCapacity:3];
if ([Warply get].length != 0) {
[applicationData setValue:[Warply get] forKey:@"sdk_version"];
}
NSString *CFBundleIdentifier = [mainBundle objectForInfoDictionaryKey:@"CFBundleIdentifier"];
if (CFBundleIdentifier.length != 0) {
[applicationData setValue:CFBundleIdentifier forKey:@"bundle_identifier"];
}
NSString *CFBundleShortVersionString = [mainBundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
if (CFBundleShortVersionString.length != 0) {
[applicationData setValue:CFBundleShortVersionString forKey:@"app_version"];
}
NSString *CFBundleVersion = [mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"];
if (CFBundleVersion.length != 0) {
[applicationData setValue:CFBundleVersion forKey:@"app_build"];
}
return applicationData;
}
#pragma mark - Private Methods
///////////////////////////////////////////////////////////////////////////////
- (BOOL)isJailBroken
{
NSDictionary *info = [[NSBundle mainBundle] infoDictionary];
// This key-value pair should not be in the pinfo file. If it is, we can be reasonably sure that the app has been compromised.
if ([info objectForKey: @"SignerIdentity"] != nil)
return YES;
// Now check for known jailbreak apps. If we encounter one, the device is jailbroken.
for (int i = 0; jailbreak_apps[i] != NULL; ++i)
{
if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithUTF8String:jailbreak_apps[i]]])
return YES;
}
return NO;
}
#pragma mark - UIAlertViewDelegate
///////////////////////////////////////////////////////////////////////////////
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1) {
[WLAnalyticsManager logUserEngagedPush:self.pendingItem];
[self handlePendingNotification];
}
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLUserManager.h
The ConsumerData Manager provides a functional interface for user related data.
Use the methods declared here to get and send user name,email and MSISDN, add tags and connect your CRM id to our data.
@copyright Warply Inc.
*/
#import <Foundation/Foundation.h>
#import "Warply.h"
/*!
@class WLUserManager
@discussion This manager enables the device and Warply server to exchange info about the user.
*/
@interface WLUserManager : NSObject
/*!
@methodgroup Sending User Data
@discusion These methods send user related data to the warply server. The users can then be targeted based on the values of the corresponding user related keys. There are some common data fields supported (email, msisdn, name) but you can also send custom data if the abeforementioned fields do not fit your needs.
*/
/*!
@abstract Send user name.
@discussion This class method send user name to Warply service.
@param userName A string object with user name.
*/
+ (void)sendName:(NSString *)userName;
/*!
@abstract Send user e-mail.
@discussion This class method send user e-mail to Warply service. Also, make sure
that e-mail is correct format prior sending it.
@param userEmail A string object with user e-mail.
*/
+ (void)sendEmail:(NSString *)userEmail;
/*!
@abstract Send user MSISDN.
@discussion This class method send user MSISDN to Warply service.
@param userMsisdn A string object with user msisdn.
*/
+ (void)sendMsisdn:(NSString *)userMsisdn;
/*!
@abstract Sends a dictionary to warply containing data related to the user.
@discussion Use this method if you want to send info about the users (in order to target them by warply)that is not one of the predefined fields (email, name, msisdn).
@param customData A dictionary containing custom user data.
*/
+ (void)sendCustomData:(NSDictionary *)customData;
/*!
@methodgroup Getting User Data
*/
/*!
@abstract Get user name.
@discussion This class method gets user name from Warply service.
@attributeblock sucessBlock This block is called when getUserName is sucessful and returns a NSString with the user name or null if user name doesn't exists.
@attributeblock failureBlock This block is called when getUserName fails and returns a NSError object with failure code and description.
*/
+ (void)getNameWithSuccessBlock:(void (^)(NSString *userName))success failureBlock:(void (^)(NSError *error))failure;
/*!
@abstract Get user e-mail.
@discussion This class method gets user e-mail from Warply service.
@attributeblock sucessBlock This block is called when getUserEmail is sucessful and returns a NSString with the user e-mail or null if user e-mail doesn't exists.
@attributeblock failureBlock This block is called when getUserEmail fails and returns a NSError object with failure code and description.
*/
+ (void)getEmailWithSuccessBlock:(void (^)(NSString *userEmail))success failureBlock:(void (^)(NSError *error))failure;
/*!
@abstract Get user MSISDN.
@discussion This class method gets user MSISDN from Warply service.
@attributeblock sucessBlock This block is called when getUserMsisdn is sucessful and returns a NSString with the user MSISDN or null if user e-mail doesn't exists.
@attributeblock failureBlock This block is called when getUserMsisdn fails and returns a NSError object with failure code and description.
*/
+ (void)getMsisdnWithSuccessBlock:(void (^)(NSString *userMsisdn))success failureBlock:(void (^)(NSError *error))failure;
/*!
@abstract Get user custom data.
@discussion This class method gets user MSISDN from Warply service.
@attributeblock sucessBlock This block is called when the call is sucessful and returns a NSDictionary with the custom user data or null if no custom data exist.
@attributeblock failureBlock This block is called when the call fails and returns a NSError object with failure code and description.
*/
+ (void)getCustomDataWithSuccessBlock:(void (^)(NSDictionary *customData))success failureBlock:(void (^)(NSError *error))failure;
/*!
@methodgroup Sending User Advertising IDs
*/
/*!
@abstract Send user advertising ids.
@discussion This class method sends both user and vendor adverting identifiers.
These identifiers are available only when user allows ad tracking from the device
settings.
@dependency AdSupport framework (Available on iOS 6 only).
*/
+ (void)sendUUIDS;
/*!
@methodgroup Tagging Users
@discusion These methods send user related tags to the warply server. The users can then be targeted based on these tags.
*/
/*!
@abstract Adds a single user tag.
@discussion This class method sends a tag to be added in Warply service. This event
is sent immediately.
@param tag A string object with an arbitrary tag.
*/
+ (void)addTag:(NSString *)tag;
/*!
@abstract Adds an array of user tags.
@discussion This class method sends an array of tags to be added in Warply service.
This event is sent immediately.
@param tag An array of tags. Each tag must me be a string object.
*/
+ (void)addTags:(NSArray *)tags;
/*!
@abstract Removes the existing tags and adds an array of user tags.
@discussion This class method sends an array of tags to be added in Warply service and replace any existing ones.
This event is sent immediately.
@param tag An array of tags. Each tag must me be a string object.
*/
+ (void)rewriteTags:(NSArray *)tags;
/*!
@methodgroup Removing User Tags
*/
/*!
@abstract Remove a single user tag.
@discussion This class method sends a tag to be removed in Warply service. This event
is sent immediately.
@param tag An string object with an arbitrary tag.
*/
+ (void)removeTag:(NSString *)tag;
/*!
@abstract Removes an array of user tags.
@discussion This class method sends an array of tags to be removed in Warply service.
This event is sent immediately.
@param tags An array of tags. Each tag must me be a string object.
*/
+ (void)removeTags:(NSArray *)tags;
/*!
@abstract Removes all user tags.
*/
+ (void)removeAllTags;
/*!
@methodgroup Getting User Tags
*/
/*!
@abstract Get user tags.
@discussion This class method gets all the user tags from the Warply service.
@attributeblock successBlock This block is called when getTags is sucessful and returns a NSArray object with the user tags.
@attributeblock failureBlock This block is called when getTags fails and returns a NSError object that encapsulates information why registration did not succeed.
*/
+ (void)getTagsWithSuccessBlock:(void (^)(NSArray *tags))success failureBlock:(void (^)(NSError *error))failure;
/*!
@methodgroup Creating and Resuming a session
@discusion Using these methods, it is possible to register a user with a time invariant token and restore all previous user sessions. Use the methods declared here to register, login and logout user. Logging in to a previously created user session means that users are unonymously recognized by warply across all his/her devices. That way they can see all their personalized offers across all the devices on which they login.
*/
/*!
@abstract Login a user. If no user has been registered with this auth token, the user is being registered.
@discussion This class method logins a user to Warply service. The login is sucessful only if
previously the user is sucesfully registered.
@param authToken User arbitrary time invariant token. Must be the same token used
for registering the user.
@attributeblock success This block is called when sessionLogin is sucessful.
@attributeblock failure This block is called when sessionLogin fails and returns a NSError object with failure code and description.
*/
+ (void)sessionLogin:(NSString *)authToken successBlock:(void (^)(void))success failureBlock:(void (^)(void))failure;
/*!
@abstract Logout a user.
@discussion This class method logouts a user to Warply service. The logout is sucessful only if
previously the user is sucesfully registered.
@param authToken User arbitrary time invariant token. Must be the same token used
for registering the user.
@attributeblock success This block is called when sessionLogout is sucessful.
@attributeblock failure This block is called when sessionLogout fails.
*/
+ (void)sessionLogout:(NSString *)authToken successBlock:(void (^)(void))success failureBlock:(void (^)(void))failure;
/*!
@abstract Determine if the user wants to receive or not push notifications from the Warply server.
@param enable BOOL value that determines if the user wants to receive or not push notifications from the Warply server. If enable == NO the Warply server does not send any push notifications to the specific user. Default value is YES.
@attributeblock success This block is called when the call is sucessful.
@attributeblock failure This block is called when the call fails.
*/
+ (void)setWarplyNotificationsEnabled:(BOOL)enable successBlock:(void (^)(void))success failureBlock:(void (^)(NSError *error))failure;
/*!
@abstract This method retreives from the server the information of whether the user wants to receive Warply notifications or not @see + warplyNotificationsEnabledWithsuccessBlock:failureBlock:
@attributeblock success This block is called when the call is sucessful and has a BOOL parameter that carries the information of whether the user wants to receive Warply notifications or not.
@attributeblock failure This block is called when the call fails.
*/
+ (void)warplyNotificationsEnabledWithsuccessBlock:(void (^)(BOOL isEnabled))success failureBlock:(void (^)(NSError *error))failure;
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "WLUserManager.h"
#import <AdSupport/AdSupport.h>
@implementation WLUserManager
#pragma mark - User Data
///////////////////////////////////////////////////////////////////////////////
+ (void)getNameWithSuccessBlock:(void (^)(NSString *userName))success
failureBlock:(void (^)(NSError *error))failure
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CONSUMER_DATA_ENABLED)) {
return;
}
[[Warply sharedService] getContextWithPath:@"consumer_data" successBlock:^(NSDictionary *dict){
if (success)
success([dict valueForKey:@"user_name"]);
} failureBlock:^(NSError *error) {
if (failure)
failure(error);
}];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)getEmailWithSuccessBlock:(void (^)(NSString *userEmail))success
failureBlock:(void (^)(NSError *error))failure
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CONSUMER_DATA_ENABLED)) {
return;
}
[[Warply sharedService] getContextWithPath:@"consumer_data" successBlock:^(NSDictionary *dict){
if (success)
success([dict valueForKey:@"user_email"]);
} failureBlock:^(NSError *error) {
if (failure)
failure(error);
}];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)getMsisdnWithSuccessBlock:(void (^)(NSString *userMsisdn))success
failureBlock:(void (^)(NSError *error))failure
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CONSUMER_DATA_ENABLED)) {
return;
}
[[Warply sharedService] getContextWithPath:@"consumer_data" successBlock:^(NSDictionary *dict){
if (success)
success([dict valueForKey:@"msisdn"]);
} failureBlock:^(NSError *error) {
if (failure)
failure(error);
}];
}
+ (void)getCustomDataWithSuccessBlock:(void (^)(NSDictionary *customData))success
failureBlock:(void (^)(NSError *error))failure
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CONSUMER_DATA_ENABLED)) {
return;
}
[[Warply sharedService] getContextWithPath:@"consumer_data" successBlock:^(NSDictionary *dict){
if (success)
success([dict valueForKey:@"custom_data"]);
} failureBlock:^(NSError *error) {
if (failure)
failure(error);
}];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)sendName:(NSString *)userName
{
[self sendLoginFieldWithName:@"user_name" andValue:userName];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)sendEmail:(NSString *)userEmail
{
[self sendLoginFieldWithName:@"user_email" andValue:userEmail];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)sendMsisdn:(NSString *)userMsisdn
{
[self sendLoginFieldWithName:@"msisdn" andValue:userMsisdn];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)sendLoginFieldWithName:(NSString *)key andValue:(NSString *)value
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CONSUMER_DATA_ENABLED)) {
return;
}
NSMutableDictionary *login_data = [NSMutableDictionary dictionaryWithCapacity:1];
if ([value length] > 0)
[login_data setValue:value forKey:key];
NSDictionary *eventDict = [NSDictionary dictionaryWithObjectsAndKeys:login_data, @"login_data", nil];
WLEventSimple *event = [WLEventSimple eventWithType:@"login_data" andContext:eventDict];
[[Warply sharedService] addEvent:event priority:YES];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)sendCustomData:(NSDictionary *)customData
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CONSUMER_DATA_ENABLED)) {
return;
}
NSMutableDictionary *custom_data = [NSMutableDictionary dictionaryWithCapacity:1];
if (customData != nil)
[custom_data setValue:customData forKey:@"custom_data"];
NSDictionary *eventDict = [NSDictionary dictionaryWithObjectsAndKeys:custom_data, @"consumer_data", nil];
WLEventSimple *event = [WLEventSimple eventWithType:@"consumer_data" andContext:eventDict];
[[Warply sharedService] addEvent:event priority:YES];
}
#pragma mark - UUIDs
///////////////////////////////////////////////////////////////////////////////
+ (void)sendUUIDS
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_CONSUMER_DATA_ENABLED)) {
return;
}
if (SYSTEM_VERSION_LESS_THAN(@"6.0"))
return;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
BOOL uuidsAlreadySentNum = [defaults boolForKey:@"uuidsAlreadySent"];
if (uuidsAlreadySentNum)
return;
NSMutableDictionary *apple_uuids = [NSMutableDictionary dictionaryWithCapacity:2];
[apple_uuids setValue:[NSNumber numberWithBool:[ASIdentifierManager sharedManager].advertisingTrackingEnabled] forKey:@"advertising_tracking_enabled"];
[apple_uuids setValue:[[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString] forKey:@"advertising_identifier"];
[apple_uuids setValue:[[[UIDevice currentDevice] identifierForVendor] UUIDString] forKey:@"identifier_for_vendor"];
NSDictionary *login_data = [NSDictionary dictionaryWithObjectsAndKeys:apple_uuids, @"ios_uuids", nil];
NSDictionary *eventDict = [NSDictionary dictionaryWithObjectsAndKeys:login_data, @"login_data", nil];
WLEventSimple *event = [WLEventSimple eventWithType:@"login_data" andContext:eventDict];
[[Warply sharedService] addEvent:event priority:NO];
[defaults setBool:YES forKey:@"uuidsAlreadySent"];
[defaults synchronize];
}
#pragma mark - User Tagging
///////////////////////////////////////////////////////////////////////////////
+ (void)addTag:(NSString *)tag
{
[self addTags:[NSArray arrayWithObject:tag]];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)addTags:(NSArray *)tags
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_USER_TAGGING_ENABLED)) {
return;
}
//Checking for items that are not NSString type.
#ifdef DEBUG
for (id tag in tags) {
NSAssert([tag isKindOfClass:[NSString class]], @"Array with only NSString objects is allowed in addTags:");
}
#endif
NSDictionary *eventContext = @{@"tags": @{@"action": @"add_tags", @"tags":tags}};
WLEventSimple *event = [[WLEventSimple alloc] initWithType:@"tags" andContext:eventContext];
[[Warply sharedService] addEvent:event priority:YES];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)removeTag:(NSString *)tag
{
[self removeTags:[NSArray arrayWithObject:tag]];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)removeTags:(NSArray *)tags
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_USER_TAGGING_ENABLED)) {
return;
}
NSDictionary *eventContext = @{@"tags": @{@"action": @"remove_tags", @"tags":tags}};
//Checking for items that are not NSString type.
#ifdef DEBUG
for (id tag in tags) {
NSAssert([tag isKindOfClass:[NSString class]], @"Array with only NSString objects is allowed in removeTags:");
}
#endif
WLEventSimple *event = [[WLEventSimple alloc] initWithType:@"tags" andContext:eventContext];
[[Warply sharedService] addEvent:event priority:YES];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)removeAllTags
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_USER_TAGGING_ENABLED)) {
return;
}
NSDictionary *eventContext = @{@"tags": @{@"action": @"remove_all_tags"}};
//Checking for items that are not NSString type.
WLEventSimple *event = [[WLEventSimple alloc] initWithType:@"tags" andContext:eventContext];
[[Warply sharedService] addEvent:event priority:YES];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)rewriteTags:(NSArray *)tags
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_USER_TAGGING_ENABLED)) {
return;
}
//Checking for items that are not NSString type.
#ifdef DEBUG
for (id tag in tags) {
NSAssert([tag isKindOfClass:[NSString class]], @"Array with only NSString objects is allowed in addTags:");
}
#endif
NSDictionary *eventContext = @{@"tags": @{@"action": @"rewrite_tags", @"tags":tags}};
WLEventSimple *event = [[WLEventSimple alloc] initWithType:@"tags" andContext:eventContext];
[[Warply sharedService] addEvent:event priority:YES];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)getTagsWithSuccessBlock:(void (^)(NSArray *tags))success failureBlock:(void (^)(NSError *error))failure
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_USER_TAGGING_ENABLED)) {
return;
}
[[Warply sharedService] getContextWithPath:@"tags"
successBlock:^(NSArray *tags) {
if (success) {
success(tags);
}
} failureBlock:^(NSError *error) {
if (failure) {
failure(error);
}
}];
}
#pragma mark - User Session
///////////////////////////////////////////////////////////////////////////////
+ (void)sessionLogin:(NSString *)authToken
successBlock:(void (^)(void))success
failureBlock:(void (^)(void))failure
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_USER_SESSION_ENABLED)) {
return;
}
if (authToken.length == 0) {
if (failure) {
WLLOG(@"Auth token should not be an empty string or nil;");
failure();
}
}
NSDictionary *userSessionDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSDictionary dictionaryWithObject:authToken forKey:@"auth_token"], @"login", nil];
NSDictionary *postDictionary = [NSDictionary dictionaryWithObjectsAndKeys:userSessionDict, @"user_session", nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:0 error:&error];
if (error) {
WLLOG(@"Invalid auth token");
if (failure) {
failure();
}
return;
}
[[Warply sharedService] sendContext:jsonData successBlock:^(NSDictionary *responseDict) {
if (success)
success();
} failureBlock:^(NSError *error) {
[self sessionRegister:authToken successBlock:success failureBlock:failure];
;
}];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)sessionLogout:(NSString *)authToken
successBlock:(void (^)(void))success
failureBlock:(void (^)(void))failure
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_USER_SESSION_ENABLED)) {
return;
}
if (authToken.length == 0) {
if (failure) {
WLLOG(@"Auth token cannot be nil or empty string.");
failure();
}
return;
}
NSDictionary *userSessionDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSDictionary dictionaryWithObject:authToken forKey:@"auth_token"], @"logout", nil];
NSDictionary *postDictionary = [NSDictionary dictionaryWithObjectsAndKeys:userSessionDict, @"user_session", nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:0 error:&error];
if (error != nil) {
WLLOG(@"Invalid auth token");
return;
}
[[Warply sharedService] sendContext:jsonData successBlock:^(NSDictionary *responseDict){
if (success)
success();
} failureBlock:^(NSError *error){
if (failure)
failure();
}];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)sessionRegister:(NSString *)authToken
successBlock:(void (^)(void))success
failureBlock:(void (^)(void))failure
{
if (WL_FEATURE_IS_DISABLED_WITH_KEY(WL_USER_SESSION_ENABLED)) {
return;
}
if (authToken.length == 0) {
if (failure) {
WLLOG(@"Auth token cannot be nil or empty string.");
failure();
}
return;
}
NSDictionary *userSessionDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSDictionary dictionaryWithObject:authToken forKey:@"auth_token"], @"register", nil];
NSDictionary *postDictionary = @{@"user_session": userSessionDict};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:0 error:&error];
if (error != nil) {
WLLOG(@"Invalid auth token");
if (failure) {
failure();
}
return;
}
[[Warply sharedService] sendContext:jsonData successBlock:^(NSDictionary *responseDict){
if (success)
success();
} failureBlock:^(NSError *error) {
if (failure)
failure();
}];
}
#pragma mark - Push Notifications Participation
///////////////////////////////////////////////////////////////////////////////
+ (void)setWarplyNotificationsEnabled:(BOOL)enable successBlock:(void (^)(void))success failureBlock:(void (^)(NSError *error))failure
{
NSDictionary *postDictionary = @{WL_APPLICATION_DATA:@{WL_WARP_NOTIFICATIONS_ENABLED:[NSNumber numberWithBool:enable]}};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:0 error:NULL];
[[Warply sharedService] sendContext:jsonData successBlock:^(NSDictionary *contextResponse) {
if (success) {
success();
}
} failureBlock:^(NSError *error) {
if (failure) {
failure(error);
}
}];
}
///////////////////////////////////////////////////////////////////////////////
+ (void)warplyNotificationsEnabledWithsuccessBlock:(void (^)(BOOL isEnabled))success failureBlock:(void (^)(NSError *error))failure;
{
[[Warply sharedService] getContextWithPath:WL_DEVICE_STATUS successBlock:^(id contextResponse) {
BOOL isEnabled = [[contextResponse valueForKey:WL_WARP_NOTIFICATIONS_ENABLED] boolValue];
if (success) {
success(isEnabled);
}
} failureBlock:^(NSError *error) {
if (failure) {
failure(error);
}
}];
return;
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLCustomNativeAdTableViewCell
The custom table view cell that user may use for presenting native advertisments.
@copyright Warply Inc.
*/
#import <UIKit/UIKit.h>
@class WLInboxItem;
/*!
@class WLCustomNativeAdTableViewCell
@discussion This class contains one setup method for the custom tableView cell that will be used for presenting the native advertisment. The custom cell MUST subclass the WLCustomNativeAdTableViewCell for this method to work.
*/
@interface WLCustomNativeAdTableViewCell : UITableViewCell
@property (strong, nonatomic) WLInboxItem *item;
/*!
* @abstract Thhis method is called from the service and it MUST be overriden in order for the custom actions to take place. Override this method in the implementation file of the custom cell and manipulate the WLInboxItem.
* @param item The WLInboxItem that contains all the data of the campaign to be presented.
*/
-(void)setupCustomCell:(WLInboxItem *)item;
-(WLInboxItem *)getInboxItem;
@end
//
// WLCustomNativeAdTableViewCell.m
// DemoApp
//
// Created by Nick Xirotyris on 4/2/16.
// Copyright © 2016 YC. All rights reserved.
//
#import "WLCustomNativeAdTableViewCell.h"
#import "WLInboxItem.h"
@implementation WLCustomNativeAdTableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
-(void)setupCustomCell:(WLInboxItem *)item {
NSLog(@"Custom native TableView Cell setup method.");
self.item = item;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
-(WLInboxItem *)getInboxItem{
return self.item;
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLCustomNativeCollectionViewCell
The custom collection view cell that user may use for presenting native advertisments.
@copyright Warply Inc.
*/
#import <UIKit/UIKit.h>
@class WLInboxItem;
/*!
@class WLCustomNativeCollectionViewCell
@discussion This class contains one setup method for the custom collectionView cell that will be used for presenting the native advertisment. The custom cell MUST subclass the WLCustomNativeCollectionViewCell for this method to work.
*/
@interface WLCustomNativeCollectionViewCell : UICollectionViewCell
@property (strong, nonatomic) WLInboxItem *item;
/*!
* @abstract Thhis method is called from the service and it MUST be overriden in order for the custom actions to take place. Override this method in the implementation file of the custom cell and manipulate the WLInboxItem.
* @param item The WLInboxItem that contains all the data of the campaign to be presented.
*/
-(void)setupCustomCell:(WLInboxItem *)item;
-(WLInboxItem *)getInboxItem;
@end
//
// WLCustomNativeCollectionViewCell.m
// DemoApp
//
// Created by Nick Xirotyris on 4/2/16.
// Copyright © 2016 YC. All rights reserved.
//
#import "WLCustomNativeCollectionViewCell.h"
#import "WLInboxItem.h"
@implementation WLCustomNativeCollectionViewCell
-(void)setupCustomCell:(WLInboxItem *)item {
NSLog(@"Custom native TableView Cell setup method.");
self.item = item;
}
-(WLInboxItem *)getInboxItem{
return self.item;
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLNativeAdCollectionViewCell
The CollectionView Cell for native ads.
@copyright Warply Inc.
*/
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
/*!
@class WLNativeAdCollectionViewCell
@discussion This class contains the properties of the cell of the native ad and the method to setup the cell.
*/
@interface WLNativeAdCollectionViewCell : UICollectionViewCell <UIWebViewDelegate>
/*!
* @property webView
* @abstract The webview that will show the native ad campaign.
*/
@property (weak, nonatomic) IBOutlet WKWebView *webView;
/*!
* @property activityIndicator
* @abstract The indicator waiting for the campaign to load.
*/
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;
/*!
@methodgroup Setup the cells
*/
/*!
* @abstract Shows the content of the native ad campaign.
* @discussion This method setups directly the content of the native ad campaign in the cell when the WLInboxItem is of display_type = feed.
* @param url The url of the campign to be presented.
*/
-(void)loadContentwithURL:(NSString *)url;
@end
//
// WLNativeAdCollectionViewCell.m
// DemoApp
//
// Created by Nick Xirotyris on 19/10/15.
// Copyright © 2015 YC. All rights reserved.
//
#import "WLNativeAdCollectionViewCell.h"
#import "Warply.h"
//#import "WLGlobals.h"
@implementation WLNativeAdCollectionViewCell
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
NSArray *arrayOfViews = [[NSBundle mainBundle] loadNibNamed:@"WLNativeAdCollectionViewCell" owner:self options:nil];
if ([arrayOfViews count] < 1) {
return nil;
}
if (![[arrayOfViews objectAtIndex:0] isKindOfClass:[UICollectionViewCell class]]) {
return nil;
}
self = [arrayOfViews objectAtIndex:0];
}
return self;
}
-(void)loadContentwithURL:(NSString *)url {
NSMutableURLRequest * request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
[request setValue:[Warply sharedService].webId forHTTPHeaderField:@"loyalty-web-id"];
[request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
[request setValue:@"gzip" forHTTPHeaderField:@"User-Agent"];
[self.webView loadRequest:request];
[self.activityIndicator startAnimating];
}
-(BOOL)webView:(WKWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (![request.URL.host isEqualToString:WARP_HOST] && ![request.URL.host isEqualToString:@"warplydata.blob.core.windows.net"]) {
[[UIApplication sharedApplication] openURL:request.URL];
}
return YES;
}
-(void)webViewDidFinishLoad:(WKWebView *)webView {
[self.activityIndicator stopAnimating];
}
-(void)webView:(WKWebView *)webView didFailLoadWithError:(NSError *)error {
NSLog(@"%@", error);
[self.activityIndicator stopAnimating];
}
@end
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="9531" systemVersion="15D21" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="9529"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<collectionViewCell opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" reuseIdentifier="adItem" id="9Rt-2X-RuJ" customClass="WLNativeAdCollectionViewCell">
<rect key="frame" x="0.0" y="0.0" width="200" height="150"/>
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<view key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center">
<rect key="frame" x="0.0" y="0.0" width="200" height="150"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<webView contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="lL4-lm-ZmW">
<rect key="frame" x="0.0" y="0.0" width="200" height="150"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<connections>
<outlet property="delegate" destination="9Rt-2X-RuJ" id="Uuz-NA-aUA"/>
</connections>
</webView>
<activityIndicatorView hidden="YES" opaque="NO" contentMode="scaleToFill" horizontalHuggingPriority="750" verticalHuggingPriority="750" fixedFrame="YES" hidesWhenStopped="YES" style="gray" translatesAutoresizingMaskIntoConstraints="NO" id="Nce-1c-FOV">
<rect key="frame" x="90" y="65" width="20" height="20"/>
</activityIndicatorView>
</subviews>
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
</view>
<constraints>
<constraint firstItem="lL4-lm-ZmW" firstAttribute="leading" secondItem="9Rt-2X-RuJ" secondAttribute="leading" id="FW4-bb-qnx"/>
<constraint firstAttribute="bottom" secondItem="lL4-lm-ZmW" secondAttribute="bottom" id="PZx-BK-Wud"/>
<constraint firstItem="lL4-lm-ZmW" firstAttribute="top" secondItem="9Rt-2X-RuJ" secondAttribute="top" id="Uw3-Vz-gUN"/>
<constraint firstAttribute="trailing" secondItem="lL4-lm-ZmW" secondAttribute="trailing" id="bb8-0l-EBV"/>
</constraints>
<size key="customSize" width="50" height="205"/>
<connections>
<outlet property="activityIndicator" destination="Nce-1c-FOV" id="JRg-6f-bVF"/>
<outlet property="webView" destination="lL4-lm-ZmW" id="yFg-tC-eyH"/>
</connections>
<point key="canvasLocation" x="186" y="127"/>
</collectionViewCell>
</objects>
</document>
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLNativeAdTableViewCell
The TableView Cell for native ads.
@copyright Warply Inc.
*/
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
#import "WLInboxItem.h"
/*!
@class WLNativeAdTableViewCell
@discussion This class contains the properties of the cell of the native ad and methods to setup the cell.
*/
@interface WLNativeAdTableViewCell : UITableViewCell <UIWebViewDelegate>
@property (strong, nonatomic) WLInboxItem *item;
/*!
* @property webView
* @abstract The webview that will show the native ad campaign.
*/
@property (weak, nonatomic) IBOutlet WKWebView *webView;
/*!
* @property activityIndicator
* @abstract The indicator waiting for the campaign to load.
*/
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;
/*!
* @property adImageView
* @abstract The image of the campaign
*/
@property (weak, nonatomic) IBOutlet UIImageView *adImageView;
/*!
* @property adLabel
* @abstract This label contains the title and the subtitle of the campaign.
*/
@property (weak, nonatomic) IBOutlet UILabel *adLabel;
/*!
@methodgroup Setup the cells
*/
/*!
* @abstract Setups the cell with a WLInboxItem.
* @discussion This method setups the cell with a WLInboxItem that is related to the native ad campaign that is presented in this cell
* @param item The WLInboxItem that is of display_type = list.
*/
-(void)setupCellWithItem:(WLInboxItem *)item;
/*!
* @abstract Shows the content of the native ad campaign.
* @discussion This method setups directly the content of the native ad campaign in the cell when the WLInboxItem is of display_type = feed.
* @param url The url of the campign to be presented.
*/
-(void)loadContentwithURL:(NSString *)url;
@end
//
// WLNativeAdTableViewCell.m
// DemoApp
//
// Created by Nick Xirotyris on 14/10/15.
// Copyright © 2015 YC. All rights reserved.
//
#import "WLNativeAdTableViewCell.h"
#import "Warply.h"
#import <WebKit/WebKit.h>
#import "UIImageView+AFNetworking.h"
//#import "WLGlobals.h"
@implementation WLNativeAdTableViewCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
self.webView.UIDelegate = self;
self.adImageView.clipsToBounds = YES;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
-(void)setupCellWithItem:(WLInboxItem *)item {
self.item = item;
self.adLabel.text = item.title;
self.webView.alpha = 0;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[item getImageURL]]];
[self.activityIndicator startAnimating];
[self.adImageView setImageWithURLRequest:request
placeholderImage:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
[self.activityIndicator stopAnimating];
self.adImageView.image = image;
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
[self.activityIndicator stopAnimating];
}];
}
-(void)loadContentwithURL:(NSString *)url {
self.adLabel.alpha = 0;
self.adImageView.alpha = 0;
NSMutableURLRequest * request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
[request setValue:[Warply sharedService].webId forHTTPHeaderField:@"loyalty-web-id"];
[request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
[request setValue:@"gzip" forHTTPHeaderField:@"User-Agent"];
[self.webView loadRequest:request];
[self.activityIndicator startAnimating];
}
#pragma mark - WebView Delegate
-(BOOL)webView:(WKWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if (![request.URL.host isEqualToString:WARP_HOST] && ![request.URL.host isEqualToString:@"warplydata.blob.core.windows.net"]) {
[[UIApplication sharedApplication] openURL:request.URL];
}
return YES;
}
-(void)webViewDidFinishLoad:(WKWebView *)webView {
[self.activityIndicator stopAnimating];
}
-(void)webView:(WKWebView *)webView didFailLoadWithError:(NSError *)error {
NSLog(@"%@", error);
[self.activityIndicator stopAnimating];
}
@end
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="9532" systemVersion="15D21" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="9530"/>
<capability name="Aspect ratio constraints" minToolsVersion="5.1"/>
<capability name="Constraints to layout margins" minToolsVersion="6.0"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="nativeCell" rowHeight="80" id="TUO-3e-Z0c" customClass="WLNativeAdTableViewCell">
<rect key="frame" x="0.0" y="0.0" width="320" height="80"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="TUO-3e-Z0c" id="rFP-el-oLd">
<rect key="frame" x="0.0" y="0.0" width="320" height="79.5"/>
<autoresizingMask key="autoresizingMask"/>
<subviews>
<webView contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="95U-Ni-FSn">
<rect key="frame" x="0.0" y="0.0" width="320" height="79"/>
<color key="backgroundColor" white="0.0" alpha="0.0" colorSpace="calibratedWhite"/>
<connections>
<outlet property="delegate" destination="TUO-3e-Z0c" id="8nn-Mf-VRq"/>
</connections>
</webView>
<imageView userInteractionEnabled="NO" contentMode="scaleAspectFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="xLm-Bp-71W">
<rect key="frame" x="8" y="8" width="152" height="64"/>
</imageView>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Advertisement" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="396-VT-2Ee">
<rect key="frame" x="233" y="65" width="87" height="14"/>
<constraints>
<constraint firstAttribute="height" constant="14" id="SFz-Ux-2Y8"/>
<constraint firstAttribute="width" constant="87" id="k55-7i-nkq"/>
</constraints>
<fontDescription key="fontDescription" type="system" pointSize="12"/>
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="center" lineBreakMode="tailTruncation" numberOfLines="0" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="NSR-sb-7cF">
<rect key="frame" x="161" y="8" width="151" height="55"/>
<fontDescription key="fontDescription" type="system" pointSize="15"/>
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
<nil key="highlightedColor"/>
</label>
<activityIndicatorView hidden="YES" opaque="NO" contentMode="scaleToFill" horizontalHuggingPriority="750" verticalHuggingPriority="750" fixedFrame="YES" hidesWhenStopped="YES" style="gray" translatesAutoresizingMaskIntoConstraints="NO" id="2i1-rB-bMz">
<rect key="frame" x="150" y="30" width="20" height="20"/>
</activityIndicatorView>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="a1K-T8-Q5a">
<rect key="frame" x="0.0" y="78" width="320" height="1"/>
<color key="backgroundColor" white="0.66666666666666663" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstAttribute="height" constant="1" id="ahQ-nq-Svc"/>
</constraints>
</view>
</subviews>
<constraints>
<constraint firstAttribute="bottom" secondItem="95U-Ni-FSn" secondAttribute="bottom" constant="1" id="2do-aZ-hiv"/>
<constraint firstAttribute="trailing" secondItem="NSR-sb-7cF" secondAttribute="trailing" constant="8" id="3TW-AH-T85"/>
<constraint firstAttribute="trailing" secondItem="95U-Ni-FSn" secondAttribute="trailing" id="DS0-Pz-ZxO"/>
<constraint firstAttribute="trailing" secondItem="a1K-T8-Q5a" secondAttribute="trailing" id="Gi2-gJ-nmY"/>
<constraint firstItem="95U-Ni-FSn" firstAttribute="top" secondItem="rFP-el-oLd" secondAttribute="top" id="GyZ-hA-4Dl"/>
<constraint firstItem="NSR-sb-7cF" firstAttribute="top" secondItem="rFP-el-oLd" secondAttribute="top" constant="8" id="JR8-fp-s3F"/>
<constraint firstItem="95U-Ni-FSn" firstAttribute="leading" secondItem="rFP-el-oLd" secondAttribute="leading" id="NIf-5g-WS2"/>
<constraint firstAttribute="trailing" secondItem="396-VT-2Ee" secondAttribute="trailing" id="Puz-ao-t5a"/>
<constraint firstAttribute="bottomMargin" secondItem="a1K-T8-Q5a" secondAttribute="bottom" id="QCr-O6-1AG"/>
<constraint firstItem="396-VT-2Ee" firstAttribute="top" secondItem="NSR-sb-7cF" secondAttribute="bottom" constant="2" id="WUG-eo-mFh"/>
<constraint firstAttribute="bottom" secondItem="396-VT-2Ee" secondAttribute="bottom" constant="0.5" id="d4X-1L-xI0"/>
<constraint firstItem="a1K-T8-Q5a" firstAttribute="leading" secondItem="rFP-el-oLd" secondAttribute="leading" id="ixG-zU-9Md"/>
<constraint firstItem="NSR-sb-7cF" firstAttribute="leading" secondItem="xLm-Bp-71W" secondAttribute="trailing" constant="1" id="mVf-Ie-GET"/>
<constraint firstItem="xLm-Bp-71W" firstAttribute="width" secondItem="NSR-sb-7cF" secondAttribute="width" id="sHF-sC-dIe"/>
<constraint firstItem="xLm-Bp-71W" firstAttribute="width" secondItem="rFP-el-oLd" secondAttribute="height" multiplier="2:1" id="sXq-4t-rRt"/>
<constraint firstItem="xLm-Bp-71W" firstAttribute="leading" secondItem="rFP-el-oLd" secondAttribute="leading" constant="8" id="tPi-ou-5x7"/>
<constraint firstAttribute="bottom" secondItem="a1K-T8-Q5a" secondAttribute="bottom" id="tQY-Sv-9zd"/>
<constraint firstItem="xLm-Bp-71W" firstAttribute="top" secondItem="rFP-el-oLd" secondAttribute="top" constant="8" id="yCS-mb-vzW"/>
<constraint firstAttribute="bottom" secondItem="xLm-Bp-71W" secondAttribute="bottom" constant="8" id="yRo-mZ-HKk"/>
</constraints>
<variation key="default">
<mask key="constraints">
<exclude reference="sXq-4t-rRt"/>
<exclude reference="QCr-O6-1AG"/>
</mask>
</variation>
</tableViewCellContentView>
<connections>
<outlet property="activityIndicator" destination="2i1-rB-bMz" id="TzL-ld-iTy"/>
<outlet property="adImageView" destination="xLm-Bp-71W" id="TZ7-9X-2hw"/>
<outlet property="adLabel" destination="NSR-sb-7cF" id="WdI-PV-UhH"/>
<outlet property="webView" destination="95U-Ni-FSn" id="JXN-nw-EjM"/>
</connections>
<point key="canvasLocation" x="684" y="370"/>
</tableViewCell>
</objects>
</document>
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLNativeAdsCollectionMode
The Collection View mode for integrating native ads in a UICollectionView
@copyright Warply Inc.
*/
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "WLInboxItem.h"
#import "WLCustomNativeCollectionViewCell.h"
/*!
@protocol WLNativeAdsCollectionModeDelegate
@abstract If there is a need for showing the content of native ad the user must create an option that conforms to the WLNativeAdsCollectionModeDelegate protocol and implement the nativeAdDidSelectWithItem: method.
*/
/*!
@methodgroup Showing native ad content
*/
/*!
@abstract Presents the content of the native ad.
@discussion Receives a WLInboxItem which you can present to a WLInboxViewController. Also, you can handle its data in any custom way.
*/
@protocol WLNativeAdsCollectionModeDelegate <NSObject>
@optional
- (void)nativeAdDidSelectWithItem:(WLInboxItem *)item;
@end
/*!
@class WLNativeAdsCollectionMode
@discussion This class handles the integration of native ads in a UICollectionView. It manages the datasource and the delegate of the original UICollectionView and returns a collectionView with native ads embeded as per user choice. All the delegates and datasource methods are executed in case the original class executes them.
*/
@interface WLNativeAdsCollectionMode : NSObject
@property (nonatomic, assign) id<WLNativeAdsCollectionModeDelegate> delegate;
/*!
* @methodgroup Initialising the CollectionView mode of native ads
*/
/*!
* @abstract Initializes the WLNativeAdsCollectionMode object.
* @discussion This class handles and integrates native ads in an original UICollectionView object.
* @param viewController The View Controller where the original collectionView exists.
* @param collectionView The original collectionView object where we will add the native ads.
* @param startPosition The position where the ads will start to appear in the collectionView. It counts from 0.
* @param frequency The frequency with which the ads will appear in the collectionView.
* @param size The size of the cell the native ad will be presented.
* @param displayType The display type of the campaigns that the user will present as native ads.
*/
-(id)initWithViewController:(UIViewController <UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout> *)viewController CollectionView:(UICollectionView *)collectionView withStartPosition:(NSInteger)startPosition Frequency:(NSInteger)frequency CellSize:(CGSize)size andDisplayType:(NSString *)displayType;
/*!
@methodgroup Setting up a custom cell for native ads
*/
/*!
* @abstract Setups a custom cell.
* @discussion The user has the option to create his own cell for the native ads and presents the data in his own descression. The custom cell MUST subclass the WLCustomNativeCollectionViewCell object and run the setupCustomCell: method. There, he can manipulate the data of a WLInboxItem. This method is optional.
* @param cell The cell object that user will use as a native Ad cell
* @param cellIdentifier The cell's identifier
* @param nibName The nib's name in the case the cell is designed with a .xib file and not in Storyboard.
*/
-(void)setCustomCellForNativeAd:(WLCustomNativeCollectionViewCell *)cell withIdentifier:(NSString *)cellIdentifier andNibName:(NSString *)nibName;
/*!
@methodgroup Handling the native Ads CollectionView
*/
/*!
* @abstract Refresh the collectionView datasource and delegate.
* @discussion Call this method when the datasource of the original collectionView will change. For example call this function after an asynchronous update of the data of the collectionView.
* @param collectionView The original collectionView object which will change after the update.
*/
-(void)refreshAdsForCollectionView:(UICollectionView *)collectionView;
/**
* @abstract Defines if the ads will appear in a repeatable way in the collectionView.
* @discussion Call this method if you want to set the repeatable property to YES. That means that the ads will be repeated until the end of the collectionView. Default value is NO.
* @param repeatable BOOL value that sets if the native ads will repeat themselves in the collectionView.
*/
-(void)setRepeatable:(BOOL)repeatable;
//-(NSIndexPath *)getOriginalIndexPath:(NSIndexPath *)indexPath;
@end
//
// WLNativeAdsCollectionMode.m
// DemoApp
//
// Created by Nick Xirotyris on 19/10/15.
// Copyright © 2015 YC. All rights reserved.
//
#import "WLNativeAdsCollectionMode.h"
#import "WLNativeAdCollectionViewCell.h"
#import "Warply.h"
@interface WLNativeAdsCollectionMode () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (weak, nonatomic) id<UICollectionViewDataSource> originalDatasource;
@property (weak, nonatomic) id<UICollectionViewDelegate> originalDelegate;
@property (strong, nonatomic) id<UICollectionViewDelegateFlowLayout> originalFlowLayout;
@property (weak, nonatomic) UICollectionView *nativeCollectionView;
@property (nonatomic, weak) WLCustomNativeCollectionViewCell *customCell;
@property (nonatomic, strong) NSString *customCellIdentifier;
@property (nonatomic, strong) NSString *customCellNibName;
@property (weak, nonatomic) UIViewController <UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout> *originalVC;
@end
@implementation WLNativeAdsCollectionMode {
NSInteger adsForCollectionView;
NSInteger startAd;
NSInteger frequencyAd;
NSInteger originalNumberOfsections;
NSInteger currentRows;
NSInteger totalExtraRows;
NSMutableArray *indexArrayOfAds;
NSArray *offersArray;
CGSize cellSize;
NSString *display_type;
BOOL repeatableAds;
}
-(id)initWithViewController:(UIViewController<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout> *)viewController CollectionView:(UICollectionView *)collectionView withStartPosition:(NSInteger)startPosition Frequency:(NSInteger)frequency CellSize:(CGSize)size andDisplayType:(NSString *)displayType{
self = [super init];
if (self) {
[self getInbox];
[self.nativeCollectionView registerClass:[WLNativeAdCollectionViewCell class] forCellWithReuseIdentifier:@"adItem"];
[collectionView registerClass:[WLNativeAdCollectionViewCell class] forCellWithReuseIdentifier:@"adItem"];
self.originalDatasource = collectionView.dataSource;
self.originalDelegate = collectionView.delegate;
self.nativeCollectionView = collectionView;
self.originalVC = viewController;
self.originalFlowLayout = (id<UICollectionViewDelegateFlowLayout>)self.originalDelegate;
startAd = startPosition;
frequencyAd = frequency;
display_type = displayType;
if ([self.originalDatasource respondsToSelector:@selector(numberOfSectionsInCollectionView:)]) {
originalNumberOfsections = [self.originalDatasource numberOfSectionsInCollectionView:collectionView];
} else {
originalNumberOfsections = 1;
}
repeatableAds = NO;
currentRows = 0;
totalExtraRows = 0;
cellSize = size;
}
return self;
}
- (void)refreshAdsForCollectionView:(UICollectionView *)collectionView {
self.originalDatasource = nil;
self.originalDelegate = nil;
self.nativeCollectionView = nil;
collectionView.dataSource = nil;
collectionView.delegate = nil;
collectionView.dataSource = self.originalVC;
collectionView.delegate = self.originalVC;
self.originalDatasource = collectionView.dataSource;
self.originalDelegate = collectionView.delegate;
self.nativeCollectionView = collectionView;
if ([self.originalDatasource respondsToSelector:@selector(numberOfSectionsInCollectionView:)]) {
originalNumberOfsections = [self.originalDatasource numberOfSectionsInCollectionView:collectionView];
} else {
originalNumberOfsections = 1;
}
currentRows = 0;
totalExtraRows = 0;
[self getInbox];
}
-(void)setRepeatable:(BOOL)repeatable {
repeatableAds = repeatable;
if (!repeatable) {
int counter = 0;
for (int i = 0; i < originalNumberOfsections; i++) {
for (int j = 0; j < [[indexArrayOfAds objectAtIndex:i] count]; j++) {
if ([[[indexArrayOfAds objectAtIndex:i] objectAtIndex:j] isEqual:@(YES)]) {
counter++;
if (counter > adsForCollectionView) {
[[indexArrayOfAds objectAtIndex:i] removeObjectAtIndex:j];
}
}
}
}
[self.nativeCollectionView reloadData];
} else {
NSLog(@"Nothing to remove");
}
}
-(void)setCustomCellForNativeAd:(WLCustomNativeCollectionViewCell *)cell withIdentifier:(NSString *)cellIdentifier andNibName:(NSString *)nibName {
self.customCell = cell;
self.customCellIdentifier = cellIdentifier;
self.customCellNibName = nibName;
}
-(void)getInbox {
[[Warply sharedService] getInboxWithSuccessBlock:^(NSArray *list) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"(display_type == '%@')", display_type]];
offersArray = [list filteredArrayUsingPredicate:predicate];
if (offersArray.count > 0) {
[self setupNewRowsPerSection];
[self setRepeatable:repeatableAds];
self.nativeCollectionView.dataSource = self;
self.nativeCollectionView.delegate = self;
self.nativeCollectionView.allowsSelection = YES;
[self.nativeCollectionView reloadData];
}
} failureBlock:^(NSError *error) {
//
}];
}
#pragma mark - Original IndexPath & Helpers
- (void)setupNewRowsPerSection {
indexArrayOfAds = [NSMutableArray array];
int count = 0;
for (int i = 0; i < originalNumberOfsections; i++) {
NSMutableArray *newRows = [NSMutableArray array];
NSInteger total = [self totalRowsWithAdsForSection:i];
for (int j = 0; j < total; j++) {
if (count == startAd || (count > startAd && (count - startAd)%(frequencyAd + 1) == 0)) {
[newRows addObject:@(YES)];
} else {
[newRows addObject:@(NO)];
}
count++;
}
[indexArrayOfAds addObject:newRows];
}
NSLog(@"%@", indexArrayOfAds);
}
-(NSInteger)totalRowsWithAdsForSection:(int)section {
NSInteger originalRows = [self.originalDatasource collectionView:self.nativeCollectionView numberOfItemsInSection:section];
currentRows += originalRows;
if (currentRows < startAd) {
return originalRows;
} else {
if (startAd + 1 >= currentRows - originalRows && startAd + 1 <= currentRows) {
NSInteger extraRows = (currentRows - startAd)/frequencyAd + 1;
totalExtraRows += extraRows;
return extraRows + originalRows;
} else {
NSInteger extraRowsSoFar = (currentRows - startAd)/frequencyAd + 1;
NSInteger extraRowsForSection = extraRowsSoFar - totalExtraRows;
totalExtraRows += extraRowsForSection;
return originalRows + extraRowsForSection;
}
}
}
-(NSIndexPath *)getOriginalIndexPath:(NSIndexPath *)indexPath {
int extraRows = 0;
for (int i = 0; i < indexPath.row; i++) {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:i] isEqual:@(YES)]) {
extraRows++;
}
}
// NSLog(@"row: %ld", (long)indexPath.row - extraRows);
return [NSIndexPath indexPathForRow:indexPath.row - extraRows inSection:indexPath.section];
}
-(int)getIndexOfAd:(NSIndexPath *)indexPath {
int adsCount = 0;
for (int i = 0; i < indexPath.section + 1; i++) {
int rows = 0;
if (indexPath.section > i) {
rows = (int)[[indexArrayOfAds objectAtIndex:i] count];
} else {
rows = (int)indexPath.row + 1;
}
for (int j = 0; j < rows; j++) {
if ([[[indexArrayOfAds objectAtIndex:i] objectAtIndex:j] isEqual:@(YES)]) {
adsCount++;
}
}
}
if (adsCount == offersArray.count) {
return adsCount-1;
} else {
return adsCount%offersArray.count - 1;
}
}
#pragma mark - CollectionView Datasource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return originalNumberOfsections;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [[indexArrayOfAds objectAtIndex:section] count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
if (self.customCell) {
NSString *customIdentifier = [NSString stringWithFormat:@"%@", self.customCellIdentifier];
WLCustomNativeCollectionViewCell *customCell = (WLCustomNativeCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:customIdentifier forIndexPath:indexPath];
if (self.customCellNibName) {
if (customCell == nil) {
customCell = [[[NSBundle mainBundle] loadNibNamed:[NSString stringWithFormat:@"%@", self.customCellNibName] owner:self options:nil] objectAtIndex:0];
}
}
if (offersArray.count > 0) {
WLInboxItem *item = (WLInboxItem *)offersArray[[self getIndexOfAd:indexPath]];
[customCell setupCustomCell:item];
}
return customCell;
} else {
WLNativeAdCollectionViewCell *cell = (WLNativeAdCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"adItem" forIndexPath:indexPath];
if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:@"WLNativeAdCollectionViewCell" owner:self options:nil] objectAtIndex:0];
}
cell.backgroundColor = [UIColor whiteColor];
WLInboxItem *item = (WLInboxItem *)offersArray[[self getIndexOfAd:indexPath]];
[cell loadContentwithURL:[item getPageURL]];
return cell;
}
} else {
return [self.originalDatasource collectionView:self.nativeCollectionView cellForItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
#pragma mark - CollectionView Delegate
-(BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
return NO;
} else {
if ([self.originalDelegate respondsToSelector:@selector(collectionView:canPerformAction:forItemAtIndexPath:withSender:)]) {
return [self.originalDelegate collectionView:self.nativeCollectionView canPerformAction:(SEL)action forItemAtIndexPath:[self getOriginalIndexPath:indexPath] withSender:sender];
}
return NO;
}
}
-(void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
return;
} else {
if ([self.originalDelegate respondsToSelector:@selector(collectionView:performAction:forItemAtIndexPath:withSender:)]) {
[self.originalDelegate collectionView:self.nativeCollectionView performAction:(SEL)action forItemAtIndexPath:[self getOriginalIndexPath:indexPath] withSender:sender];
}
}
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
return;
} else {
if ([self.originalDelegate respondsToSelector:@selector(collectionView:didDeselectItemAtIndexPath:)]) {
return [self.originalDelegate collectionView:self.nativeCollectionView didDeselectItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
if (offersArray.count > 0) {
WLInboxItem *item = (WLInboxItem *)offersArray[[self getIndexOfAd:indexPath]];
if ([[self delegate] respondsToSelector:@selector(nativeAdDidSelectWithItem:)]) {
[[self delegate] nativeAdDidSelectWithItem:item];
}
}
} else {
if ([self.originalDelegate respondsToSelector:@selector(collectionView:didSelectItemAtIndexPath:)]) {
[self.originalDelegate collectionView:self.nativeCollectionView didSelectItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
}
-(void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
return;
} else {
if ([self.originalDelegate respondsToSelector:@selector(collectionView:didHighlightItemAtIndexPath:)]) {
return [self.originalDelegate collectionView:self.nativeCollectionView didHighlightItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
}
-(void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
return;
} else {
if ([self.originalDelegate respondsToSelector:@selector(collectionView:didUnhighlightItemAtIndexPath:)]) {
return [self.originalDelegate collectionView:self.nativeCollectionView didUnhighlightItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
}
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
//FIXME: wrong conditions
// if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
// return NO;
// } else {
// if ([self.originalDelegate respondsToSelector:@selector(collectionView:shouldSelectItemAtIndexPath:)]) {
// return [self.originalDelegate collectionView:self.nativeCollectionView shouldSelectItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
// }
// }
return YES;
}
-(BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
// if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
// return NO;
// } else {
// if ([self.originalDelegate respondsToSelector:@selector(collectionView:shouldDeselectItemAtIndexPath:)]) {
// return [self.originalDelegate collectionView:self.nativeCollectionView shouldDeselectItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
// }
// }
return YES;
}
-(BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath {
//FIXME: wrong conditions
// if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
// return NO;
// } else {
// if ([self.originalDelegate respondsToSelector:@selector(collectionView:shouldHighlightItemAtIndexPath:)]) {
// return [self.originalDelegate collectionView:self.nativeCollectionView shouldHighlightItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
// }
// }
//
// return NO;
return YES;
}
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
return NO;
} else {
if ([self.originalDelegate respondsToSelector:@selector(collectionView:shouldShowMenuForItemAtIndexPath:)]) {
return [self.originalDelegate collectionView:self.nativeCollectionView shouldShowMenuForItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
return NO;
}
-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
return;
} else {
if ([self.originalDelegate respondsToSelector:@selector(collectionView:willDisplayCell:forItemAtIndexPath:)]) {
return [self.originalDelegate collectionView:self.nativeCollectionView willDisplayCell:cell forItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
}
-(void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
return;
} else {
if ([self.originalDelegate respondsToSelector:@selector(collectionView:didEndDisplayingCell:forItemAtIndexPath:)]) {
return [self.originalDelegate collectionView:self.nativeCollectionView didEndDisplayingCell:cell forItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
}
-(void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
return;
} else {
if ([self.originalDelegate respondsToSelector:@selector(collectionView:willDisplaySupplementaryView:forElementKind:atIndexPath:)]) {
return [self.originalDelegate collectionView:self.nativeCollectionView willDisplaySupplementaryView:view forElementKind:elementKind atIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
}
-(void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(UICollectionReusableView *)view forElementOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
return;
} else {
if ([self.originalDelegate respondsToSelector:@selector(collectionView:didEndDisplayingSupplementaryView:forElementOfKind:atIndexPath:)]) {
return [self.originalDelegate collectionView:self.nativeCollectionView didEndDisplayingSupplementaryView:view forElementOfKind:elementKind atIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
}
#pragma mark - CollectionView Flow Layout
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
if ([self.originalFlowLayout respondsToSelector:@selector(collectionView:layout:insetForSectionAtIndex:)]) {
return [self.originalFlowLayout collectionView:self.nativeCollectionView layout:collectionViewLayout insetForSectionAtIndex:section];
}
return UIEdgeInsetsZero;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
if ([self.originalFlowLayout respondsToSelector:@selector(collectionView:layout:minimumInteritemSpacingForSectionAtIndex:)]) {
return [self.originalFlowLayout collectionView:self.nativeCollectionView layout:collectionViewLayout minimumInteritemSpacingForSectionAtIndex:section];
}
return 10;
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
if ([self.originalFlowLayout respondsToSelector:@selector(collectionView:layout:minimumLineSpacingForSectionAtIndex:)]) {
return [self.originalFlowLayout collectionView:self.nativeCollectionView layout:collectionViewLayout minimumLineSpacingForSectionAtIndex:section];
}
return 10;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
if ([self.originalFlowLayout respondsToSelector:@selector(collectionView:layout:referenceSizeForFooterInSection:)]) {
return [self.originalFlowLayout collectionView:self.nativeCollectionView layout:collectionViewLayout referenceSizeForFooterInSection:section];
}
return CGSizeZero;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
if ([self.originalFlowLayout respondsToSelector:@selector(collectionView:layout:referenceSizeForHeaderInSection:)]) {
return [self.originalFlowLayout collectionView:self.nativeCollectionView layout:collectionViewLayout referenceSizeForHeaderInSection:section];
}
return CGSizeZero;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
return cellSize;
} else {
if ([self.originalDelegate respondsToSelector:@selector(collectionView:layout:sizeForItemAtIndexPath:)]) {
return [self.originalFlowLayout collectionView:self.nativeCollectionView layout:collectionViewLayout sizeForItemAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
UICollectionViewFlowLayout *flow = (UICollectionViewFlowLayout *)collectionView.collectionViewLayout;
return flow.itemSize;
}
@end
/*
Copyright 2010-2016 Warply Inc. All rights reserved.
Redistribution and use in source and binary forms, without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binaryform must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
EVENT SHALL WARPLY LTD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*!
@header WLNativeAdsTableMode
The Table View mode for integrating native ads in a UITableView
@copyright Warply Inc.
*/
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "WLInboxItem.h"
#import "WLCustomNativeAdTableViewCell.h"
/*!
@protocol WLNativeAdsTableModeDelegate
@abstract If there is a need for showing the content of native ad the user must create an option that conforms to the WLNativeAdsTableModeDelegate protocol and implement the nativeAdDidSelectWithItem: method.
*/
/*!
@methodgroup Showing native ad content
*/
/*!
@abstract Presents the content of the native ad.
@discussion Receives a WLInboxItem which you can present to a WLInboxViewController. Also, you can handle its data in any custom way.
*/
@protocol WLNativeAdsTableModeDelegate <NSObject>
@optional
- (void)nativeAdDidSelectWithItem:(WLInboxItem *)item;
@end
/*!
@class WLNativeAdsTableMode
@discussion This class handles the integration of native ads in a UITableView. It manages the datasource and the delegate of the original UITableView and returns a tableview with native ads embeded as per user choice. All the delegates and datasource methods are executed in case the original class executes them
*/
@interface WLNativeAdsTableMode : NSObject <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, assign) id<WLNativeAdsTableModeDelegate> delegate;
/*!
@methodgroup Initialising the TableView mode of native ads
*/
/*!
@abstract Initializes the WLNativeAdsTableMode object.
@discussion This class handles and integrates native ads in an original UITableView object.
@param viewController The View Controller where the original tableview exists.
@param tableView The original tableview object where we will add the native ads.
@param startPosition The position where the ads will start to appear in the tableView. It counts from 0.
@param frequency The frequency with which the ads will appear in the tableView.
@param adHeight The height of the cell the native ad will be presented.
@param displayType The display type of the campaigns that the user will present as native ads.
*/
-(id)initWithViewController:(UIViewController <UITableViewDataSource,UITableViewDelegate> *)viewController Tableview:(UITableView *)tableView withStartPosition:(NSInteger)startPosition Frequency:(NSInteger)frequency Height:(CGFloat)adHeight andDisplayType:(NSString *)displayType;
/*!
@methodgroup Setting up a custom cell for native ads
*/
/*!
* @abstract Setups a custom cell.
* @discussion The user has the option to create his own cell for the native ads and presents the data in his own descression. The custom cell MUST subclass the WLCustomNativeAdTableViewCell object and run the setupCustomCell: method. There, he can manipulate the data of a WLInboxItem. This method is optional.
* @param cell The cell object that user will use as a native Ad cell
* @param cellIdentifier The cell's identifier
* @param nibName The nib's name in the case the cell is designed with a .xib file and not in Storyboard.
*/
-(void)setCustomCellForNativeAd:(WLCustomNativeAdTableViewCell *)cell withIdentifier:(NSString *)cellIdentifier andNibName:(NSString *)nibName;
/*!
@methodgroup Handling the native Ads TableView
*/
/*!
@abstract Refresh the tableView datasource and delegate.
@discussion Call this method when the datasource of the original tableView will change. For example call this function after an asynchronous update of the data of the tableView.
@param tableView The original tableview object which will change after the update.
*/
-(void)refreshAdsForTableView:(UITableView *)tableView;
/*!
@abstract Defines if the ads will appear in a repeatable way in the tableView.
@discussion Call this method if you want to set the repeatable property to YES. That means that the ads will be repeated until the end of the tableView. Default value is NO.
@param repeatable BOOL value that sets fi the native ads will repeat themselves in the tableView.
*/
-(void)setRepeatable:(BOOL)repeatable;
//-(NSIndexPath *)getOriginalIndexPath:(NSIndexPath *)indexPath;
@end
//
// WLNativeAds.m
// DemoApp
//
// Created by Nick Xirotyris on 14/10/15.
// Copyright © 2015 YC. All rights reserved.
//
#import "WLNativeAdsTableMode.h"
#import "Warply.h"
#import <UIKit/UIKit.h>
#import "WLNativeAdTableViewCell.h"
#import <AVFoundation/AVFoundation.h>
@interface WLNativeAdsTableMode ()
@property (nonatomic, strong) id<UITableViewDelegate> originalDelegate;
@property (nonatomic, weak) id<UITableViewDataSource> originalDataSource;
@property (nonatomic, weak) UITableView *nativeTableView;
@property (nonatomic, weak) WLCustomNativeAdTableViewCell *customCell;
@property (nonatomic, strong) NSString *customCellIdentifier;
@property (nonatomic, strong) NSString *customCellNibName;
@property(nonatomic, weak) UIViewController <UITableViewDataSource,UITableViewDelegate> *originalVC;
@end
@implementation WLNativeAdsTableMode {
NSArray *offersArray;
CGFloat nativeAdHeight;
NSInteger startAd;
NSInteger frequencyAd;
NSInteger totalOriginalRows;
NSInteger totalExtraRows;
NSInteger currentRows;
NSInteger originalNumberOfsections;
NSMutableArray *originalRowsPerSection;
NSMutableArray *indexArrayOfAds;
NSString *display_type;
BOOL repeatableAds;
}
-(id)initWithViewController:(UIViewController <UITableViewDataSource,UITableViewDelegate> *)viewController Tableview:(UITableView *)tableView withStartPosition:(NSInteger)startPosition Frequency:(NSInteger)frequency Height:(CGFloat)adHeight andDisplayType:(NSString *)displayType{
NSLog(@"%@", displayType);
self = [super init];
if (self) {
[self.nativeTableView registerNib:[UINib nibWithNibName:@"WLNativeAdTableViewCell" bundle:nil] forCellReuseIdentifier:@"nativeCell"];
[tableView registerNib:[UINib nibWithNibName:@"WLNativeAdTableViewCell" bundle:nil] forCellReuseIdentifier:@"nativeCell"];
self.originalDataSource = tableView.dataSource;
self.originalDelegate = tableView.delegate;
self.nativeTableView = tableView;
self.originalVC = viewController;
if ([self.originalDataSource respondsToSelector:@selector(numberOfSectionsInTableView:)]) {
originalNumberOfsections = [self.originalDataSource numberOfSectionsInTableView:tableView];
} else {
originalNumberOfsections = 1;
}
currentRows = 0;
totalExtraRows = 0;
startAd = startPosition;
frequencyAd = frequency;
nativeAdHeight = adHeight;
display_type = displayType;
repeatableAds = NO;
[self getInbox];
// tableView.dataSource = self.nativeTableView.dataSource;
// tableView.delegate = self.nativeTableView.delegate;
}
return self;
}
- (void)refreshAdsForTableView:(UITableView *)tableView {
self.originalDataSource = nil;
self.originalDelegate = nil;
self.nativeTableView = nil;
tableView.dataSource = nil;
tableView.delegate = nil;
tableView.dataSource = self.originalVC;
tableView.delegate = self.originalVC;
self.originalDataSource = tableView.dataSource;
self.originalDelegate = tableView.delegate;
self.nativeTableView = tableView;
if ([tableView.dataSource respondsToSelector:@selector(numberOfSectionsInTableView:)]) {
originalNumberOfsections = [tableView.dataSource numberOfSectionsInTableView:tableView];
} else {
originalNumberOfsections = 1;
}
currentRows = 0;
totalExtraRows = 0;
[self getInbox];
}
-(void)setCustomCellForNativeAd:(WLCustomNativeAdTableViewCell *)cell withIdentifier:(NSString *)cellIdentifier andNibName:(NSString *)nibName {
self.customCell = cell;
self.customCellIdentifier = cellIdentifier;
self.customCellNibName = nibName;
}
-(void)setRepeatable:(BOOL)repeatable {
repeatableAds = repeatable;
if (!repeatable) {
int counter = 0;
for (int i = 0; i < originalNumberOfsections; i++) {
for (int j = 0; j < [[indexArrayOfAds objectAtIndex:i] count]; j++) {
if ([[[indexArrayOfAds objectAtIndex:i] objectAtIndex:j] isEqual:@(YES)]) {
counter++;
if (counter > offersArray.count) {
[[indexArrayOfAds objectAtIndex:i] removeObjectAtIndex:j];
}
}
}
}
[self.nativeTableView reloadData];
} else {
NSLog(@"Nothing to remove");
}
}
-(void)getInbox {
[[Warply sharedService] getInboxWithSuccessBlock:^(NSArray *list) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"(display_type == '%@')", display_type]];
offersArray = [list filteredArrayUsingPredicate:predicate];
if (offersArray.count > 0) {
[self setupNewRowsPerSection];
[self setRepeatable:repeatableAds];
self.nativeTableView.dataSource = self;
self.nativeTableView.delegate = self;
[self.nativeTableView reloadData];
}
} failureBlock:^(NSError *error) {
//
}];
}
#pragma mark - Original IndexPath & Helpers
-(NSIndexPath *)getOriginalIndexPath:(NSIndexPath *)indexPath {
int extraRows = 0;
for (int i = 0; i < indexPath.row; i++) {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:i] isEqual:@(YES)]) {
extraRows++;
}
}
return [NSIndexPath indexPathForRow:indexPath.row - extraRows inSection:indexPath.section];
}
- (void)setupNewRowsPerSection {
indexArrayOfAds = [NSMutableArray array];
int count = 0;
for (int i = 0; i < originalNumberOfsections; i++) {
NSMutableArray *newRows = [NSMutableArray array];
NSInteger total = [self totalRowsWithAdsForSection:i];
for (int j = 0; j < total; j++) {
if (count == startAd || (count > startAd && (count - startAd)%(frequencyAd + 1) == 0)) {
[newRows addObject:@(YES)];
} else {
[newRows addObject:@(NO)];
}
count++;
}
[indexArrayOfAds addObject:newRows];
}
}
-(NSInteger)totalRowsWithAdsForSection:(int)section {
NSInteger originalRows = [self.originalDataSource tableView:self.nativeTableView numberOfRowsInSection:section];
currentRows += originalRows;
if (currentRows < startAd) {
return originalRows;
} else {
if (startAd + 1 >= currentRows - originalRows && startAd + 1 <= currentRows) {
NSInteger extraRows = (currentRows - startAd)/frequencyAd + 1;
totalExtraRows += extraRows;
return extraRows + originalRows;
} else {
NSInteger extraRowsSoFar = (currentRows - startAd)/frequencyAd + 1;
NSInteger extraRowsForSection = extraRowsSoFar - totalExtraRows;
totalExtraRows += extraRowsForSection;
return originalRows + extraRowsForSection;
}
}
}
-(int)getIndexOfAd:(NSIndexPath *)indexPath {
int adsCount = 0;
for (int i = 0; i < indexPath.section + 1; i++) {
int rows = 0;
if (indexPath.section > i) {
rows = (int)[[indexArrayOfAds objectAtIndex:i] count];
} else {
rows = (int)indexPath.row + 1;
}
for (int j = 0; j < rows; j++) {
if ([[[indexArrayOfAds objectAtIndex:i] objectAtIndex:j] isEqual:@(YES)]) {
adsCount++;
}
}
}
if (adsCount == offersArray.count) {
return adsCount-1;
} else {
return adsCount%offersArray.count - 1;
}
}
#pragma mark - TableView Datasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return originalNumberOfsections;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [[indexArrayOfAds objectAtIndex:section] count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
if (self.customCell) {
NSString *customIdentifier = [NSString stringWithFormat:@"%@", self.customCellIdentifier];
WLCustomNativeAdTableViewCell *customCell = (WLCustomNativeAdTableViewCell *)[tableView dequeueReusableCellWithIdentifier:customIdentifier];
if (self.customCellNibName) {
if (customCell == nil) {
customCell = [[[NSBundle mainBundle] loadNibNamed:[NSString stringWithFormat:@"%@", self.customCellNibName] owner:self options:nil] objectAtIndex:0];
}
}
if (offersArray.count > 0) {
WLInboxItem *item = (WLInboxItem *)offersArray[[self getIndexOfAd:indexPath]];
[customCell setupCustomCell:item];
}
[WLAnalyticsManager logEventWithEventId:[NSString stringWithFormat:@"native_campaign_view:%@",customCell.item.session_uuid] pageId:@"" actionMetadata:nil];
NSLog(@"LOG EVENT with Event ID : %@", [NSString stringWithFormat:@"native_campaign_view:%@", customCell.item.session_uuid]);
return customCell;
} else {
WLNativeAdTableViewCell *cell = (WLNativeAdTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"nativeCell"];
if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:@"WLNativeAdTableViewCell" owner:self options:nil] objectAtIndex:0];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
if (offersArray.count > 0) {
WLInboxItem *item = (WLInboxItem *)offersArray[[self getIndexOfAd:indexPath]];
if ([item.display_type isEqualToString:@"list"]) {
[cell setupCellWithItem:item];
// [cell loadContentwithURL:[item getPageURL]];
} else if ([item.display_type isEqualToString:@"feed"]){
[cell loadContentwithURL:[item getPageURL]];
}
}
[WLAnalyticsManager logEventWithEventId:[NSString stringWithFormat:@"native_campaign_view:%@", cell.item.session_uuid] pageId:@"" actionMetadata:nil];
NSLog(@"LOG EVENT with Event ID : %@", [NSString stringWithFormat:@"native_campaign_view:%@", cell.item.session_uuid]);
return cell;
}
} else {
UITableViewCell *original = [self.originalDataSource tableView:self.nativeTableView cellForRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
original.selectionStyle = UITableViewCellSelectionStyleNone;
return original;
}
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
return NO;
}
else {
if ([self.originalDataSource respondsToSelector:@selector(tableView:canEditRowAtIndexPath:)]) {
return [self.originalDataSource tableView:self.nativeTableView canEditRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
return YES;
}
-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self.originalDataSource respondsToSelector:@selector(tableView:canMoveRowAtIndexPath:)]) {
return [self.originalDataSource tableView:self.nativeTableView canMoveRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
return NO;
}
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
if ([[[indexArrayOfAds objectAtIndex:sourceIndexPath.section] objectAtIndex:sourceIndexPath.row] isEqual:@(YES)]) {
return;
}
else {
if ([self.originalDataSource respondsToSelector:@selector(tableView:moveRowAtIndexPath:toIndexPath:)]) {
[self.originalDataSource tableView:self.nativeTableView moveRowAtIndexPath:[self getOriginalIndexPath:sourceIndexPath] toIndexPath:[self getOriginalIndexPath:destinationIndexPath]];
}
}
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self.originalDataSource respondsToSelector:@selector(tableView:commitEditingStyle:forRowAtIndexPath:)]) {
[self.originalDataSource tableView:self.nativeTableView commitEditingStyle:editingStyle forRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if ([self.originalDataSource respondsToSelector:@selector(tableView:titleForHeaderInSection:)]) {
return [self.originalDataSource tableView:self.nativeTableView titleForHeaderInSection:section];
}
return nil;
}
-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
if ([self.originalDataSource respondsToSelector:@selector(tableView:titleForFooterInSection:)]) {
return [self.originalDataSource tableView:self.nativeTableView titleForFooterInSection:section];
}
return nil;
}
#pragma mark - TableView Delegate
-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
// NSLog(@"Ad accessory button pressed pressed");
}
else {
if ([self.originalDelegate respondsToSelector:@selector(tableView:accessoryButtonTappedForRowWithIndexPath:)]) {
[self.originalDelegate tableView:self.nativeTableView accessoryButtonTappedForRowWithIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
}
-(BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
return NO;
}
else {
if ([self.originalDelegate respondsToSelector:@selector(tableView:canPerformAction:forRowAtIndexPath:withSender:)]) {
return [self.originalDelegate tableView:self.nativeTableView canPerformAction:(SEL)action forRowAtIndexPath:[self getOriginalIndexPath:indexPath] withSender:sender];
}
}
return NO;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
//NSLog(@"Will display Ad cell");
}
else {
if ([self.originalDelegate respondsToSelector:@selector(tableView:willDisplayCell:forRowAtIndexPath:)]) {
[self.originalDelegate tableView:self.nativeTableView willDisplayCell:cell forRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
}
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self.originalDelegate respondsToSelector:@selector(tableView:didEndDisplayingCell:forRowAtIndexPath:)]) {
[self.originalDelegate tableView:self.nativeTableView didEndDisplayingCell:cell forRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
-(NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self.originalDelegate respondsToSelector:@selector(tableView:editActionsForRowAtIndexPath:)]) {
return [self.originalDelegate tableView:self.nativeTableView editActionsForRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
return nil;
}
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self.originalDelegate respondsToSelector:@selector(tableView:editingStyleForRowAtIndexPath:)]) {
return [self.originalDelegate tableView:self.nativeTableView editingStyleForRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
return UITableViewCellEditingStyleNone;
}
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self.originalDelegate respondsToSelector:@selector(tableView:estimatedHeightForRowAtIndexPath:)]) {
return [self.originalDelegate tableView:self.nativeTableView estimatedHeightForRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
return 80;
}
-(NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self.originalDelegate respondsToSelector:@selector(tableView:indentationLevelForRowAtIndexPath:)]) {
return [self.originalDelegate tableView:self.nativeTableView indentationLevelForRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
return 2;
}
-(void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
if ([self.originalDelegate respondsToSelector:@selector(tableView:performAction:forRowAtIndexPath:withSender:)]) {
[self.originalDelegate tableView:self.nativeTableView performAction:(SEL)action forRowAtIndexPath:[self getOriginalIndexPath:indexPath] withSender:sender];
}
return;
}
-(BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self.originalDelegate respondsToSelector:@selector(tableView:shouldShowMenuForRowAtIndexPath:)]) {
return [self.originalDelegate tableView:self.nativeTableView shouldShowMenuForRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
return NO;
}
-(void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
// NSLog(@"Will begin editing Ad cell");
}
else {
if ([self.originalDelegate respondsToSelector:@selector(tableView:willBeginEditingRowAtIndexPath:)]) {
[self.originalDelegate tableView:self.nativeTableView willBeginEditingRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
}
-(void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self.originalDelegate respondsToSelector:@selector(tableView:didEndEditingRowAtIndexPath:)]) {
[self.originalDelegate tableView:self.nativeTableView didEndEditingRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
-(void)tableView:(UITableView *)tableView didHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self.originalDelegate respondsToSelector:@selector(tableView:didHighlightRowAtIndexPath:)]) {
[self.originalDelegate tableView:self.nativeTableView didHighlightRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
-(void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self.originalDelegate respondsToSelector:@selector(tableView:didUnhighlightRowAtIndexPath:)]) {
[self.originalDelegate tableView:self.nativeTableView didUnhighlightRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
WLInboxItem *item = (WLInboxItem *)offersArray[[self getIndexOfAd:indexPath]];
if ([item.display_type isEqualToString:@"list"]) {
return nativeAdHeight;
} else if ([item.display_type isEqualToString:@"feed"]){
return 300;
}
return nativeAdHeight;
} else {
if ([self.originalDelegate respondsToSelector:@selector(tableView:heightForRowAtIndexPath:)]) {
return [self.originalDelegate tableView:self.nativeTableView heightForRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
return tableView.rowHeight;
}
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
// NSLog(@"Will select ad");
}
else {
if ([self.originalDelegate respondsToSelector:@selector(tableView:willSelectRowAtIndexPath:)]) {
[self.originalDelegate tableView:self.nativeTableView willSelectRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
return indexPath;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
NSLog(@"Ad pressed");
if (offersArray.count > 0) {
WLInboxItem *item = (WLInboxItem *)offersArray[[self getIndexOfAd:indexPath]];
if ([[self delegate] respondsToSelector:@selector(nativeAdDidSelectWithItem:)]) {
[[self delegate] nativeAdDidSelectWithItem:item];
}
[WLAnalyticsManager logEventWithEventId:[NSString stringWithFormat:@"native_campaign_click:%@", item.session_uuid] pageId:@"" actionMetadata:nil];
NSLog(@"LOG EVENT with Event ID : %@", [NSString stringWithFormat:@"native_campaign_click:%@", item.session_uuid]);
}
}
else {
if ([self.originalDelegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)]) {
[self.originalDelegate tableView:self.nativeTableView didSelectRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
// NSLog(@"Ad deselected");
}
else {
if ([self.originalDelegate respondsToSelector:@selector(tableView:didDeselectRowAtIndexPath:)]) {
[self.originalDelegate tableView:self.nativeTableView didDeselectRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
}
-(NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([[[indexArrayOfAds objectAtIndex:indexPath.section] objectAtIndex:indexPath.row] isEqual:@(YES)]) {
//NSLog(@"Will deselect ad");
}
else {
if ([self.originalDelegate respondsToSelector:@selector(tableView:willDeselectRowAtIndexPath:)]) {
[self.originalDelegate tableView:self.nativeTableView willDeselectRowAtIndexPath:[self getOriginalIndexPath:indexPath]];
}
}
return indexPath;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
if ([self.originalDelegate respondsToSelector:@selector(tableView:viewForFooterInSection:)]) {
return [self.originalDelegate tableView:self.nativeTableView viewForFooterInSection:section];
}
return [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
if ([self.originalDelegate respondsToSelector:@selector(tableView:viewForHeaderInSection:)]) {
return [self.originalDelegate tableView:self.nativeTableView viewForHeaderInSection:section];
}
return [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
if ([self.originalDelegate respondsToSelector:@selector(tableView:heightForHeaderInSection:)]) {
return [self.originalDelegate tableView:self.nativeTableView heightForHeaderInSection:section];
}
if ([self.originalDelegate respondsToSelector:@selector(tableView:viewForHeaderInSection:)]) {
UIView *header = (UIView *)[self.originalDelegate tableView:self.nativeTableView viewForHeaderInSection:section];
return header.bounds.size.height;
}
return 0;
}
//-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section {
// if ([self.originalDelegate respondsToSelector:@selector(tableView:estimatedHeightForHeaderInSection:)]) {
// return [self.originalDelegate tableView:self.nativeTableView estimatedHeightForHeaderInSection:section];
// }
// return 0;
//}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
if ([self.originalDelegate respondsToSelector:@selector(tableView:heightForFooterInSection:)]) {
return [self.originalDelegate tableView:self.nativeTableView heightForFooterInSection:section];
}
if ([self.originalDelegate respondsToSelector:@selector(tableView:viewForFooterInSection:)]) {
UIView *footer = (UIView *)[self.originalDelegate tableView:self.nativeTableView viewForFooterInSection:section];
return footer.bounds.size.height;
}
return 0;
}
//-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section {
// if ([self.originalDelegate respondsToSelector:@selector(tableView:estimatedHeightForFooterInSection:)]) {
// return [self.originalDelegate tableView:self.nativeTableView estimatedHeightForFooterInSection:section];
// }
// return 0;
//}
-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
if ([self.originalDelegate respondsToSelector:@selector(tableView:willDisplayHeaderView:forSection:)]) {
[self.originalDelegate tableView:self.nativeTableView willDisplayHeaderView:view forSection:section];
}
}
-(void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section {
if ([self.originalDelegate respondsToSelector:@selector(tableView:didEndDisplayingHeaderView:forSection:)]) {
[self.originalDelegate tableView:self.nativeTableView didEndDisplayingHeaderView:view forSection:section];
}
}
-(void)tableView:(UITableView *)tableView willDisplayFooterView:(UIView *)view forSection:(NSInteger)section {
if ([self.originalDelegate respondsToSelector:@selector(tableView:willDisplayFooterView:forSection:)]) {
[self.originalDelegate tableView:self.nativeTableView willDisplayFooterView:view forSection:section];
}
}
-(void)tableView:(UITableView *)tableView didEndDisplayingFooterView:(UIView *)view forSection:(NSInteger)section {
if ([self.originalDelegate respondsToSelector:@selector(tableView:didEndDisplayingFooterView:forSection:)]) {
[self.originalDelegate tableView:self.nativeTableView didEndDisplayingFooterView:view forSection:section];
}
}
@end
//
// WLNativeVideoTableViewCell.h
// DemoApp
//
// Created by Nick Xirotyris on 2/2/16.
// Copyright © 2016 YC. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface WLNativeVideoTableViewCell : UITableViewCell
@end
//
// WLNativeVideoTableViewCell.m
// DemoApp
//
// Created by Nick Xirotyris on 2/2/16.
// Copyright © 2016 YC. All rights reserved.
//
#import "WLNativeVideoTableViewCell.h"
#import <AVFoundation/AVFoundation.h>
@implementation WLNativeVideoTableViewCell
- (void)awakeFromNib {
// Initialization code
[super awakeFromNib];
}
- (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" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="9531" systemVersion="15D21" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="9529"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view contentMode="scaleToFill" id="iN0-l3-epB" customClass="WLNativeVideoTableViewCell">
<rect key="frame" x="0.0" y="0.0" width="260" height="260"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<freeformSimulatedSizeMetrics key="simulatedDestinationMetrics"/>
<point key="canvasLocation" x="476.5" y="376"/>
</view>
</objects>
</document>
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 55;
objects = {
/* Begin PBXBuildFile section */
E6D8DE6D27A942010006A3A9 /* WarplySDKFrameworkIOS.docc in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE6C27A942010006A3A9 /* WarplySDKFrameworkIOS.docc */; };
E6D8DE6E27A942010006A3A9 /* WarplySDKFrameworkIOS.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE6B27A942010006A3A9 /* WarplySDKFrameworkIOS.h */; settings = {ATTRIBUTES = (Public, ); }; };
E6D8DEEE27A942920006A3A9 /* WarplyReactMethods.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE7527A942910006A3A9 /* WarplyReactMethods.m */; };
E6D8DEEF27A942920006A3A9 /* WarplyReactMethods.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE7627A942910006A3A9 /* WarplyReactMethods.h */; };
E6D8DEF027A942920006A3A9 /* WLNativeAdCollectionViewCell.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE7927A942910006A3A9 /* WLNativeAdCollectionViewCell.h */; };
E6D8DEF127A942920006A3A9 /* WLNativeVideoTableViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE7A27A942910006A3A9 /* WLNativeVideoTableViewCell.xib */; };
E6D8DEF227A942920006A3A9 /* WLNativeAdTableViewCell.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE7B27A942910006A3A9 /* WLNativeAdTableViewCell.h */; };
E6D8DEF327A942920006A3A9 /* WLNativeVideoTableViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE7C27A942910006A3A9 /* WLNativeVideoTableViewCell.m */; };
E6D8DEF427A942920006A3A9 /* WLCustomNativeCollectionViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE7D27A942910006A3A9 /* WLCustomNativeCollectionViewCell.m */; };
E6D8DEF527A942920006A3A9 /* WLNativeAdsTableMode.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE7E27A942910006A3A9 /* WLNativeAdsTableMode.m */; };
E6D8DEF627A942920006A3A9 /* WLCustomNativeAdTableViewCell.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE7F27A942910006A3A9 /* WLCustomNativeAdTableViewCell.h */; };
E6D8DEF727A942920006A3A9 /* WLNativeAdsCollectionMode.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE8027A942910006A3A9 /* WLNativeAdsCollectionMode.m */; };
E6D8DEF827A942920006A3A9 /* WLNativeAdTableViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE8127A942910006A3A9 /* WLNativeAdTableViewCell.m */; };
E6D8DEF927A942920006A3A9 /* WLNativeAdCollectionViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE8227A942910006A3A9 /* WLNativeAdCollectionViewCell.m */; };
E6D8DEFA27A942920006A3A9 /* WLNativeAdTableViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE8327A942910006A3A9 /* WLNativeAdTableViewCell.xib */; };
E6D8DEFB27A942920006A3A9 /* WLNativeAdCollectionViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE8427A942910006A3A9 /* WLNativeAdCollectionViewCell.xib */; };
E6D8DEFC27A942920006A3A9 /* WLCustomNativeAdTableViewCell.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE8527A942910006A3A9 /* WLCustomNativeAdTableViewCell.m */; };
E6D8DEFD27A942920006A3A9 /* WLNativeAdsTableMode.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE8627A942910006A3A9 /* WLNativeAdsTableMode.h */; };
E6D8DEFE27A942920006A3A9 /* WLCustomNativeCollectionViewCell.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE8727A942910006A3A9 /* WLCustomNativeCollectionViewCell.h */; };
E6D8DEFF27A942920006A3A9 /* WLNativeVideoTableViewCell.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE8827A942910006A3A9 /* WLNativeVideoTableViewCell.h */; };
E6D8DF0027A942920006A3A9 /* WLNativeAdsCollectionMode.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE8927A942910006A3A9 /* WLNativeAdsCollectionMode.h */; };
E6D8DF0127A942920006A3A9 /* WLBeacon.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE8B27A942910006A3A9 /* WLBeacon.h */; };
E6D8DF0227A942920006A3A9 /* WLBaseItem.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE8C27A942910006A3A9 /* WLBaseItem.h */; };
E6D8DF0327A942920006A3A9 /* WLInboxItemViewController.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE8D27A942910006A3A9 /* WLInboxItemViewController.h */; };
E6D8DF0427A942920006A3A9 /* WLInboxItem.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE8E27A942910006A3A9 /* WLInboxItem.m */; };
E6D8DF0527A942920006A3A9 /* WLAPSItem.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE8F27A942910006A3A9 /* WLAPSItem.h */; };
E6D8DF0627A942920006A3A9 /* WLBeacon.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE9027A942910006A3A9 /* WLBeacon.m */; };
E6D8DF0727A942920006A3A9 /* WLInboxItemViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE9127A942910006A3A9 /* WLInboxItemViewController.m */; };
E6D8DF0827A942920006A3A9 /* WLBaseItem.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE9227A942910006A3A9 /* WLBaseItem.m */; };
E6D8DF0927A942920006A3A9 /* WLInboxItem.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DE9327A942910006A3A9 /* WLInboxItem.h */; };
E6D8DF0A27A942920006A3A9 /* WLAPSItem.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE9427A942910006A3A9 /* WLAPSItem.m */; };
E6D8DF0B27A942920006A3A9 /* WLEvent.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE9527A942910006A3A9 /* WLEvent.m */; };
E6D8DF0C27A942920006A3A9 /* warp_white_back_button@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE9727A942910006A3A9 /* warp_white_back_button@2x.png */; };
E6D8DF0D27A942920006A3A9 /* warp_white_forward_button.png in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE9827A942910006A3A9 /* warp_white_forward_button.png */; };
E6D8DF0E27A942920006A3A9 /* warp_white_back_button.png in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE9927A942910006A3A9 /* warp_white_back_button.png */; };
E6D8DF0F27A942920006A3A9 /* warp_white_close_button@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE9A27A942910006A3A9 /* warp_white_close_button@2x.png */; };
E6D8DF1027A942920006A3A9 /* warp_white_forward_button@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE9B27A942910006A3A9 /* warp_white_forward_button@2x.png */; };
E6D8DF1127A942920006A3A9 /* warp_white_close_button.png in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DE9C27A942910006A3A9 /* warp_white_close_button.png */; };
E6D8DF1227A942920006A3A9 /* WLPushManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE9E27A942910006A3A9 /* WLPushManager.m */; };
E6D8DF1327A942920006A3A9 /* WLBeaconManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DE9F27A942910006A3A9 /* WLBeaconManager.m */; };
E6D8DF1427A942920006A3A9 /* WLLocationManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEA027A942910006A3A9 /* WLLocationManager.m */; };
E6D8DF1527A942920006A3A9 /* WLAnalyticsManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEA127A942910006A3A9 /* WLAnalyticsManager.h */; };
E6D8DF1627A942920006A3A9 /* WLUserManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEA227A942910006A3A9 /* WLUserManager.h */; };
E6D8DF1727A942920006A3A9 /* WLBeaconManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEA327A942910006A3A9 /* WLBeaconManager.h */; };
E6D8DF1827A942920006A3A9 /* WLPushManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEA427A942910006A3A9 /* WLPushManager.h */; };
E6D8DF1927A942920006A3A9 /* WLAnalyticsManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEA527A942910006A3A9 /* WLAnalyticsManager.m */; };
E6D8DF1A27A942920006A3A9 /* WLLocationManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEA627A942910006A3A9 /* WLLocationManager.h */; };
E6D8DF1B27A942920006A3A9 /* WLUserManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEA727A942910006A3A9 /* WLUserManager.m */; };
E6D8DF1C27A942920006A3A9 /* WLUtils.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEA927A942910006A3A9 /* WLUtils.m */; };
E6D8DF1D27A942920006A3A9 /* UIViewController+WLAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEAA27A942910006A3A9 /* UIViewController+WLAdditions.h */; };
E6D8DF1E27A942920006A3A9 /* UIViewController+WLAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEAB27A942910006A3A9 /* UIViewController+WLAdditions.m */; };
E6D8DF1F27A942920006A3A9 /* WLUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEAC27A942910006A3A9 /* WLUtils.h */; };
E6D8DF2027A942920006A3A9 /* Warply.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEAD27A942910006A3A9 /* Warply.m */; };
E6D8DF2127A942920006A3A9 /* WLAPPActionHandler.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEAF27A942910006A3A9 /* WLAPPActionHandler.m */; };
E6D8DF2227A942920006A3A9 /* WLSMSActionHanlder.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEB027A942910006A3A9 /* WLSMSActionHanlder.h */; };
E6D8DF2327A942920006A3A9 /* WLSMSActionHandlerDeprecated.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEB127A942910006A3A9 /* WLSMSActionHandlerDeprecated.m */; };
E6D8DF2427A942920006A3A9 /* WLSMSActionHandlerDeprecated.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEB227A942910006A3A9 /* WLSMSActionHandlerDeprecated.h */; };
E6D8DF2527A942920006A3A9 /* WLSMSActionHanlder.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEB327A942910006A3A9 /* WLSMSActionHanlder.m */; };
E6D8DF2627A942920006A3A9 /* WLAPPActionHandler.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEB427A942910006A3A9 /* WLAPPActionHandler.h */; };
E6D8DF2727A942920006A3A9 /* WLGlobals.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEB527A942910006A3A9 /* WLGlobals.h */; };
E6D8DF2827A942920006A3A9 /* NSString+SSToolkitAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEB827A942910006A3A9 /* NSString+SSToolkitAdditions.h */; };
E6D8DF2927A942920006A3A9 /* NSData+SSToolkitAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEB927A942910006A3A9 /* NSData+SSToolkitAdditions.m */; };
E6D8DF2A27A942920006A3A9 /* NSData+SSToolkitAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEBA27A942910006A3A9 /* NSData+SSToolkitAdditions.h */; };
E6D8DF2B27A942920006A3A9 /* NSString+SSToolkitAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEBB27A942910006A3A9 /* NSString+SSToolkitAdditions.m */; };
E6D8DF2C27A942920006A3A9 /* UIProgressView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEBD27A942910006A3A9 /* UIProgressView+AFNetworking.m */; };
E6D8DF2D27A942920006A3A9 /* UIButton+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEBE27A942910006A3A9 /* UIButton+AFNetworking.h */; };
E6D8DF2E27A942920006A3A9 /* UIRefreshControl+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEBF27A942910006A3A9 /* UIRefreshControl+AFNetworking.m */; };
E6D8DF2F27A942920006A3A9 /* UIImageView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEC027A942910006A3A9 /* UIImageView+AFNetworking.h */; };
E6D8DF3027A942920006A3A9 /* AFImageDownloader.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEC127A942910006A3A9 /* AFImageDownloader.h */; };
E6D8DF3127A942920006A3A9 /* AFNetworkActivityIndicatorManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEC227A942910006A3A9 /* AFNetworkActivityIndicatorManager.m */; };
E6D8DF3227A942920006A3A9 /* AFAutoPurgingImageCache.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEC327A942910006A3A9 /* AFAutoPurgingImageCache.h */; };
E6D8DF3327A942920006A3A9 /* UIWebView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEC427A942910006A3A9 /* UIWebView+AFNetworking.h */; };
E6D8DF3427A942920006A3A9 /* UIActivityIndicatorView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEC527A942910006A3A9 /* UIActivityIndicatorView+AFNetworking.h */; };
E6D8DF3527A942920006A3A9 /* UIImage+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEC627A942910006A3A9 /* UIImage+AFNetworking.h */; };
E6D8DF3627A942920006A3A9 /* UIProgressView+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEC727A942910006A3A9 /* UIProgressView+AFNetworking.h */; };
E6D8DF3727A942920006A3A9 /* UIImageView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEC827A942910006A3A9 /* UIImageView+AFNetworking.m */; };
E6D8DF3827A942920006A3A9 /* UIKit+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEC927A942910006A3A9 /* UIKit+AFNetworking.h */; };
E6D8DF3927A942920006A3A9 /* UIRefreshControl+AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DECA27A942910006A3A9 /* UIRefreshControl+AFNetworking.h */; };
E6D8DF3A27A942920006A3A9 /* UIButton+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DECB27A942910006A3A9 /* UIButton+AFNetworking.m */; };
E6D8DF3B27A942920006A3A9 /* UIActivityIndicatorView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DECC27A942910006A3A9 /* UIActivityIndicatorView+AFNetworking.m */; };
E6D8DF3C27A942920006A3A9 /* UIWebView+AFNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DECD27A942910006A3A9 /* UIWebView+AFNetworking.m */; };
E6D8DF3D27A942920006A3A9 /* AFAutoPurgingImageCache.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DECE27A942910006A3A9 /* AFAutoPurgingImageCache.m */; };
E6D8DF3E27A942920006A3A9 /* AFNetworkActivityIndicatorManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DECF27A942910006A3A9 /* AFNetworkActivityIndicatorManager.h */; };
E6D8DF3F27A942920006A3A9 /* AFImageDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DED027A942910006A3A9 /* AFImageDownloader.m */; };
E6D8DF4027A942920006A3A9 /* AFSecurityPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DED227A942910006A3A9 /* AFSecurityPolicy.h */; };
E6D8DF4127A942920006A3A9 /* AFNetworkReachabilityManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DED327A942910006A3A9 /* AFNetworkReachabilityManager.h */; };
E6D8DF4227A942920006A3A9 /* AFURLSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DED427A942910006A3A9 /* AFURLSessionManager.h */; };
E6D8DF4327A942920006A3A9 /* AFURLRequestSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DED527A942910006A3A9 /* AFURLRequestSerialization.h */; };
E6D8DF4427A942920006A3A9 /* AFURLResponseSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DED627A942910006A3A9 /* AFURLResponseSerialization.m */; };
E6D8DF4527A942920006A3A9 /* AFHTTPSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DED727A942910006A3A9 /* AFHTTPSessionManager.m */; };
E6D8DF4627A942920006A3A9 /* AFURLResponseSerialization.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DED827A942910006A3A9 /* AFURLResponseSerialization.h */; };
E6D8DF4727A942920006A3A9 /* AFURLSessionManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DED927A942910006A3A9 /* AFURLSessionManager.m */; };
E6D8DF4827A942920006A3A9 /* AFURLRequestSerialization.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEDA27A942910006A3A9 /* AFURLRequestSerialization.m */; };
E6D8DF4927A942920006A3A9 /* AFNetworking.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEDB27A942910006A3A9 /* AFNetworking.h */; };
E6D8DF4A27A942920006A3A9 /* AFNetworkReachabilityManager.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEDC27A942910006A3A9 /* AFNetworkReachabilityManager.m */; };
E6D8DF4B27A942920006A3A9 /* AFSecurityPolicy.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEDD27A942910006A3A9 /* AFSecurityPolicy.m */; };
E6D8DF4C27A942920006A3A9 /* AFHTTPSessionManager.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEDE27A942910006A3A9 /* AFHTTPSessionManager.h */; };
E6D8DF4D27A942920006A3A9 /* FMDatabase.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEE027A942910006A3A9 /* FMDatabase.h */; };
E6D8DF4E27A942920006A3A9 /* FMDatabaseQueue.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEE127A942910006A3A9 /* FMDatabaseQueue.m */; };
E6D8DF4F27A942920006A3A9 /* FMResultSet.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEE227A942910006A3A9 /* FMResultSet.h */; };
E6D8DF5027A942920006A3A9 /* FMDatabasePool.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEE327A942910006A3A9 /* FMDatabasePool.h */; };
E6D8DF5127A942920006A3A9 /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEE427A942910006A3A9 /* FMDatabaseAdditions.m */; };
E6D8DF5227A942920006A3A9 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEE527A942910006A3A9 /* FMDatabase.m */; };
E6D8DF5327A942920006A3A9 /* FMDatabaseQueue.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEE627A942910006A3A9 /* FMDatabaseQueue.h */; };
E6D8DF5427A942920006A3A9 /* FMDB.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEE727A942910006A3A9 /* FMDB.h */; };
E6D8DF5527A942920006A3A9 /* FMDatabaseAdditions.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEE827A942910006A3A9 /* FMDatabaseAdditions.h */; };
E6D8DF5627A942920006A3A9 /* FMDatabasePool.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEE927A942910006A3A9 /* FMDatabasePool.m */; };
E6D8DF5727A942920006A3A9 /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DEEA27A942910006A3A9 /* FMResultSet.m */; };
E6D8DF5827A942920006A3A9 /* WLEvent.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEEB27A942910006A3A9 /* WLEvent.h */; };
E6D8DF5927A942920006A3A9 /* Warply.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DEEC27A942910006A3A9 /* Warply.h */; };
E6D8DF5A27A942920006A3A9 /* Media.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = E6D8DEED27A942920006A3A9 /* Media.xcassets */; };
E6D8DF5F27A9429E0006A3A9 /* ProfileViewInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DF5B27A9429E0006A3A9 /* ProfileViewInterface.swift */; };
E6D8DF6027A9429E0006A3A9 /* MyApi.m in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DF5C27A9429E0006A3A9 /* MyApi.m */; };
E6D8DF6127A9429E0006A3A9 /* ProfileView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6D8DF5D27A9429E0006A3A9 /* ProfileView.swift */; };
E6D8DF6227A9429E0006A3A9 /* MyApi.h in Headers */ = {isa = PBXBuildFile; fileRef = E6D8DF5E27A9429E0006A3A9 /* MyApi.h */; settings = {ATTRIBUTES = (Public, ); }; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
E6D8DE6827A942010006A3A9 /* WarplySDKFrameworkIOS.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = WarplySDKFrameworkIOS.framework; sourceTree = BUILT_PRODUCTS_DIR; };
E6D8DE6B27A942010006A3A9 /* WarplySDKFrameworkIOS.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WarplySDKFrameworkIOS.h; sourceTree = "<group>"; };
E6D8DE6C27A942010006A3A9 /* WarplySDKFrameworkIOS.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = WarplySDKFrameworkIOS.docc; sourceTree = "<group>"; };
E6D8DE7527A942910006A3A9 /* WarplyReactMethods.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WarplyReactMethods.m; sourceTree = "<group>"; };
E6D8DE7627A942910006A3A9 /* WarplyReactMethods.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WarplyReactMethods.h; sourceTree = "<group>"; };
E6D8DE7927A942910006A3A9 /* WLNativeAdCollectionViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLNativeAdCollectionViewCell.h; sourceTree = "<group>"; };
E6D8DE7A27A942910006A3A9 /* WLNativeVideoTableViewCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = WLNativeVideoTableViewCell.xib; sourceTree = "<group>"; };
E6D8DE7B27A942910006A3A9 /* WLNativeAdTableViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLNativeAdTableViewCell.h; sourceTree = "<group>"; };
E6D8DE7C27A942910006A3A9 /* WLNativeVideoTableViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLNativeVideoTableViewCell.m; sourceTree = "<group>"; };
E6D8DE7D27A942910006A3A9 /* WLCustomNativeCollectionViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLCustomNativeCollectionViewCell.m; sourceTree = "<group>"; };
E6D8DE7E27A942910006A3A9 /* WLNativeAdsTableMode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLNativeAdsTableMode.m; sourceTree = "<group>"; };
E6D8DE7F27A942910006A3A9 /* WLCustomNativeAdTableViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLCustomNativeAdTableViewCell.h; sourceTree = "<group>"; };
E6D8DE8027A942910006A3A9 /* WLNativeAdsCollectionMode.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLNativeAdsCollectionMode.m; sourceTree = "<group>"; };
E6D8DE8127A942910006A3A9 /* WLNativeAdTableViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLNativeAdTableViewCell.m; sourceTree = "<group>"; };
E6D8DE8227A942910006A3A9 /* WLNativeAdCollectionViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLNativeAdCollectionViewCell.m; sourceTree = "<group>"; };
E6D8DE8327A942910006A3A9 /* WLNativeAdTableViewCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = WLNativeAdTableViewCell.xib; sourceTree = "<group>"; };
E6D8DE8427A942910006A3A9 /* WLNativeAdCollectionViewCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = WLNativeAdCollectionViewCell.xib; sourceTree = "<group>"; };
E6D8DE8527A942910006A3A9 /* WLCustomNativeAdTableViewCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLCustomNativeAdTableViewCell.m; sourceTree = "<group>"; };
E6D8DE8627A942910006A3A9 /* WLNativeAdsTableMode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLNativeAdsTableMode.h; sourceTree = "<group>"; };
E6D8DE8727A942910006A3A9 /* WLCustomNativeCollectionViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLCustomNativeCollectionViewCell.h; sourceTree = "<group>"; };
E6D8DE8827A942910006A3A9 /* WLNativeVideoTableViewCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLNativeVideoTableViewCell.h; sourceTree = "<group>"; };
E6D8DE8927A942910006A3A9 /* WLNativeAdsCollectionMode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLNativeAdsCollectionMode.h; sourceTree = "<group>"; };
E6D8DE8B27A942910006A3A9 /* WLBeacon.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLBeacon.h; sourceTree = "<group>"; };
E6D8DE8C27A942910006A3A9 /* WLBaseItem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLBaseItem.h; sourceTree = "<group>"; };
E6D8DE8D27A942910006A3A9 /* WLInboxItemViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLInboxItemViewController.h; sourceTree = "<group>"; };
E6D8DE8E27A942910006A3A9 /* WLInboxItem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLInboxItem.m; sourceTree = "<group>"; };
E6D8DE8F27A942910006A3A9 /* WLAPSItem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLAPSItem.h; sourceTree = "<group>"; };
E6D8DE9027A942910006A3A9 /* WLBeacon.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLBeacon.m; sourceTree = "<group>"; };
E6D8DE9127A942910006A3A9 /* WLInboxItemViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLInboxItemViewController.m; sourceTree = "<group>"; };
E6D8DE9227A942910006A3A9 /* WLBaseItem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLBaseItem.m; sourceTree = "<group>"; };
E6D8DE9327A942910006A3A9 /* WLInboxItem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLInboxItem.h; sourceTree = "<group>"; };
E6D8DE9427A942910006A3A9 /* WLAPSItem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLAPSItem.m; sourceTree = "<group>"; };
E6D8DE9527A942910006A3A9 /* WLEvent.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLEvent.m; sourceTree = "<group>"; };
E6D8DE9727A942910006A3A9 /* warp_white_back_button@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "warp_white_back_button@2x.png"; sourceTree = "<group>"; };
E6D8DE9827A942910006A3A9 /* warp_white_forward_button.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = warp_white_forward_button.png; sourceTree = "<group>"; };
E6D8DE9927A942910006A3A9 /* warp_white_back_button.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = warp_white_back_button.png; sourceTree = "<group>"; };
E6D8DE9A27A942910006A3A9 /* warp_white_close_button@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "warp_white_close_button@2x.png"; sourceTree = "<group>"; };
E6D8DE9B27A942910006A3A9 /* warp_white_forward_button@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "warp_white_forward_button@2x.png"; sourceTree = "<group>"; };
E6D8DE9C27A942910006A3A9 /* warp_white_close_button.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = warp_white_close_button.png; sourceTree = "<group>"; };
E6D8DE9E27A942910006A3A9 /* WLPushManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLPushManager.m; sourceTree = "<group>"; };
E6D8DE9F27A942910006A3A9 /* WLBeaconManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLBeaconManager.m; sourceTree = "<group>"; };
E6D8DEA027A942910006A3A9 /* WLLocationManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLLocationManager.m; sourceTree = "<group>"; };
E6D8DEA127A942910006A3A9 /* WLAnalyticsManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLAnalyticsManager.h; sourceTree = "<group>"; };
E6D8DEA227A942910006A3A9 /* WLUserManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLUserManager.h; sourceTree = "<group>"; };
E6D8DEA327A942910006A3A9 /* WLBeaconManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLBeaconManager.h; sourceTree = "<group>"; };
E6D8DEA427A942910006A3A9 /* WLPushManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLPushManager.h; sourceTree = "<group>"; };
E6D8DEA527A942910006A3A9 /* WLAnalyticsManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLAnalyticsManager.m; sourceTree = "<group>"; };
E6D8DEA627A942910006A3A9 /* WLLocationManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLLocationManager.h; sourceTree = "<group>"; };
E6D8DEA727A942910006A3A9 /* WLUserManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLUserManager.m; sourceTree = "<group>"; };
E6D8DEA927A942910006A3A9 /* WLUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLUtils.m; sourceTree = "<group>"; };
E6D8DEAA27A942910006A3A9 /* UIViewController+WLAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIViewController+WLAdditions.h"; sourceTree = "<group>"; };
E6D8DEAB27A942910006A3A9 /* UIViewController+WLAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIViewController+WLAdditions.m"; sourceTree = "<group>"; };
E6D8DEAC27A942910006A3A9 /* WLUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLUtils.h; sourceTree = "<group>"; };
E6D8DEAD27A942910006A3A9 /* Warply.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Warply.m; sourceTree = "<group>"; };
E6D8DEAF27A942910006A3A9 /* WLAPPActionHandler.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLAPPActionHandler.m; sourceTree = "<group>"; };
E6D8DEB027A942910006A3A9 /* WLSMSActionHanlder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLSMSActionHanlder.h; sourceTree = "<group>"; };
E6D8DEB127A942910006A3A9 /* WLSMSActionHandlerDeprecated.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLSMSActionHandlerDeprecated.m; sourceTree = "<group>"; };
E6D8DEB227A942910006A3A9 /* WLSMSActionHandlerDeprecated.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLSMSActionHandlerDeprecated.h; sourceTree = "<group>"; };
E6D8DEB327A942910006A3A9 /* WLSMSActionHanlder.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WLSMSActionHanlder.m; sourceTree = "<group>"; };
E6D8DEB427A942910006A3A9 /* WLAPPActionHandler.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLAPPActionHandler.h; sourceTree = "<group>"; };
E6D8DEB527A942910006A3A9 /* WLGlobals.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLGlobals.h; sourceTree = "<group>"; };
E6D8DEB827A942910006A3A9 /* NSString+SSToolkitAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSString+SSToolkitAdditions.h"; sourceTree = "<group>"; };
E6D8DEB927A942910006A3A9 /* NSData+SSToolkitAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSData+SSToolkitAdditions.m"; sourceTree = "<group>"; };
E6D8DEBA27A942910006A3A9 /* NSData+SSToolkitAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSData+SSToolkitAdditions.h"; sourceTree = "<group>"; };
E6D8DEBB27A942910006A3A9 /* NSString+SSToolkitAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSString+SSToolkitAdditions.m"; sourceTree = "<group>"; };
E6D8DEBD27A942910006A3A9 /* UIProgressView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIProgressView+AFNetworking.m"; sourceTree = "<group>"; };
E6D8DEBE27A942910006A3A9 /* UIButton+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIButton+AFNetworking.h"; sourceTree = "<group>"; };
E6D8DEBF27A942910006A3A9 /* UIRefreshControl+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIRefreshControl+AFNetworking.m"; sourceTree = "<group>"; };
E6D8DEC027A942910006A3A9 /* UIImageView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImageView+AFNetworking.h"; sourceTree = "<group>"; };
E6D8DEC127A942910006A3A9 /* AFImageDownloader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFImageDownloader.h; sourceTree = "<group>"; };
E6D8DEC227A942910006A3A9 /* AFNetworkActivityIndicatorManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkActivityIndicatorManager.m; sourceTree = "<group>"; };
E6D8DEC327A942910006A3A9 /* AFAutoPurgingImageCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFAutoPurgingImageCache.h; sourceTree = "<group>"; };
E6D8DEC427A942910006A3A9 /* UIWebView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIWebView+AFNetworking.h"; sourceTree = "<group>"; };
E6D8DEC527A942910006A3A9 /* UIActivityIndicatorView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIActivityIndicatorView+AFNetworking.h"; sourceTree = "<group>"; };
E6D8DEC627A942910006A3A9 /* UIImage+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImage+AFNetworking.h"; sourceTree = "<group>"; };
E6D8DEC727A942910006A3A9 /* UIProgressView+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIProgressView+AFNetworking.h"; sourceTree = "<group>"; };
E6D8DEC827A942910006A3A9 /* UIImageView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImageView+AFNetworking.m"; sourceTree = "<group>"; };
E6D8DEC927A942910006A3A9 /* UIKit+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIKit+AFNetworking.h"; sourceTree = "<group>"; };
E6D8DECA27A942910006A3A9 /* UIRefreshControl+AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIRefreshControl+AFNetworking.h"; sourceTree = "<group>"; };
E6D8DECB27A942910006A3A9 /* UIButton+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIButton+AFNetworking.m"; sourceTree = "<group>"; };
E6D8DECC27A942910006A3A9 /* UIActivityIndicatorView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIActivityIndicatorView+AFNetworking.m"; sourceTree = "<group>"; };
E6D8DECD27A942910006A3A9 /* UIWebView+AFNetworking.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIWebView+AFNetworking.m"; sourceTree = "<group>"; };
E6D8DECE27A942910006A3A9 /* AFAutoPurgingImageCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFAutoPurgingImageCache.m; sourceTree = "<group>"; };
E6D8DECF27A942910006A3A9 /* AFNetworkActivityIndicatorManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkActivityIndicatorManager.h; sourceTree = "<group>"; };
E6D8DED027A942910006A3A9 /* AFImageDownloader.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFImageDownloader.m; sourceTree = "<group>"; };
E6D8DED227A942910006A3A9 /* AFSecurityPolicy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFSecurityPolicy.h; sourceTree = "<group>"; };
E6D8DED327A942910006A3A9 /* AFNetworkReachabilityManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworkReachabilityManager.h; sourceTree = "<group>"; };
E6D8DED427A942910006A3A9 /* AFURLSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLSessionManager.h; sourceTree = "<group>"; };
E6D8DED527A942910006A3A9 /* AFURLRequestSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLRequestSerialization.h; sourceTree = "<group>"; };
E6D8DED627A942910006A3A9 /* AFURLResponseSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLResponseSerialization.m; sourceTree = "<group>"; };
E6D8DED727A942910006A3A9 /* AFHTTPSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFHTTPSessionManager.m; sourceTree = "<group>"; };
E6D8DED827A942910006A3A9 /* AFURLResponseSerialization.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFURLResponseSerialization.h; sourceTree = "<group>"; };
E6D8DED927A942910006A3A9 /* AFURLSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLSessionManager.m; sourceTree = "<group>"; };
E6D8DEDA27A942910006A3A9 /* AFURLRequestSerialization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFURLRequestSerialization.m; sourceTree = "<group>"; };
E6D8DEDB27A942910006A3A9 /* AFNetworking.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFNetworking.h; sourceTree = "<group>"; };
E6D8DEDC27A942910006A3A9 /* AFNetworkReachabilityManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFNetworkReachabilityManager.m; sourceTree = "<group>"; };
E6D8DEDD27A942910006A3A9 /* AFSecurityPolicy.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AFSecurityPolicy.m; sourceTree = "<group>"; };
E6D8DEDE27A942910006A3A9 /* AFHTTPSessionManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AFHTTPSessionManager.h; sourceTree = "<group>"; };
E6D8DEE027A942910006A3A9 /* FMDatabase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabase.h; sourceTree = "<group>"; };
E6D8DEE127A942910006A3A9 /* FMDatabaseQueue.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseQueue.m; sourceTree = "<group>"; };
E6D8DEE227A942910006A3A9 /* FMResultSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMResultSet.h; sourceTree = "<group>"; };
E6D8DEE327A942910006A3A9 /* FMDatabasePool.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabasePool.h; sourceTree = "<group>"; };
E6D8DEE427A942910006A3A9 /* FMDatabaseAdditions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabaseAdditions.m; sourceTree = "<group>"; };
E6D8DEE527A942910006A3A9 /* FMDatabase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabase.m; sourceTree = "<group>"; };
E6D8DEE627A942910006A3A9 /* FMDatabaseQueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabaseQueue.h; sourceTree = "<group>"; };
E6D8DEE727A942910006A3A9 /* FMDB.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDB.h; sourceTree = "<group>"; };
E6D8DEE827A942910006A3A9 /* FMDatabaseAdditions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FMDatabaseAdditions.h; sourceTree = "<group>"; };
E6D8DEE927A942910006A3A9 /* FMDatabasePool.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMDatabasePool.m; sourceTree = "<group>"; };
E6D8DEEA27A942910006A3A9 /* FMResultSet.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FMResultSet.m; sourceTree = "<group>"; };
E6D8DEEB27A942910006A3A9 /* WLEvent.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WLEvent.h; sourceTree = "<group>"; };
E6D8DEEC27A942910006A3A9 /* Warply.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Warply.h; sourceTree = "<group>"; };
E6D8DEED27A942920006A3A9 /* Media.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Media.xcassets; sourceTree = SOURCE_ROOT; };
E6D8DF5B27A9429E0006A3A9 /* ProfileViewInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ProfileViewInterface.swift; sourceTree = "<group>"; };
E6D8DF5C27A9429E0006A3A9 /* MyApi.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MyApi.m; sourceTree = "<group>"; };
E6D8DF5D27A9429E0006A3A9 /* ProfileView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ProfileView.swift; sourceTree = "<group>"; };
E6D8DF5E27A9429E0006A3A9 /* MyApi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MyApi.h; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
E6D8DE6527A942010006A3A9 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
E6D8DE5E27A942000006A3A9 = {
isa = PBXGroup;
children = (
E6D8DE6A27A942010006A3A9 /* WarplySDKFrameworkIOS */,
E6D8DE6927A942010006A3A9 /* Products */,
);
sourceTree = "<group>";
};
E6D8DE6927A942010006A3A9 /* Products */ = {
isa = PBXGroup;
children = (
E6D8DE6827A942010006A3A9 /* WarplySDKFrameworkIOS.framework */,
);
name = Products;
sourceTree = "<group>";
};
E6D8DE6A27A942010006A3A9 /* WarplySDKFrameworkIOS */ = {
isa = PBXGroup;
children = (
E6D8DF5E27A9429E0006A3A9 /* MyApi.h */,
E6D8DF5C27A9429E0006A3A9 /* MyApi.m */,
E6D8DF5D27A9429E0006A3A9 /* ProfileView.swift */,
E6D8DF5B27A9429E0006A3A9 /* ProfileViewInterface.swift */,
E6D8DE7427A942910006A3A9 /* Helpers */,
E6D8DEED27A942920006A3A9 /* Media.xcassets */,
E6D8DE7727A942910006A3A9 /* Warply */,
E6D8DE6B27A942010006A3A9 /* WarplySDKFrameworkIOS.h */,
E6D8DE6C27A942010006A3A9 /* WarplySDKFrameworkIOS.docc */,
);
path = WarplySDKFrameworkIOS;
sourceTree = "<group>";
};
E6D8DE7427A942910006A3A9 /* Helpers */ = {
isa = PBXGroup;
children = (
E6D8DE7527A942910006A3A9 /* WarplyReactMethods.m */,
E6D8DE7627A942910006A3A9 /* WarplyReactMethods.h */,
);
path = Helpers;
sourceTree = SOURCE_ROOT;
};
E6D8DE7727A942910006A3A9 /* Warply */ = {
isa = PBXGroup;
children = (
E6D8DE7827A942910006A3A9 /* nativeAds */,
E6D8DE8A27A942910006A3A9 /* inbox */,
E6D8DE9527A942910006A3A9 /* WLEvent.m */,
E6D8DE9627A942910006A3A9 /* resources */,
E6D8DE9D27A942910006A3A9 /* managers */,
E6D8DEA827A942910006A3A9 /* foundation */,
E6D8DEAD27A942910006A3A9 /* Warply.m */,
E6D8DEAE27A942910006A3A9 /* actions */,
E6D8DEB527A942910006A3A9 /* WLGlobals.h */,
E6D8DEB627A942910006A3A9 /* external */,
E6D8DEEB27A942910006A3A9 /* WLEvent.h */,
E6D8DEEC27A942910006A3A9 /* Warply.h */,
);
path = Warply;
sourceTree = SOURCE_ROOT;
};
E6D8DE7827A942910006A3A9 /* nativeAds */ = {
isa = PBXGroup;
children = (
E6D8DE7927A942910006A3A9 /* WLNativeAdCollectionViewCell.h */,
E6D8DE7A27A942910006A3A9 /* WLNativeVideoTableViewCell.xib */,
E6D8DE7B27A942910006A3A9 /* WLNativeAdTableViewCell.h */,
E6D8DE7C27A942910006A3A9 /* WLNativeVideoTableViewCell.m */,
E6D8DE7D27A942910006A3A9 /* WLCustomNativeCollectionViewCell.m */,
E6D8DE7E27A942910006A3A9 /* WLNativeAdsTableMode.m */,
E6D8DE7F27A942910006A3A9 /* WLCustomNativeAdTableViewCell.h */,
E6D8DE8027A942910006A3A9 /* WLNativeAdsCollectionMode.m */,
E6D8DE8127A942910006A3A9 /* WLNativeAdTableViewCell.m */,
E6D8DE8227A942910006A3A9 /* WLNativeAdCollectionViewCell.m */,
E6D8DE8327A942910006A3A9 /* WLNativeAdTableViewCell.xib */,
E6D8DE8427A942910006A3A9 /* WLNativeAdCollectionViewCell.xib */,
E6D8DE8527A942910006A3A9 /* WLCustomNativeAdTableViewCell.m */,
E6D8DE8627A942910006A3A9 /* WLNativeAdsTableMode.h */,
E6D8DE8727A942910006A3A9 /* WLCustomNativeCollectionViewCell.h */,
E6D8DE8827A942910006A3A9 /* WLNativeVideoTableViewCell.h */,
E6D8DE8927A942910006A3A9 /* WLNativeAdsCollectionMode.h */,
);
path = nativeAds;
sourceTree = "<group>";
};
E6D8DE8A27A942910006A3A9 /* inbox */ = {
isa = PBXGroup;
children = (
E6D8DE8B27A942910006A3A9 /* WLBeacon.h */,
E6D8DE8C27A942910006A3A9 /* WLBaseItem.h */,
E6D8DE8D27A942910006A3A9 /* WLInboxItemViewController.h */,
E6D8DE8E27A942910006A3A9 /* WLInboxItem.m */,
E6D8DE8F27A942910006A3A9 /* WLAPSItem.h */,
E6D8DE9027A942910006A3A9 /* WLBeacon.m */,
E6D8DE9127A942910006A3A9 /* WLInboxItemViewController.m */,
E6D8DE9227A942910006A3A9 /* WLBaseItem.m */,
E6D8DE9327A942910006A3A9 /* WLInboxItem.h */,
E6D8DE9427A942910006A3A9 /* WLAPSItem.m */,
);
path = inbox;
sourceTree = "<group>";
};
E6D8DE9627A942910006A3A9 /* resources */ = {
isa = PBXGroup;
children = (
E6D8DE9727A942910006A3A9 /* warp_white_back_button@2x.png */,
E6D8DE9827A942910006A3A9 /* warp_white_forward_button.png */,
E6D8DE9927A942910006A3A9 /* warp_white_back_button.png */,
E6D8DE9A27A942910006A3A9 /* warp_white_close_button@2x.png */,
E6D8DE9B27A942910006A3A9 /* warp_white_forward_button@2x.png */,
E6D8DE9C27A942910006A3A9 /* warp_white_close_button.png */,
);
path = resources;
sourceTree = "<group>";
};
E6D8DE9D27A942910006A3A9 /* managers */ = {
isa = PBXGroup;
children = (
E6D8DE9E27A942910006A3A9 /* WLPushManager.m */,
E6D8DE9F27A942910006A3A9 /* WLBeaconManager.m */,
E6D8DEA027A942910006A3A9 /* WLLocationManager.m */,
E6D8DEA127A942910006A3A9 /* WLAnalyticsManager.h */,
E6D8DEA227A942910006A3A9 /* WLUserManager.h */,
E6D8DEA327A942910006A3A9 /* WLBeaconManager.h */,
E6D8DEA427A942910006A3A9 /* WLPushManager.h */,
E6D8DEA527A942910006A3A9 /* WLAnalyticsManager.m */,
E6D8DEA627A942910006A3A9 /* WLLocationManager.h */,
E6D8DEA727A942910006A3A9 /* WLUserManager.m */,
);
path = managers;
sourceTree = "<group>";
};
E6D8DEA827A942910006A3A9 /* foundation */ = {
isa = PBXGroup;
children = (
E6D8DEA927A942910006A3A9 /* WLUtils.m */,
E6D8DEAA27A942910006A3A9 /* UIViewController+WLAdditions.h */,
E6D8DEAB27A942910006A3A9 /* UIViewController+WLAdditions.m */,
E6D8DEAC27A942910006A3A9 /* WLUtils.h */,
);
path = foundation;
sourceTree = "<group>";
};
E6D8DEAE27A942910006A3A9 /* actions */ = {
isa = PBXGroup;
children = (
E6D8DEAF27A942910006A3A9 /* WLAPPActionHandler.m */,
E6D8DEB027A942910006A3A9 /* WLSMSActionHanlder.h */,
E6D8DEB127A942910006A3A9 /* WLSMSActionHandlerDeprecated.m */,
E6D8DEB227A942910006A3A9 /* WLSMSActionHandlerDeprecated.h */,
E6D8DEB327A942910006A3A9 /* WLSMSActionHanlder.m */,
E6D8DEB427A942910006A3A9 /* WLAPPActionHandler.h */,
);
path = actions;
sourceTree = "<group>";
};
E6D8DEB627A942910006A3A9 /* external */ = {
isa = PBXGroup;
children = (
E6D8DEB727A942910006A3A9 /* sstoolkit */,
E6D8DEBC27A942910006A3A9 /* UIKit+AFNetworking */,
E6D8DED127A942910006A3A9 /* AFNetworking */,
E6D8DEDF27A942910006A3A9 /* fmdb */,
);
path = external;
sourceTree = "<group>";
};
E6D8DEB727A942910006A3A9 /* sstoolkit */ = {
isa = PBXGroup;
children = (
E6D8DEB827A942910006A3A9 /* NSString+SSToolkitAdditions.h */,
E6D8DEB927A942910006A3A9 /* NSData+SSToolkitAdditions.m */,
E6D8DEBA27A942910006A3A9 /* NSData+SSToolkitAdditions.h */,
E6D8DEBB27A942910006A3A9 /* NSString+SSToolkitAdditions.m */,
);
path = sstoolkit;
sourceTree = "<group>";
};
E6D8DEBC27A942910006A3A9 /* UIKit+AFNetworking */ = {
isa = PBXGroup;
children = (
E6D8DEBD27A942910006A3A9 /* UIProgressView+AFNetworking.m */,
E6D8DEBE27A942910006A3A9 /* UIButton+AFNetworking.h */,
E6D8DEBF27A942910006A3A9 /* UIRefreshControl+AFNetworking.m */,
E6D8DEC027A942910006A3A9 /* UIImageView+AFNetworking.h */,
E6D8DEC127A942910006A3A9 /* AFImageDownloader.h */,
E6D8DEC227A942910006A3A9 /* AFNetworkActivityIndicatorManager.m */,
E6D8DEC327A942910006A3A9 /* AFAutoPurgingImageCache.h */,
E6D8DEC427A942910006A3A9 /* UIWebView+AFNetworking.h */,
E6D8DEC527A942910006A3A9 /* UIActivityIndicatorView+AFNetworking.h */,
E6D8DEC627A942910006A3A9 /* UIImage+AFNetworking.h */,
E6D8DEC727A942910006A3A9 /* UIProgressView+AFNetworking.h */,
E6D8DEC827A942910006A3A9 /* UIImageView+AFNetworking.m */,
E6D8DEC927A942910006A3A9 /* UIKit+AFNetworking.h */,
E6D8DECA27A942910006A3A9 /* UIRefreshControl+AFNetworking.h */,
E6D8DECB27A942910006A3A9 /* UIButton+AFNetworking.m */,
E6D8DECC27A942910006A3A9 /* UIActivityIndicatorView+AFNetworking.m */,
E6D8DECD27A942910006A3A9 /* UIWebView+AFNetworking.m */,
E6D8DECE27A942910006A3A9 /* AFAutoPurgingImageCache.m */,
E6D8DECF27A942910006A3A9 /* AFNetworkActivityIndicatorManager.h */,
E6D8DED027A942910006A3A9 /* AFImageDownloader.m */,
);
path = "UIKit+AFNetworking";
sourceTree = "<group>";
};
E6D8DED127A942910006A3A9 /* AFNetworking */ = {
isa = PBXGroup;
children = (
E6D8DED227A942910006A3A9 /* AFSecurityPolicy.h */,
E6D8DED327A942910006A3A9 /* AFNetworkReachabilityManager.h */,
E6D8DED427A942910006A3A9 /* AFURLSessionManager.h */,
E6D8DED527A942910006A3A9 /* AFURLRequestSerialization.h */,
E6D8DED627A942910006A3A9 /* AFURLResponseSerialization.m */,
E6D8DED727A942910006A3A9 /* AFHTTPSessionManager.m */,
E6D8DED827A942910006A3A9 /* AFURLResponseSerialization.h */,
E6D8DED927A942910006A3A9 /* AFURLSessionManager.m */,
E6D8DEDA27A942910006A3A9 /* AFURLRequestSerialization.m */,
E6D8DEDB27A942910006A3A9 /* AFNetworking.h */,
E6D8DEDC27A942910006A3A9 /* AFNetworkReachabilityManager.m */,
E6D8DEDD27A942910006A3A9 /* AFSecurityPolicy.m */,
E6D8DEDE27A942910006A3A9 /* AFHTTPSessionManager.h */,
);
path = AFNetworking;
sourceTree = "<group>";
};
E6D8DEDF27A942910006A3A9 /* fmdb */ = {
isa = PBXGroup;
children = (
E6D8DEE027A942910006A3A9 /* FMDatabase.h */,
E6D8DEE127A942910006A3A9 /* FMDatabaseQueue.m */,
E6D8DEE227A942910006A3A9 /* FMResultSet.h */,
E6D8DEE327A942910006A3A9 /* FMDatabasePool.h */,
E6D8DEE427A942910006A3A9 /* FMDatabaseAdditions.m */,
E6D8DEE527A942910006A3A9 /* FMDatabase.m */,
E6D8DEE627A942910006A3A9 /* FMDatabaseQueue.h */,
E6D8DEE727A942910006A3A9 /* FMDB.h */,
E6D8DEE827A942910006A3A9 /* FMDatabaseAdditions.h */,
E6D8DEE927A942910006A3A9 /* FMDatabasePool.m */,
E6D8DEEA27A942910006A3A9 /* FMResultSet.m */,
);
path = fmdb;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXHeadersBuildPhase section */
E6D8DE6327A942010006A3A9 /* Headers */ = {
isa = PBXHeadersBuildPhase;
buildActionMask = 2147483647;
files = (
E6D8DEEF27A942920006A3A9 /* WarplyReactMethods.h in Headers */,
E6D8DF0027A942920006A3A9 /* WLNativeAdsCollectionMode.h in Headers */,
E6D8DF3027A942920006A3A9 /* AFImageDownloader.h in Headers */,
E6D8DF4927A942920006A3A9 /* AFNetworking.h in Headers */,
E6D8DF5827A942920006A3A9 /* WLEvent.h in Headers */,
E6D8DF3927A942920006A3A9 /* UIRefreshControl+AFNetworking.h in Headers */,
E6D8DF1A27A942920006A3A9 /* WLLocationManager.h in Headers */,
E6D8DF2827A942920006A3A9 /* NSString+SSToolkitAdditions.h in Headers */,
E6D8DF1627A942920006A3A9 /* WLUserManager.h in Headers */,
E6D8DF2D27A942920006A3A9 /* UIButton+AFNetworking.h in Headers */,
E6D8DF2A27A942920006A3A9 /* NSData+SSToolkitAdditions.h in Headers */,
E6D8DF4027A942920006A3A9 /* AFSecurityPolicy.h in Headers */,
E6D8DF3427A942920006A3A9 /* UIActivityIndicatorView+AFNetworking.h in Headers */,
E6D8DF2F27A942920006A3A9 /* UIImageView+AFNetworking.h in Headers */,
E6D8DF5927A942920006A3A9 /* Warply.h in Headers */,
E6D8DF5327A942920006A3A9 /* FMDatabaseQueue.h in Headers */,
E6D8DF1827A942920006A3A9 /* WLPushManager.h in Headers */,
E6D8DF5427A942920006A3A9 /* FMDB.h in Headers */,
E6D8DF0327A942920006A3A9 /* WLInboxItemViewController.h in Headers */,
E6D8DEF627A942920006A3A9 /* WLCustomNativeAdTableViewCell.h in Headers */,
E6D8DF4D27A942920006A3A9 /* FMDatabase.h in Headers */,
E6D8DF0127A942920006A3A9 /* WLBeacon.h in Headers */,
E6D8DF4C27A942920006A3A9 /* AFHTTPSessionManager.h in Headers */,
E6D8DF1727A942920006A3A9 /* WLBeaconManager.h in Headers */,
E6D8DF4127A942920006A3A9 /* AFNetworkReachabilityManager.h in Headers */,
E6D8DF0527A942920006A3A9 /* WLAPSItem.h in Headers */,
E6D8DF1D27A942920006A3A9 /* UIViewController+WLAdditions.h in Headers */,
E6D8DEF227A942920006A3A9 /* WLNativeAdTableViewCell.h in Headers */,
E6D8DF5527A942920006A3A9 /* FMDatabaseAdditions.h in Headers */,
E6D8DF5027A942920006A3A9 /* FMDatabasePool.h in Headers */,
E6D8DF2727A942920006A3A9 /* WLGlobals.h in Headers */,
E6D8DF1F27A942920006A3A9 /* WLUtils.h in Headers */,
E6D8DF0227A942920006A3A9 /* WLBaseItem.h in Headers */,
E6D8DF3527A942920006A3A9 /* UIImage+AFNetworking.h in Headers */,
E6D8DF3827A942920006A3A9 /* UIKit+AFNetworking.h in Headers */,
E6D8DF4F27A942920006A3A9 /* FMResultSet.h in Headers */,
E6D8DEFD27A942920006A3A9 /* WLNativeAdsTableMode.h in Headers */,
E6D8DF2427A942920006A3A9 /* WLSMSActionHandlerDeprecated.h in Headers */,
E6D8DF3627A942920006A3A9 /* UIProgressView+AFNetworking.h in Headers */,
E6D8DEF027A942920006A3A9 /* WLNativeAdCollectionViewCell.h in Headers */,
E6D8DF4327A942920006A3A9 /* AFURLRequestSerialization.h in Headers */,
E6D8DF2227A942920006A3A9 /* WLSMSActionHanlder.h in Headers */,
E6D8DF2627A942920006A3A9 /* WLAPPActionHandler.h in Headers */,
E6D8DF4227A942920006A3A9 /* AFURLSessionManager.h in Headers */,
E6D8DF1527A942920006A3A9 /* WLAnalyticsManager.h in Headers */,
E6D8DF6227A9429E0006A3A9 /* MyApi.h in Headers */,
E6D8DF3227A942920006A3A9 /* AFAutoPurgingImageCache.h in Headers */,
E6D8DEFE27A942920006A3A9 /* WLCustomNativeCollectionViewCell.h in Headers */,
E6D8DF0927A942920006A3A9 /* WLInboxItem.h in Headers */,
E6D8DEFF27A942920006A3A9 /* WLNativeVideoTableViewCell.h in Headers */,
E6D8DF3E27A942920006A3A9 /* AFNetworkActivityIndicatorManager.h in Headers */,
E6D8DE6E27A942010006A3A9 /* WarplySDKFrameworkIOS.h in Headers */,
E6D8DF3327A942920006A3A9 /* UIWebView+AFNetworking.h in Headers */,
E6D8DF4627A942920006A3A9 /* AFURLResponseSerialization.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXHeadersBuildPhase section */
/* Begin PBXNativeTarget section */
E6D8DE6727A942010006A3A9 /* WarplySDKFrameworkIOS */ = {
isa = PBXNativeTarget;
buildConfigurationList = E6D8DE7127A942010006A3A9 /* Build configuration list for PBXNativeTarget "WarplySDKFrameworkIOS" */;
buildPhases = (
E6D8DE6327A942010006A3A9 /* Headers */,
E6D8DE6427A942010006A3A9 /* Sources */,
E6D8DE6527A942010006A3A9 /* Frameworks */,
E6D8DE6627A942010006A3A9 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = WarplySDKFrameworkIOS;
productName = WarplySDKFrameworkIOS;
productReference = E6D8DE6827A942010006A3A9 /* WarplySDKFrameworkIOS.framework */;
productType = "com.apple.product-type.framework";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
E6D8DE5F27A942010006A3A9 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastUpgradeCheck = 1310;
TargetAttributes = {
E6D8DE6727A942010006A3A9 = {
CreatedOnToolsVersion = 13.1;
LastSwiftMigration = 1310;
};
};
};
buildConfigurationList = E6D8DE6227A942010006A3A9 /* Build configuration list for PBXProject "WarplySDKFrameworkIOS" */;
compatibilityVersion = "Xcode 13.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = E6D8DE5E27A942000006A3A9;
productRefGroup = E6D8DE6927A942010006A3A9 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
E6D8DE6727A942010006A3A9 /* WarplySDKFrameworkIOS */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
E6D8DE6627A942010006A3A9 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
E6D8DF5A27A942920006A3A9 /* Media.xcassets in Resources */,
E6D8DF1127A942920006A3A9 /* warp_white_close_button.png in Resources */,
E6D8DF0E27A942920006A3A9 /* warp_white_back_button.png in Resources */,
E6D8DF0F27A942920006A3A9 /* warp_white_close_button@2x.png in Resources */,
E6D8DF0D27A942920006A3A9 /* warp_white_forward_button.png in Resources */,
E6D8DEFA27A942920006A3A9 /* WLNativeAdTableViewCell.xib in Resources */,
E6D8DF1027A942920006A3A9 /* warp_white_forward_button@2x.png in Resources */,
E6D8DEF127A942920006A3A9 /* WLNativeVideoTableViewCell.xib in Resources */,
E6D8DEFB27A942920006A3A9 /* WLNativeAdCollectionViewCell.xib in Resources */,
E6D8DF0C27A942920006A3A9 /* warp_white_back_button@2x.png in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
E6D8DE6427A942010006A3A9 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
E6D8DF0B27A942920006A3A9 /* WLEvent.m in Sources */,
E6D8DF1E27A942920006A3A9 /* UIViewController+WLAdditions.m in Sources */,
E6D8DF2E27A942920006A3A9 /* UIRefreshControl+AFNetworking.m in Sources */,
E6D8DF4827A942920006A3A9 /* AFURLRequestSerialization.m in Sources */,
E6D8DEF327A942920006A3A9 /* WLNativeVideoTableViewCell.m in Sources */,
E6D8DF2527A942920006A3A9 /* WLSMSActionHanlder.m in Sources */,
E6D8DF5727A942920006A3A9 /* FMResultSet.m in Sources */,
E6D8DF3A27A942920006A3A9 /* UIButton+AFNetworking.m in Sources */,
E6D8DF0627A942920006A3A9 /* WLBeacon.m in Sources */,
E6D8DF2927A942920006A3A9 /* NSData+SSToolkitAdditions.m in Sources */,
E6D8DEFC27A942920006A3A9 /* WLCustomNativeAdTableViewCell.m in Sources */,
E6D8DF5F27A9429E0006A3A9 /* ProfileViewInterface.swift in Sources */,
E6D8DF4A27A942920006A3A9 /* AFNetworkReachabilityManager.m in Sources */,
E6D8DF4B27A942920006A3A9 /* AFSecurityPolicy.m in Sources */,
E6D8DF1327A942920006A3A9 /* WLBeaconManager.m in Sources */,
E6D8DF0427A942920006A3A9 /* WLInboxItem.m in Sources */,
E6D8DF5127A942920006A3A9 /* FMDatabaseAdditions.m in Sources */,
E6D8DF2127A942920006A3A9 /* WLAPPActionHandler.m in Sources */,
E6D8DF5627A942920006A3A9 /* FMDatabasePool.m in Sources */,
E6D8DF4527A942920006A3A9 /* AFHTTPSessionManager.m in Sources */,
E6D8DF3B27A942920006A3A9 /* UIActivityIndicatorView+AFNetworking.m in Sources */,
E6D8DF3727A942920006A3A9 /* UIImageView+AFNetworking.m in Sources */,
E6D8DF3127A942920006A3A9 /* AFNetworkActivityIndicatorManager.m in Sources */,
E6D8DF3D27A942920006A3A9 /* AFAutoPurgingImageCache.m in Sources */,
E6D8DF0A27A942920006A3A9 /* WLAPSItem.m in Sources */,
E6D8DF2C27A942920006A3A9 /* UIProgressView+AFNetworking.m in Sources */,
E6D8DF3C27A942920006A3A9 /* UIWebView+AFNetworking.m in Sources */,
E6D8DF1427A942920006A3A9 /* WLLocationManager.m in Sources */,
E6D8DF6027A9429E0006A3A9 /* MyApi.m in Sources */,
E6D8DF3F27A942920006A3A9 /* AFImageDownloader.m in Sources */,
E6D8DEF727A942920006A3A9 /* WLNativeAdsCollectionMode.m in Sources */,
E6D8DEF427A942920006A3A9 /* WLCustomNativeCollectionViewCell.m in Sources */,
E6D8DF2B27A942920006A3A9 /* NSString+SSToolkitAdditions.m in Sources */,
E6D8DF4727A942920006A3A9 /* AFURLSessionManager.m in Sources */,
E6D8DF1927A942920006A3A9 /* WLAnalyticsManager.m in Sources */,
E6D8DF5227A942920006A3A9 /* FMDatabase.m in Sources */,
E6D8DF1227A942920006A3A9 /* WLPushManager.m in Sources */,
E6D8DEF827A942920006A3A9 /* WLNativeAdTableViewCell.m in Sources */,
E6D8DE6D27A942010006A3A9 /* WarplySDKFrameworkIOS.docc in Sources */,
E6D8DF4427A942920006A3A9 /* AFURLResponseSerialization.m in Sources */,
E6D8DEF527A942920006A3A9 /* WLNativeAdsTableMode.m in Sources */,
E6D8DF1C27A942920006A3A9 /* WLUtils.m in Sources */,
E6D8DF1B27A942920006A3A9 /* WLUserManager.m in Sources */,
E6D8DF6127A9429E0006A3A9 /* ProfileView.swift in Sources */,
E6D8DF2027A942920006A3A9 /* Warply.m in Sources */,
E6D8DF2327A942920006A3A9 /* WLSMSActionHandlerDeprecated.m in Sources */,
E6D8DEEE27A942920006A3A9 /* WarplyReactMethods.m in Sources */,
E6D8DEF927A942920006A3A9 /* WLNativeAdCollectionViewCell.m in Sources */,
E6D8DF4E27A942920006A3A9 /* FMDatabaseQueue.m in Sources */,
E6D8DF0827A942920006A3A9 /* WLBaseItem.m in Sources */,
E6D8DF0727A942920006A3A9 /* WLInboxItemViewController.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
E6D8DE6F27A942010006A3A9 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 1;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Debug;
};
E6D8DE7027A942010006A3A9 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++17";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 1;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
VALIDATE_PRODUCT = YES;
VERSIONING_SYSTEM = "apple-generic";
VERSION_INFO_PREFIX = "";
};
name = Release;
};
E6D8DE7227A942010006A3A9 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEFINES_MODULE = YES;
DEVELOPMENT_TEAM = VW5AF53FLP;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = framework.warp.ly.WarplySDKFrameworkIOS;
PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
SKIP_INSTALL = YES;
SUPPORTS_MACCATALYST = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
E6D8DE7327A942010006A3A9 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
DEFINES_MODULE = YES;
DEVELOPMENT_TEAM = VW5AF53FLP;
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = framework.warp.ly.WarplySDKFrameworkIOS;
PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)";
SKIP_INSTALL = YES;
SUPPORTS_MACCATALYST = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
E6D8DE6227A942010006A3A9 /* Build configuration list for PBXProject "WarplySDKFrameworkIOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
E6D8DE6F27A942010006A3A9 /* Debug */,
E6D8DE7027A942010006A3A9 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
E6D8DE7127A942010006A3A9 /* Build configuration list for PBXNativeTarget "WarplySDKFrameworkIOS" */ = {
isa = XCConfigurationList;
buildConfigurations = (
E6D8DE7227A942010006A3A9 /* Debug */,
E6D8DE7327A942010006A3A9 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = E6D8DE5F27A942010006A3A9 /* Project object */;
}
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:">
</FileRef>
</Workspace>
<?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>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
<?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>SchemeUserState</key>
<dict>
<key>WarplySDKFrameworkIOS.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
</dict>
</dict>
</dict>
</plist>
//
// MyApi.h
// warplyFramework
//
// Created by Βασιλης Σκουρας on 8/12/21.
//
#ifndef MyApi_h
#define MyApi_h
#import <UIKit/UIKit.h>
@interface MyApi : NSObject
+ (void)init:(NSDictionary *)launchOptions uuid:(NSString*)uuid merchantId:(NSString*)merchantId lang:(NSString*)lang;
- (void) setToStage;
- (UIViewController *) openProfile:(UIViewController*)controller :(UIWindow*) window;
- (void) applicationDidEnterBackground:(UIApplication *)application;
- (void) applicationWillEnterForeground:(UIApplication *)application;
- (void) applicationDidBecomeActive:(UIApplication *)application;
- (void) applicationWillTerminate:(UIApplication *)application;
- (void) application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken;
- (void) application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error;
- (void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo;
- (NSMutableArray *)getProducts:(NSString *) filter;
- (NSMutableArray*)sendContact:(NSString*)name email:(NSString*)email msisdn:(NSString*)msisdn message:(NSString*)message;
- (NSMutableArray *)getContent:(NSString *)category tags:(NSArray *)tags;
- (NSMutableArray *)getMerchantCategories;
- (NSMutableArray *)getMerchants;
- (NSMutableArray *)getTagsCategories;
- (NSMutableArray *)getTags;
- (NSDictionary *)login:(NSString *)id password:(NSString *)password loginType:(NSString*) loginType;
- (NSDictionary *)register:(NSString *)id password:(NSString *)password name:(NSString*)name email:(NSString*)email segmentation:(NSNumber*)segmentation newsletter:(NSNumber*)newsletter;
- (NSDictionary *)registerAutoLogin:(NSString *)id password:(NSString *)password name:(NSString*)name email:(NSString*)email segmentation:(NSNumber*)segmentation newsletter:(NSNumber*)newsletter loginType:(NSString*)loginType;
- (NSDictionary *)refreshToken;
- (NSDictionary *)changePassword:(NSString *)oldPassword newPassword:(NSString *)newPassword;
- (NSDictionary *)getProfile;
- (NSDictionary *)editProfile:(NSString*)firstname andLastname:(NSString*)lastname andEmail:(NSString *)email andSalutation:(NSString *)salutation andMsisdn:(NSString *)msisdn andNickname:(NSString *)nickname andGender:(NSString *)gender andBirthday:(NSString *)birthday andNameDay:(NSString *)nameday andTaxID:(NSString *)taxid andProfileMetadata:(NSDictionary *)profileMetadata optin:(NSNumber *)optin newsLetter:(NSNumber *)newsletter andSMS:(NSNumber *)sms andSegmentation:(NSNumber *)segmentation andSMSSegmentation:(NSNumber *)smsSegmentation;
- (NSDictionary *)changeProfileImage:(NSString*)image andUserId:(NSString*)userId;
- (NSDictionary*) addCard:(NSString*)number andCardIssuer:(NSString*)cardIssuer andCardHolder:(NSString*)cardHolder andExpirationMonth:(NSString*)expirationMonth andExpirationYear:(NSString*)expirationYear;
- (NSDictionary*) getCards;
- (NSDictionary*) deleteCard:(NSString*)token;
- (NSDictionary*) verifyTicket:(NSString*)guid ticket:(NSString*)ticket;
- (NSDictionary*) getCoupons;
- (NSDictionary*) getTransactionHistory;
- (NSDictionary*) getPointsHistory;
- (NSDictionary*)addAddress:(NSString*)friendlyName andAddressName:(NSString*)addressName andAddressNumber:(NSString*)addressNumber andPostalCode:(NSString*)postalCode andFloorNumber:(NSNumber*)floorNumber andDoorbell:(NSString*)doorbel andRegion:(NSString*)region andLatitude:(NSString*)latitude andLongitude:(NSString*)longitude andNotes:(NSString*)notes;
- (NSDictionary*)getAddress;
- (NSDictionary*)editAddress:(NSString*)friendlyName andAddressName:(NSString*)addressName andAddressNumber:(NSString*)addressNumber andPostalCode:(NSString*)postalCode andFloorNumber:(NSNumber*)floorNumber andDoorbell:(NSString*)doorbel andRegion:(NSString*)region andLatitude:(NSString*)latitude andLongitude:(NSString*)longitude andNotes:(NSString*)notes andUuid:(NSString*)uuid;
- (NSDictionary*)deleteAddress:(NSString*)uuid;
- (NSDictionary*)redeemCoupon:(NSString*)id andUuid:(NSString*)uuid;
- (NSDictionary*)forgotPasswordWithId:(NSString*)id andConfCode:(NSString*)confCode andOtpUuid:(NSString*)otpUuid;
- (NSDictionary*)resetPasswordWithPassword:(NSString*)password andConfCode:(NSString*)confCode andOtpUuid:(NSString*)otpUuid andConfToken:(NSString*)confToken;
- (NSDictionary*)requestOtpWithMsisdn:(NSString*)msisdn andScope:(NSString*)scope;
- (NSDictionary*)retrieveMultilingualMerchantsWithCategories:(NSArray*)categories andDefaultShown:(NSNumber*)defaultShown andCenter:(NSNumber*)center andTags:(NSArray*)tags andUuid:(NSString*)uuid andDistance:(NSNumber*)distance;
@end
#endif /* MyApi_h */
//
// MyApi.m
// warplyFramework
//
// Created by Βασιλης Σκουρας on 8/12/21.
//
#import <Foundation/Foundation.h>
#import "MyApi.h"
#import "Warply.h"
#import <warplySDKFrameworkIOS/warplySDKFrameworkIOS-Swift.h>
@implementation MyApi
NSString *WARP_PRODUCTION_BASE_URL = @"https://engage.warp.ly";
NSString *WARP_HOST = @"engage.warp.ly";
NSString *WARP_ERROR_DOMAIN = @"engage.warp.ly";
NSString *MERCHANT_ID;
NSString *LANG;
+ (void)init:(NSDictionary *)launchOptions uuid:(NSString*)uuid merchantId:(NSString*)merchantId lang:(NSString*)lang{
#if (DEBUG == 1)
[Warply launchWithAppUUID:uuid launchOptions:launchOptions];
#else
[Warply launchWithAppUUID:uuid launchOptions:launchOptions];
#endif
[[Warply sharedService].pushManager registerForRemoteNotifications];
[[Warply sharedService].pushManager resetBadge];
MERCHANT_ID = merchantId;
LANG = lang;
}
- (void) setToStage {
WARP_PRODUCTION_BASE_URL = @"https://engage-stage.warp.ly";
WARP_HOST = @"engage-stage.warp.ly";
WARP_ERROR_DOMAIN = @"engage-stage.warp.ly";
}
- (UIViewController *) openProfile:(UIViewController*)controller :(UIWindow*) window {
UIViewController *profileViewController = [ProfileViewInterface profileViewController];
// controller = [[UINavigationController alloc]initWithRootViewController:profileViewController];
// [window makeKeyAndVisible];
return profileViewController;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[[Warply sharedService] applicationDidEnterBackground];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)applicationWillEnterForeground:(UIApplication *)application
{
[[Warply sharedService] applicationWillEnterForeground];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[[Warply sharedService] applicationDidBecomeActive];
[[Warply sharedService].pushManager resetBadge];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)applicationWillTerminate:(UIApplication *)application
{
[[Warply sharedService] applicationWillTerminate];
}
//#pragma mark - UIApplicationDelegate/RemoteNotificationsRegistration
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[[Warply sharedService].pushManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
[[Warply sharedService].pushManager didFailToRegisterForRemoteNotificationsWithError:error];
}
//#pragma mark - UIApplicationDelegate/Notifications
///////////////////////////////////////////////////////////////////////////////////////////////////
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
[[Warply sharedService].pushManager application:application didReceiveRemoteNotification:userInfo];
[[Warply sharedService].pushManager resetBadge];
}
- (NSMutableArray *)getProducts:(NSString *) filter {
__block NSMutableArray *prods = [NSMutableArray alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] getProductsWithSuccessBlock:filter :^(NSMutableArray *products) {
prods = products;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
prods = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return prods;
}
-(NSMutableArray*)sendContact:(NSString*)name email:(NSString*)email msisdn:(NSString*)msisdn message:(NSString*)message{
__block NSMutableArray *resp = [NSMutableArray alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] sendContactWithSuccessBlock:name andEmail:email andMsisdn:msisdn andMessage:message :^(NSMutableArray *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSMutableArray *)getContentWithCategory:(NSString *)category tags:(NSArray *)tags {
__block NSMutableArray *cont = [NSMutableArray alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] getContentWithCategoryWithSuccessBlock:category andTags:tags :^(NSMutableArray *content) {
cont = content;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
cont = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return cont;
}
- (NSMutableArray *)getMerchantCategories {
__block NSMutableArray *cats = [NSMutableArray alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] getMerchantCategoriesWithSuccessBlock :^(NSMutableArray *categories) {
cats = categories;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
cats = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return cats;
}
- (NSMutableArray *)getMerchants {
__block NSMutableArray *mers = [NSMutableArray alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] getMerchantsWithSuccessBlock:^(NSMutableArray *merchants) {
mers = merchants;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
mers = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return mers;
}
- (NSMutableArray *)getTagsCategories {
__block NSMutableArray *categories = [NSMutableArray alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] getTagsCategoriesWithSuccessBlock :^(NSMutableArray *tagsCategories) {
categories = tagsCategories;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
categories = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return categories;
}
- (NSMutableArray *)getTags {
__block NSMutableArray *tgs = [NSMutableArray alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] getTagsWithSuccessBlock :^(NSMutableArray *tags) {
tgs = tags;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
tgs = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return tgs;
}
- (NSDictionary *)login:(NSString *)id password:(NSString *)password loginType:(NSString*) loginType{
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] loginWithSuccessBlock:id andPassword:password andLoginType:loginType:^(NSDictionary *response) {
if ([[response objectForKey:@"status"] isEqual:@1]) {
NSString* clientId = [NSString alloc];
clientId = [response objectForKey:@"client_id"];
NSString* clientSecret = [NSString alloc];
clientSecret = [response objectForKey:@"client_secret"];
[[Warply sharedService] webAuthorizeWithSuccessBlock:response andId:id andLoginType:loginType :^(NSDictionary *response) {
[[Warply sharedService] tokenWithSuccessBlock:response andClientId:clientId andClientSecret:clientSecret andLoginType:loginType :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
} failureBlock:^(NSError *error){
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
} else {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary *)register:(NSString *)id password:(NSString *)password name:(NSString*)name email:(NSString*)email segmentation:(NSNumber*)segmentation newsletter:(NSNumber*)newsletter {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] registerWithSuccessBlock:id andPassword:password andName:(NSString*)name andEmail:(NSString*)email andSegmentation:(NSNumber*)segmentation andNewsletter:(NSNumber*)newsletter :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary *)registerAutoLogin:(NSString *)id password:(NSString *)password name:(NSString*)name email:(NSString*)email segmentation:(NSNumber*)segmentation newsletter:(NSNumber*)newsletter loginType:(NSString*)loginType {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] registerWithSuccessBlock:id andPassword:password andName:(NSString*)name andEmail:(NSString*)email andSegmentation:(NSNumber*)segmentation andNewsletter:(NSNumber*)newsletter :^(NSDictionary *response) {
if ([[response objectForKey:@"status"] isEqual:@1]) {
[[Warply sharedService] loginWithSuccessBlock:id andPassword:password andLoginType:loginType:^(NSDictionary *response) {
NSString* clientId = [NSString alloc];
clientId = [response objectForKey:@"client_id"];
NSString* clientSecret = [NSString alloc];
clientSecret = [response objectForKey:@"client_secret"];
[[Warply sharedService] webAuthorizeWithSuccessBlock:response andId:id andLoginType:loginType :^(NSDictionary *response) {
[[Warply sharedService] tokenWithSuccessBlock:response andClientId:clientId andClientSecret:clientSecret andLoginType:loginType :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
} failureBlock:^(NSError *error){
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary *)refreshToken {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] refreshToken:^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary *)changePassword:(NSString *)oldPassword newPassword:(NSString *)newPassword {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] changePasswordWithSuccessBlock:oldPassword andNewPassword:newPassword :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary *)getProfile {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] getProfileWithSuccessBlock:^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary *)editProfile:(NSString*)firstname andLastname:(NSString*)lastname andEmail:(NSString *)email andSalutation:(NSString *)salutation andMsisdn:(NSString *)msisdn andNickname:(NSString *)nickname andGender:(NSString *)gender andBirthday:(NSString *)birthday andNameDay:(NSString *)nameday andTaxID:(NSString *)taxid andProfileMetadata:(NSDictionary *)profileMetadata optin:(NSNumber *)optin newsLetter:(NSNumber *)newsletter andSMS:(NSNumber *)sms andSegmentation:(NSNumber *)segmentation andSMSSegmentation:(NSNumber *)smsSegmentation{
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] editProfileWithSuccessBlock:firstname andLastName:lastname andEmail:email andSalutation:salutation andMsisdn:msisdn andNickname:nickname andGender:gender andBirthday:birthday andNameDay:nameday andTaxID:taxid andProfileMetadata:profileMetadata optin:optin newsLetter:newsletter andSMS:sms andSegmentation:segmentation andSMSSegmentation:smsSegmentation :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary *)changeProfileImage:(NSString*)image andUserId:(NSString*)userId {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] changeProfileImageWithSuccessBlock:image andUserId:userId :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary*) addCard:(NSString*)number andCardIssuer:(NSString*)cardIssuer andCardHolder:(NSString*)cardHolder andExpirationMonth:(NSString*)expirationMonth andExpirationYear:(NSString*)expirationYear {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] addCardWithSuccessBlock:number andCardIssuer:cardIssuer andCardHolder:cardHolder andExpirationMonth:expirationMonth andExpirationYear:expirationYear :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary*) getCards {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] getCardsWithSuccessBlock:^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary*) deleteCard:(NSString*)token {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] deleteCardWithSuccessBlock:token :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary*) verifyTicket:(NSString*)guid ticket:(NSString*)ticket {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] verifyTicketWithSuccessBlock:guid :ticket :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary*) getCoupons {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] getCouponsWithSuccessBlock:^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary*) getTransactionHistory {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] getTransactionHistoryWithSuccessBlock:^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary*) getPointsHistory {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] getPointsHistoryWithSuccessBlock:^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary*)addAddress:(NSString*)friendlyName andAddressName:(NSString*)addressName andAddressNumber:(NSString*)addressNumber andPostalCode:(NSString*)postalCode andFloorNumber:(NSNumber*)floorNumber andDoorbell:(NSString*)doorbel andRegion:(NSString*)region andLatitude:(NSString*)latitude andLongitude:(NSString*)longitude andNotes:(NSString*)notes {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] addAddressWithSuccessBlock:friendlyName :addressName :addressNumber :postalCode :floorNumber :doorbel :region :latitude :longitude :notes :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary*)getAddress{
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] getAddressWithSuccessBlock:^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary*)editAddress:(NSString*)friendlyName andAddressName:(NSString*)addressName andAddressNumber:(NSString*)addressNumber andPostalCode:(NSString*)postalCode andFloorNumber:(NSNumber*)floorNumber andDoorbell:(NSString*)doorbel andRegion:(NSString*)region andLatitude:(NSString*)latitude andLongitude:(NSString*)longitude andNotes:(NSString*)notes andUuid:(NSString*)uuid {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] editAddressWithSuccessBlock:friendlyName andAddressName:addressName andAddressNumber:addressNumber andPostalCode:postalCode andFloorNumber:floorNumber andDoorbel:doorbel andRegion:region andLatitude:latitude andLongitude:longitude andNotes:notes andUuid:uuid :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary*)deleteAddress:(NSString*)uuid{
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] deleteAddressWithSuccessBlock:uuid :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary*)redeemCoupon:(NSString*)id andUuid:(NSString*)uuid {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] redeemCouponWithSuccessBlock:id andUuid:uuid :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary*)forgotPasswordWithId:(NSString*)id andConfCode:(NSString*)confCode andOtpUuid:(NSString*)otpUuid {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] forgotPasswordWithIdWithSuccessBlock:id andConfCode:confCode andOtpUuid:otpUuid :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary*)resetPasswordWithPassword:(NSString*)password andConfCode:(NSString*)confCode andOtpUuid:(NSString*)otpUuid andConfToken:(NSString*)confToken {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] resetPasswordWithPasswordWithSuccessBlock:password andConfCode:confCode andOtpUuid:otpUuid andConfToken:confToken :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary*)requestOtpWithMsisdn:(NSString*)msisdn andScope:(NSString*)scope {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] requestOtpWithMsisdnWithSuccessBlock:msisdn andScope:scope :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
- (NSDictionary*)retrieveMultilingualMerchantsWithCategories:(NSArray*)categories andDefaultShown:(NSNumber*)defaultShown andCenter:(NSNumber*)center andTags:(NSArray*)tags andUuid:(NSString*)uuid andDistance:(NSNumber*)distance {
__block NSDictionary *resp = [NSDictionary alloc];
__block BOOL isRunLoopNested = NO;
__block BOOL isOperationCompleted = NO;
[[Warply sharedService] retrieveMultilingualMerchantsWithCategoriesWithSuccessBlock:categories andDefaultShown:defaultShown andCenter:center andTags:tags andUuid:uuid andDistance:distance :^(NSDictionary *response) {
resp = response;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
} failureBlock:^(NSError *error) {
NSLog(@"%@", error);
resp = nil;
isOperationCompleted = YES;
if (isRunLoopNested) {
CFRunLoopStop(CFRunLoopGetCurrent()); // CFRunLoopRun() returns
}
}];
if ( ! isOperationCompleted) {
isRunLoopNested = YES;
NSLog(@"Waiting...");
CFRunLoopRun(); // Magic!
isRunLoopNested = NO;
}
return resp;
}
@end
//
// ProfileView.swift
// warplyFramework
//
// Created by Βασιλης Σκουρας on 13/1/22.
//
import SwiftUI
@available(iOS 13.0.0, *)
struct ProfileView: View {
let uiscreen = UIScreen.main.bounds
@State private var bottomRect: CGRect = .zero
var body: some View {
ScrollView {
VStack {
// var instanceOfMyApi = MyApi()
// var myJson = instanceOfMyApi.getProfile() as AnyObject?
ZStack {
Image("logo", bundle: Bundle(identifier:"framework.warp.ly.warplySDKFrameworkIOS"))
.resizable()
.frame(width: self.uiscreen.height * 0.025, height: self.uiscreen.height * 0.02)
.offset(x: -self.uiscreen.width / 2 + self.uiscreen.width * 0.05, y: self.uiscreen.height * 0.04)
Text("Το προφίλ μου")
.frame(width: self.uiscreen.width * 0.8, height: self.uiscreen.height * 0.025, alignment: .center)
.offset( y: self.uiscreen.height * 0.04)
}
.frame(width: self.uiscreen.width)
// Rectangle()
//
// .foregroundStyle(
// .linearGradient(
// colors: [Color.init(UIColor(red: 82.0/255.0, green: 223.0/255.0, blue: 90.0/255.0, alpha: 1.0)), Color.init(UIColor(red: 29.0/255.0, green: 168.0/255.0, blue: 122.0/255.0, alpha: 1.0)), Color.init(UIColor(red: 4.0/255.0, green: 120.0/255.0, blue: 190.0/255.0, alpha: 1.0))],
// startPoint: .leading,
// endPoint: .trailing
// )
// )
//
// .frame(width: self.uiscreen.width * 0.9,
// height: self.uiscreen.height * 0.15,
// alignment: .topLeading)
// .cornerRadius(CGFloat(7))
// .offset(x: self.uiscreen.width * 0.0025, y: self.uiscreen.height * 0.08)
ZStack {
Image("logo", bundle: Bundle(identifier:"framework.warp.ly.warplySDKFrameworkIOS"))
.resizable()
.frame(width: self.uiscreen.height * 0.04, height: self.uiscreen.height * 0.04, alignment: .topLeading)
.cornerRadius(CGFloat(self.uiscreen.height * 0.02))
.offset(x: -self.uiscreen.width / 2 + self.uiscreen.width * 0.14, y: -self.uiscreen.height * 0.07)
Image("logo", bundle: Bundle(identifier:"framework.warp.ly.warplySDKFrameworkIOS"))
.resizable()
.frame(width: self.uiscreen.width * 0.24, height: self.uiscreen.height * 0.038, alignment: .topLeading)
.cornerRadius(CGFloat(self.uiscreen.height * 0.02))
.offset(x: self.uiscreen.width / 2 - self.uiscreen.width * 0.2, y: -self.uiscreen.height * 0.07)
}
Text("Χριστίνα Γεωργίου")
.frame( width: self.uiscreen.width * 0.8, height: self.uiscreen.height * 0.04, alignment: .leading)
.offset(y: -self.uiscreen.height * 0.03)
.foregroundColor(.white)
}
Text("Ενεργά κουπόνια")
.frame(width: self.uiscreen.width * 0.9, alignment: .leading)
// .offset(x: -self.uiscreen.width / 4 + self.uiscreen.width * 0.0025)
}
.frame(width:self.uiscreen.width, height:self.uiscreen.height )
}
}
struct ProfileView_Previews: PreviewProvider {
static var previews: some View {
ProfileView()
}
}
//
// ProfileViewController.swift
// warplyFramework
//
// Created by Βασιλης Σκουρας on 14/1/22.
//
import Foundation
import SwiftUI
@available(iOS 13.0.0, *)
@objc public class ProfileViewInterface : NSObject {
@objc static public func profileViewController() -> UIViewController {
return UIHostingController(rootView: ProfileView())
}
}
# ``WarplySDKFrameworkIOS``
<!--@START_MENU_TOKEN@-->Summary<!--@END_MENU_TOKEN@-->
## Overview
<!--@START_MENU_TOKEN@-->Text<!--@END_MENU_TOKEN@-->
## Topics
### <!--@START_MENU_TOKEN@-->Group<!--@END_MENU_TOKEN@-->
- <!--@START_MENU_TOKEN@-->``Symbol``<!--@END_MENU_TOKEN@-->
\ No newline at end of file
//
// WarplySDKFrameworkIOS.h
// WarplySDKFrameworkIOS
//
// Created by Βασιλης Σκουρας on 1/2/22.
//
#import <Foundation/Foundation.h>
//! Project version number for WarplySDKFrameworkIOS.
FOUNDATION_EXPORT double WarplySDKFrameworkIOSVersionNumber;
//! Project version string for WarplySDKFrameworkIOS.
FOUNDATION_EXPORT const unsigned char WarplySDKFrameworkIOSVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <WarplySDKFrameworkIOS/PublicHeader.h>